Janeka commited on
Commit
3d0fa07
·
verified ·
1 Parent(s): 232d27c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -44
app.py CHANGED
@@ -1,55 +1,49 @@
1
- import gradio as gr
2
  import numpy as np
3
- from PIL import Image
4
- from rembg import remove, new_session
 
5
 
6
- # Initialize session with proper settings to prevent cropping
7
- session = new_session("u2net")
8
- bg_removal_kwargs = {
9
- "alpha_matting": False, # Disable advanced features that cause cropping
10
- "session": session,
11
- "only_mask": False,
12
- "post_process_mask": True # Clean edges without cropping
13
- }
14
 
15
- def remove_background(input_image):
16
  try:
17
- # Convert any input to PIL Image
18
- if isinstance(input_image, np.ndarray):
19
- img = Image.fromarray(input_image)
20
- elif isinstance(input_image, dict): # Handle paste/drop
21
- img = Image.open(input_image["name"])
22
- else:
23
- img = input_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Preserve original size (disable auto-resizing)
26
- result = remove(img, **bg_removal_kwargs)
27
  return result
28
-
29
  except Exception as e:
30
- print(f"Error: {str(e)}")
31
- return input_image # Return original if fails
32
 
33
- # Gradio interface with proper image handling
34
  with gr.Blocks() as demo:
35
- gr.Markdown("## 🖼️ Background Remover (No Cropping)")
36
-
37
  with gr.Row():
38
- input_img = gr.Image(
39
- label="Original",
40
- type="pil", # Ensures we get PIL Images
41
- height=400
42
- )
43
- output_img = gr.Image(
44
- label="Result",
45
- type="pil",
46
- height=400
47
- )
48
-
49
- gr.Button("Remove Background").click(
50
- remove_background,
51
- inputs=input_img,
52
- outputs=output_img
53
- )
54
 
55
- demo.launch()
 
1
+ import cv2
2
  import numpy as np
3
+ from PIL import Image, ImageFilter
4
+ from rembg import new_session
5
+ from skimage import restoration
6
 
7
+ # Initialize ISNet (best free-tier detail model)
8
+ session = new_session("isnet-general-use")
 
 
 
 
 
 
9
 
10
+ def perfect_remove_bg(img):
11
  try:
12
+ # Convert input
13
+ if isinstance(img, np.ndarray):
14
+ img = Image.fromarray(img)
15
+
16
+ # Preserve original size
17
+ w, h = img.size
18
+
19
+ # Step 1: Initial removal
20
+ result = remove(
21
+ img,
22
+ session=session,
23
+ alpha_matting=False, # Disable auto-crop
24
+ post_process_mask=True
25
+ )
26
+
27
+ # Step 2: Edge refinement (CPU-only)
28
+ mask = np.array(result.split()[-1]) # Extract alpha
29
+ mask = restoration.denoise_tv_chambolle(mask, weight=0.1) # Smooth edges
30
+ mask = (mask * 255).astype(np.uint8)
31
+
32
+ # Step 3: Apply refined mask
33
+ result.putalpha(Image.fromarray(mask).resize((w,h)))
34
 
 
 
35
  return result
36
+
37
  except Exception as e:
38
+ print(f"Error: {e}")
39
+ return img
40
 
41
+ # Gradio interface
42
  with gr.Blocks() as demo:
43
+ gr.Markdown("## Free Detail-Preserving BG Remover")
 
44
  with gr.Row():
45
+ input_img = gr.Image(label="Input", type="pil", sources=["upload"])
46
+ output_img = gr.Image(label="Output", type="pil")
47
+ gr.Button("Process").click(perfect_remove_bg, inputs=input_img, outputs=output_img)
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ demo.launch(show_error=True)