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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -37
app.py CHANGED
@@ -1,49 +1,25 @@
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)
 
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 (will auto-download model)
7
  session = new_session("isnet-general-use")
8
 
9
+ def remove_bg(image):
10
  try:
11
+ if isinstance(image, np.ndarray):
12
+ image = Image.fromarray(image)
13
+ return remove(image, session=session)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  except Exception as e:
15
  print(f"Error: {e}")
16
+ return image
17
 
 
18
  with gr.Blocks() as demo:
19
+ gr.Markdown("## 🆓 Free Background Remover")
20
  with gr.Row():
21
+ input_img = gr.Image(label="Input", type="pil")
22
  output_img = gr.Image(label="Output", type="pil")
23
+ gr.Button("Remove BG").click(remove_bg, inputs=input_img, outputs=output_img)
24
 
25
+ demo.launch()