Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,25 @@
|
|
| 1 |
-
import
|
| 2 |
import numpy as np
|
| 3 |
-
from PIL import Image
|
| 4 |
-
from rembg import new_session
|
| 5 |
-
from skimage import restoration
|
| 6 |
|
| 7 |
-
# Initialize
|
| 8 |
session = new_session("isnet-general-use")
|
| 9 |
|
| 10 |
-
def
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 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
|
| 40 |
|
| 41 |
-
# Gradio interface
|
| 42 |
with gr.Blocks() as demo:
|
| 43 |
-
gr.Markdown("##
|
| 44 |
with gr.Row():
|
| 45 |
-
input_img = gr.Image(label="Input", type="pil"
|
| 46 |
output_img = gr.Image(label="Output", type="pil")
|
| 47 |
-
gr.Button("
|
| 48 |
|
| 49 |
-
demo.launch(
|
|
|
|
| 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()
|