Janeka commited on
Commit
3cd9d3e
·
verified ·
1 Parent(s): 92e0f3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -23
app.py CHANGED
@@ -1,38 +1,40 @@
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 PIL Image to NumPy array
8
- image_np = np.array(image)
9
-
10
- # Check if image has alpha channel
11
- if image_np.shape[2] != 4:
12
- return image # Return original if no alpha channel
13
 
14
- # Separate color and alpha channels
15
- b, g, r, a = cv2.split(image_np)
16
 
17
- # Apply Gaussian blur to alpha channel
18
- a_blurred = cv2.GaussianBlur(a, (5, 5), 0)
19
 
20
- # Apply morphological operations to smooth edges
21
  kernel = np.ones((3, 3), np.uint8)
22
- a_morph = cv2.morphologyEx(a_blurred, cv2.MORPH_OPEN, kernel)
 
 
 
 
 
 
23
 
24
- # Merge channels back
25
- result = cv2.merge((b, g, r, a_morph))
26
 
27
- # Convert back to PIL Image
28
- return Image.fromarray(result)
29
 
 
30
  iface = gr.Interface(
31
- fn=refine_edges,
32
- inputs=gr.Image(type="pil", image_mode="RGBA", label="Upload Transparent PNG"),
33
- outputs=gr.Image(type="pil", image_mode="RGBA", label="Refined Image"),
34
- title="Edge Smoother",
35
- description="Upload a transparent PNG image to refine its edges, especially around hair and fur."
36
  )
37
 
38
  if __name__ == "__main__":
 
1
  import gradio as gr
 
2
  import numpy as np
3
+ import cv2
4
  from PIL import Image
5
 
6
+ def smooth_edges(image: Image.Image):
7
+ # Convert to numpy array
8
+ img_np = np.array(image.convert("RGB"))
 
 
 
 
9
 
10
+ # Create a grayscale version to detect edges
11
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
12
 
13
+ # Detect edges using Canny
14
+ edges = cv2.Canny(gray, threshold1=50, threshold2=150)
15
 
16
+ # Dilate edges a bit to make the mask thicker
17
  kernel = np.ones((3, 3), np.uint8)
18
+ dilated = cv2.dilate(edges, kernel, iterations=1)
19
+
20
+ # Create a mask with blur
21
+ mask = cv2.GaussianBlur(dilated, (11, 11), 0)
22
+
23
+ # Convert mask to 3-channel
24
+ mask_3c = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB) / 255.0
25
 
26
+ # Apply soft blending of edges
27
+ softened = (img_np * (1 - mask_3c) + cv2.GaussianBlur(img_np, (15, 15), 0) * mask_3c).astype(np.uint8)
28
 
29
+ return Image.fromarray(softened)
 
30
 
31
+ # Interface
32
  iface = gr.Interface(
33
+ fn=smooth_edges,
34
+ inputs=gr.Image(type="pil", label="Upload Image (even non-transparent!)"),
35
+ outputs=gr.Image(type="pil", label="Softened Edges"),
36
+ title="Edge Smoother v2",
37
+ description="Smooth the edges of your subject works for normal and background-removed images."
38
  )
39
 
40
  if __name__ == "__main__":