Update app.py
Browse files
app.py
CHANGED
|
@@ -1,25 +1,55 @@
|
|
| 1 |
-
import
|
| 2 |
import numpy as np
|
| 3 |
-
from PIL import Image
|
| 4 |
-
from rembg import
|
|
|
|
| 5 |
|
| 6 |
-
# Initialize
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
def
|
| 10 |
try:
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
except Exception as e:
|
| 15 |
-
print(f"Error: {e}")
|
| 16 |
-
return
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 20 |
with gr.Row():
|
| 21 |
-
input_img = gr.Image(label="
|
| 22 |
-
output_img = gr.Image(label="
|
| 23 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
demo.launch()
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
import numpy as np
|
| 3 |
+
from PIL import Image, ImageFilter
|
| 4 |
+
from rembg import new_session, remove
|
| 5 |
+
from skimage import filters, restoration
|
| 6 |
|
| 7 |
+
# Initialize best free-tier models
|
| 8 |
+
isnet_session = new_session("isnet-general-use") # Best details
|
| 9 |
+
u2net_session = new_session("u2net") # Fallback model
|
| 10 |
|
| 11 |
+
def perfect_remove_bg(img):
|
| 12 |
try:
|
| 13 |
+
# Convert input and preserve original size
|
| 14 |
+
if isinstance(img, np.ndarray):
|
| 15 |
+
img = Image.fromarray(img)
|
| 16 |
+
w, h = img.size
|
| 17 |
+
|
| 18 |
+
# Step 1: Primary removal with ISNet (best details)
|
| 19 |
+
result = remove(img, session=isnet_session)
|
| 20 |
+
|
| 21 |
+
# Step 2: Edge refinement
|
| 22 |
+
mask = np.array(result.split()[-1])
|
| 23 |
+
|
| 24 |
+
# Edge-preserving smoothing
|
| 25 |
+
mask = filters.rank.mean(
|
| 26 |
+
mask.astype(np.uint8),
|
| 27 |
+
np.ones((3,3), np.uint8)
|
| 28 |
+
|
| 29 |
+
# Step 3: Combine with U²Net for confidence areas
|
| 30 |
+
u2net_mask = np.array(remove(img, session=u2net_session).split()[-1]
|
| 31 |
+
final_mask = np.where(u2net_mask > 200, mask, u2net_mask) # Trust U²Net in clear areas
|
| 32 |
+
|
| 33 |
+
# Step 4: Apply refined mask
|
| 34 |
+
result.putalpha(Image.fromarray(final_mask).resize((w,h)))
|
| 35 |
+
|
| 36 |
+
return result
|
| 37 |
+
|
| 38 |
except Exception as e:
|
| 39 |
+
print(f"⚠️ Error: {e}")
|
| 40 |
+
return remove(img, session=u2net_session) # Fallback
|
| 41 |
|
| 42 |
+
# Gradio interface
|
| 43 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 44 |
+
gr.Markdown("""<h1><center>✨ Ultimate Free Background Remover</center></h1>""")
|
| 45 |
with gr.Row():
|
| 46 |
+
input_img = gr.Image(label="Upload", type="pil", height=400)
|
| 47 |
+
output_img = gr.Image(label="Result", type="pil", height=400)
|
| 48 |
+
with gr.Row():
|
| 49 |
+
gr.Button("Remove Background", variant="primary").click(
|
| 50 |
+
perfect_remove_bg,
|
| 51 |
+
inputs=input_img,
|
| 52 |
+
outputs=output_img
|
| 53 |
+
)
|
| 54 |
|
| 55 |
+
demo.launch(show_error=True)
|