File size: 1,575 Bytes
888c15e b613973 31c0ed8 888c15e ec18915 888c15e c14759a 888c15e aa4568b 888c15e fc5d884 888c15e 97cf485 888c15e aa4568b 888c15e 7ab6643 888c15e 31c0ed8 888c15e 7ab6643 888c15e 7ab6643 31c0ed8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import gradio as gr
import numpy as np
from PIL import Image
from rembg import remove, new_session
# Initialize session with proper settings to prevent cropping
session = new_session("u2net")
bg_removal_kwargs = {
"alpha_matting": False, # Disable advanced features that cause cropping
"session": session,
"only_mask": False,
"post_process_mask": True # Clean edges without cropping
}
def remove_background(input_image):
try:
# Convert any input to PIL Image
if isinstance(input_image, np.ndarray):
img = Image.fromarray(input_image)
elif isinstance(input_image, dict): # Handle paste/drop
img = Image.open(input_image["name"])
else:
img = input_image
# Preserve original size (disable auto-resizing)
result = remove(img, **bg_removal_kwargs)
return result
except Exception as e:
print(f"Error: {str(e)}")
return input_image # Return original if fails
# Gradio interface with proper image handling
with gr.Blocks() as demo:
gr.Markdown("## 🖼️ Background Remover (No Cropping)")
with gr.Row():
input_img = gr.Image(
label="Original",
type="pil", # Ensures we get PIL Images
height=400
)
output_img = gr.Image(
label="Result",
type="pil",
height=400
)
gr.Button("Remove Background").click(
remove_background,
inputs=input_img,
outputs=output_img
)
demo.launch() |