Janeka commited on
Commit
a41cfa7
·
verified ·
1 Parent(s): b613973

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -23
app.py CHANGED
@@ -3,41 +3,47 @@ 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(
 
3
  from PIL import Image
4
  from rembg import remove, new_session
5
 
6
+ # Initialize model with NO cropping
7
  session = new_session("u2net")
 
 
 
 
 
 
8
 
9
+ def remove_background(img):
10
  try:
11
+ # Convert to PIL if needed (preserves original size)
12
+ if isinstance(img, np.ndarray):
13
+ img = Image.fromarray(img)
14
+ elif isinstance(img, dict): # Handle file uploads
15
+ img = Image.open(img["name"])
 
 
16
 
17
+ # Get original dimensions
18
+ original_size = img.size
19
+
20
+ # Process WITHOUT cropping
21
+ result = remove(
22
+ img,
23
+ session=session,
24
+ alpha_matting=False, # Disable auto-crop
25
+ only_mask=False,
26
+ post_process_mask=False # Disable post-processing that may crop
27
+ )
28
+
29
+ # Force result to original size
30
+ if result.size != original_size:
31
+ result = result.resize(original_size, Image.LANCZOS)
32
+
33
  return result
34
 
35
  except Exception as e:
36
+ print(f"Error: {e}")
37
+ return img # Return original if fails
38
 
39
+ # Gradio interface with size preservation
40
  with gr.Blocks() as demo:
41
+ gr.Markdown("## 📸 Background Remover (Original Size)")
42
 
43
  with gr.Row():
44
  input_img = gr.Image(
45
+ label="Original",
46
+ type="filepath", # Better for size preservation
47
  height=400
48
  )
49
  output_img = gr.Image(