Janeka commited on
Commit
34c6bf6
·
verified ·
1 Parent(s): 31584aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -26
app.py CHANGED
@@ -1,36 +1,107 @@
1
- import gradio as gr
2
  import cv2
3
  import numpy as np
4
  from PIL import Image
 
 
5
 
6
- def refine_edges(image: Image.Image):
7
- # Convert to OpenCV format (RGBA)
8
- image_np = np.array(image)
9
- if image_np.shape[2] == 4:
10
- alpha_channel = image_np[:, :, 3]
11
- else:
12
- return image # Return original if no alpha channel
13
-
14
- # Step 1: Blur the alpha channel
15
- blurred = cv2.GaussianBlur(alpha_channel, (5, 5), 0)
16
 
17
- # Step 2: Morphological refinement
18
- kernel = np.ones((3,3), np.uint8)
19
- refined = cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- # Step 3: Recombine channels
22
- b, g, r = image_np[:, :, 0], image_np[:, :, 1], image_np[:, :, 2]
23
- rgba = cv2.merge((b, g, r, refined))
 
 
 
24
 
25
- return Image.fromarray(rgba)
 
 
 
 
 
 
26
 
27
- iface = gr.Interface(
28
- fn=refine_edges,
29
- inputs=gr.Image(type="pil", image_mode="RGBA"),
30
- outputs="image",
31
- title="Edge Refiner",
32
- description="Upload a background-removed PNG and get smoother edges!"
33
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  if __name__ == "__main__":
36
- iface.launch()
 
 
1
  import cv2
2
  import numpy as np
3
  from PIL import Image
4
+ import gradio as gr
5
+ import os
6
 
7
+ # Create examples directory if it doesn't exist
8
+ os.makedirs("examples", exist_ok=True)
 
 
 
 
 
 
 
 
9
 
10
+ def refine_edges(image, edge_smoothness=3, blur_radius=2, feather_amount=1):
11
+ """
12
+ Refines edges of a transparent PNG image with configurable parameters.
13
+
14
+ Args:
15
+ image: Input image (PIL Image)
16
+ edge_smoothness: Intensity of edge refinement (1-5)
17
+ blur_radius: Kernel size for edge smoothing (1-5)
18
+ feather_amount: Feathering amount at transparency edges (0-5)
19
+
20
+ Returns:
21
+ Refined PIL Image
22
+ """
23
+ img = image.convert("RGBA")
24
+ np_img = np.array(img)
25
+ alpha = np_img[:, :, 3]
26
+
27
+ # Scale parameters
28
+ blur_kernel = blur_radius * 2 + 1 # 3,5,7,9,11
29
+ smooth_iterations = edge_smoothness
30
+ feather_size = feather_amount
31
+
32
+ # Edge smoothing with morphological operations
33
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
34
+ for _ in range(smooth_iterations):
35
+ alpha = cv2.morphologyEx(alpha, cv2.MORPH_OPEN, kernel)
36
+ alpha = cv2.morphologyEx(alpha, cv2.MORPH_CLOSE, kernel)
37
+
38
+ # Gaussian blur for smoother edges
39
+ alpha = cv2.GaussianBlur(alpha, (blur_kernel, blur_kernel), 0)
40
+
41
+ # Feather edges if enabled
42
+ if feather_amount > 0:
43
+ _, mask = cv2.threshold(alpha, 10, 255, cv2.THRESH_BINARY)
44
+ edges = cv2.Canny(mask, 100, 200)
45
+ edges = cv2.dilate(edges, np.ones((feather_size, feather_size), np.uint8), iterations=1)
46
+ alpha_blurred = cv2.GaussianBlur(alpha, (blur_kernel, blur_kernel), 0)
47
+ alpha = np.where(edges > 0, alpha_blurred, alpha)
48
+
49
+ # Re-normalize alpha
50
+ alpha = np.clip(alpha, 0, 255).astype(np.uint8)
51
+ np_img[:, :, 3] = alpha
52
+
53
+ return Image.fromarray(np_img)
54
 
55
+ # Download example images if they don't exist
56
+ example_images = {
57
+ "hair.png": "https://huggingface.co/spaces/sd-org/remove-bg/resolve/main/examples/hair.png",
58
+ "furry_animal.png": "https://huggingface.co/spaces/sd-org/remove-bg/resolve/main/examples/animal.png",
59
+ "glasses.png": "https://huggingface.co/spaces/sd-org/remove-bg/resolve/main/examples/glasses.png"
60
+ }
61
 
62
+ for filename, url in example_images.items():
63
+ if not os.path.exists(f"examples/{filename}"):
64
+ try:
65
+ from urllib.request import urlretrieve
66
+ urlretrieve(url, f"examples/{filename}")
67
+ except:
68
+ print(f"Couldn't download example image: {filename}")
69
 
70
+ # Create Gradio interface
71
+ with gr.Blocks() as demo:
72
+ gr.Markdown("""
73
+ # ✨ Edge Refiner - Clean Up Your Background-Removed Images!
74
+ Refine the edges of images that have already been background-removed (PNGs with transparency).
75
+ """)
76
+
77
+ with gr.Row():
78
+ with gr.Column():
79
+ input_image = gr.Image(type="pil", label="Input Image (Transparent PNG)")
80
+ edge_smoothness = gr.Slider(1, 5, value=3, step=1, label="Edge Smoothness")
81
+ blur_radius = gr.Slider(1, 5, value=2, step=1, label="Blur Radius")
82
+ feather_amount = gr.Slider(0, 5, value=1, step=1, label="Feather Amount")
83
+ submit_btn = gr.Button("Refine Edges")
84
+
85
+ with gr.Column():
86
+ output_image = gr.Image(type="pil", label="Refined Image")
87
+
88
+ gr.Examples(
89
+ examples=[
90
+ ["examples/hair.png", 4, 2, 1],
91
+ ["examples/furry_animal.png", 3, 3, 2],
92
+ ["examples/glasses.png", 2, 1, 0]
93
+ ],
94
+ inputs=[input_image, edge_smoothness, blur_radius, feather_amount],
95
+ outputs=output_image,
96
+ fn=refine_edges,
97
+ cache_examples=True
98
+ )
99
+
100
+ submit_btn.click(
101
+ fn=refine_edges,
102
+ inputs=[input_image, edge_smoothness, blur_radius, feather_amount],
103
+ outputs=output_image
104
+ )
105
 
106
  if __name__ == "__main__":
107
+ demo.launch()