Spaces:
Sleeping
Sleeping
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| import gradio as gr | |
| import os | |
| def refine_edges(image, edge_smoothness=3, blur_radius=2, feather_amount=1, threshold=0.1): | |
| """ | |
| Enhanced edge refinement that specifically targets leftover background pixels | |
| """ | |
| img = image.convert("RGBA") | |
| np_img = np.array(img) | |
| r, g, b, a = cv2.split(np_img) | |
| # Convert parameters | |
| blur_kernel = blur_radius * 2 + 1 | |
| smooth_iterations = edge_smoothness | |
| # 1. Create a strict alpha mask (remove semi-transparent pixels) | |
| _, strict_alpha = cv2.threshold(a, 254, 255, cv2.THRESH_BINARY) | |
| # 2. Find the "edge zone" (area between strict alpha and original alpha) | |
| edge_zone = cv2.bitwise_xor(a, strict_alpha) | |
| # 3. Process only the edge zone | |
| kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) | |
| for _ in range(smooth_iterations): | |
| edge_zone = cv2.morphologyEx(edge_zone, cv2.MORPH_OPEN, kernel) | |
| edge_zone = cv2.morphologyEx(edge_zone, cv2.MORPH_CLOSE, kernel) | |
| # 4. Apply blur only to edge zone | |
| blurred_edge = cv2.GaussianBlur(edge_zone, (blur_kernel, blur_kernel), 0) | |
| # 5. Feathering with thresholding to remove leftover bg | |
| if feather_amount > 0: | |
| edge_mask = (blurred_edge > threshold * 255).astype(np.uint8) * 255 | |
| edge_mask = cv2.erode(edge_mask, np.ones((feather_amount, feather_amount), np.uint8)) | |
| final_edge = cv2.GaussianBlur(edge_mask, (blur_kernel, blur_kernel), 0) | |
| else: | |
| final_edge = blurred_edge | |
| # 6. Combine with strict alpha | |
| new_alpha = cv2.bitwise_or(strict_alpha, final_edge) | |
| # 7. Remove color information from transparent areas | |
| r = r * (new_alpha > 0) | |
| g = g * (new_alpha > 0) | |
| b = b * (new_alpha > 0) | |
| # Recombine channels | |
| result = cv2.merge([r, g, b, new_alpha]) | |
| return Image.fromarray(result) | |
| # Gradio interface | |
| with gr.Blocks(title="✨ Advanced Edge Refiner") as demo: | |
| gr.Markdown(""" | |
| # ✨ Advanced Edge Refiner | |
| Removes leftover background artifacts around hair and fine edges | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_image = gr.Image(type="pil", label="Input Image") | |
| edge_smoothness = gr.Slider(1, 5, value=3, label="Edge Smoothness") | |
| blur_radius = gr.Slider(1, 5, value=2, label="Blur Strength") | |
| feather_amount = gr.Slider(0, 5, value=1, label="Feather Amount") | |
| threshold = gr.Slider(0, 100, value=10, label="Edge Threshold (%)") | |
| submit_btn = gr.Button("Refine Edges", variant="primary") | |
| with gr.Column(): | |
| output_image = gr.Image(type="pil", label="Refined Image") | |
| submit_btn.click( | |
| fn=refine_edges, | |
| inputs=[input_image, edge_smoothness, blur_radius, feather_amount, threshold], | |
| outputs=output_image | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |