Janeka commited on
Commit
a0d6a06
·
verified ·
1 Parent(s): ce25591

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -17
app.py CHANGED
@@ -2,41 +2,135 @@ import gradio as gr
2
  from rembg import remove
3
  from PIL import Image
4
  import numpy as np
 
 
 
 
5
 
6
- def remove_background(input_image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  try:
8
  # Convert to PIL Image if it's a numpy array
9
  if isinstance(input_image, np.ndarray):
10
  input_image = Image.fromarray(input_image)
11
 
 
 
 
12
  # Process with rembg
13
- output = remove(input_image)
 
 
 
 
 
 
 
14
 
15
- # Create mask from alpha channel
16
  if output.mode == 'RGBA':
17
  mask = output.split()[-1]
18
  mask_np = np.array(mask)
 
 
19
  else:
20
  mask_np = np.ones(output.size[::-1], dtype=np.uint8) * 255
21
 
22
- return output, Image.fromarray(mask_np)
 
 
 
 
 
 
 
23
 
24
  except Exception as e:
25
  print(f"Error processing image: {str(e)}")
26
- return None, None
 
 
 
 
 
 
 
27
 
28
  # Create interface
29
- iface = gr.Interface(
30
- fn=remove_background,
31
- inputs=gr.Image(type="pil", label="Input Image"),
32
- outputs=[
33
- gr.Image(type="pil", label="Result with Transparent Background"),
34
- gr.Image(type="pil", label="Segmentation Mask")
35
- ],
36
- title="Background Remover (CPU)",
37
- description="Upload an image to remove the background using U²-Net. Processing takes 5-15 seconds on CPU."
38
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- # Launch with minimal configuration
41
  if __name__ == "__main__":
42
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
2
  from rembg import remove
3
  from PIL import Image
4
  import numpy as np
5
+ import cv2
6
+ from skimage import filters
7
+ import time
8
+ import os
9
 
10
+ # Settings
11
+ MAX_SIZE = 1024 # Maximum dimension for input images
12
+ QUALITY = 90 # Output image quality
13
+
14
+ def enhance_mask(mask):
15
+ """Refine the mask edges for better quality"""
16
+ # Convert to grayscale if needed
17
+ if len(mask.shape) == 3:
18
+ mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
19
+
20
+ # Apply Gaussian blur
21
+ mask = cv2.GaussianBlur(mask, (5, 5), 0)
22
+
23
+ # Threshold to create binary mask
24
+ _, binary_mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
25
+
26
+ # Apply edge refinement
27
+ edges = filters.sobel(binary_mask)
28
+ refined_mask = np.where(edges > 0.1, 255, binary_mask)
29
+
30
+ return refined_mask.astype(np.uint8)
31
+
32
+ def resize_image(img):
33
+ """Resize large images while maintaining aspect ratio"""
34
+ width, height = img.size
35
+ if max(width, height) > MAX_SIZE:
36
+ ratio = MAX_SIZE / max(width, height)
37
+ new_size = (int(width * ratio), int(height * ratio))
38
+ img = img.resize(new_size, Image.LANCZOS)
39
+ return img
40
+
41
+ def remove_background(input_image, post_process=True, alpha_matting=False):
42
+ start_time = time.time()
43
+
44
  try:
45
  # Convert to PIL Image if it's a numpy array
46
  if isinstance(input_image, np.ndarray):
47
  input_image = Image.fromarray(input_image)
48
 
49
+ # Resize if too large
50
+ input_image = resize_image(input_image)
51
+
52
  # Process with rembg
53
+ output = remove(
54
+ input_image,
55
+ post_process=post_process,
56
+ alpha_matting=alpha_matting,
57
+ alpha_matting_foreground_threshold=240,
58
+ alpha_matting_background_threshold=10,
59
+ alpha_matting_erode_size=10
60
+ )
61
 
62
+ # Create enhanced mask
63
  if output.mode == 'RGBA':
64
  mask = output.split()[-1]
65
  mask_np = np.array(mask)
66
+ if post_process:
67
+ mask_np = enhance_mask(mask_np)
68
  else:
69
  mask_np = np.ones(output.size[::-1], dtype=np.uint8) * 255
70
 
71
+ # Apply refined mask
72
+ if post_process:
73
+ output.putalpha(Image.fromarray(mask_np))
74
+
75
+ # Calculate processing time
76
+ proc_time = time.time() - start_time
77
+
78
+ return output, Image.fromarray(mask_np), f"Processed in {proc_time:.2f} seconds"
79
 
80
  except Exception as e:
81
  print(f"Error processing image: {str(e)}")
82
+ return None, None, "Error processing image"
83
+
84
+ # Custom CSS for better UI
85
+ custom_css = """
86
+ .gradio-container { max-width: 900px !important; }
87
+ .output-image { border: 1px solid #e2e8f0 !important; border-radius: 8px !important; }
88
+ .processing-time { font-size: 0.9em; color: #64748b; margin-top: 8px; }
89
+ """
90
 
91
  # Create interface
92
+ with gr.Blocks(css=custom_css) as demo:
93
+ gr.Markdown("""
94
+ # 🖼️ Professional Background Remover
95
+ *Powered by U²-Net with enhanced post-processing*
96
+ """)
97
+
98
+ with gr.Row():
99
+ with gr.Column():
100
+ input_img = gr.Image(label="Upload Image", type="pil", elem_id="input-image")
101
+ with gr.Accordion("Advanced Options", open=False):
102
+ post_process = gr.Checkbox(label="Enhanced Post-Processing", value=True)
103
+ alpha_matting = gr.Checkbox(label="Use Alpha Matting (for fine details)", value=False)
104
+ submit_btn = gr.Button("Remove Background", variant="primary")
105
+
106
+ with gr.Column():
107
+ output_img = gr.Image(label="Result", type="pil", elem_id="output-image")
108
+ output_mask = gr.Image(label="Segmentation Mask", type="pil")
109
+ time_text = gr.Markdown(elem_classes=["processing-time"])
110
+
111
+ # Examples
112
+ gr.Examples(
113
+ examples=[
114
+ os.path.join(os.path.dirname(__file__), "example1.jpg"),
115
+ os.path.join(os.path.dirname(__file__), "example2.png")
116
+ ],
117
+ inputs=input_img,
118
+ outputs=[output_img, output_mask, time_text],
119
+ fn=remove_background,
120
+ cache_examples=True,
121
+ label="Try these examples"
122
+ )
123
+
124
+ submit_btn.click(
125
+ fn=remove_background,
126
+ inputs=[input_img, post_process, alpha_matting],
127
+ outputs=[output_img, output_mask, time_text]
128
+ )
129
 
 
130
  if __name__ == "__main__":
131
+ demo.launch(
132
+ server_name="0.0.0.0",
133
+ server_port=7860,
134
+ show_error=True,
135
+ favicon_path=None
136
+ )