WeVi commited on
Commit
d9dd398
·
verified ·
1 Parent(s): b0be711

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -35
app.py CHANGED
@@ -2,40 +2,58 @@ import gradio as gr
2
  from PIL import Image
3
  import torch
4
  import numpy as np
5
- from transformers import U2NetForImageSegmentation, U2NetProcessor
6
-
7
- # Load model and processor
8
- processor = U2NetProcessor.from_pretrained("akhaliq/U-2-Net")
9
- model = U2NetForImageSegmentation.from_pretrained("akhaliq/U-2-Net")
10
-
11
- def remove_background(image: Image.Image) -> Image.Image:
12
- # Convert to RGB
13
- image = image.convert("RGB")
14
-
15
- # Prepare input
16
- inputs = processor(images=image, return_tensors="pt")
17
-
18
- # Run inference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  with torch.no_grad():
20
- outputs = model(**inputs)
21
-
22
- # Get predicted mask
23
- pred = outputs.predictions[0][0]
24
- mask = (pred > 0.5).numpy().astype(np.uint8) * 255
25
- mask_image = Image.fromarray(mask).resize(image.size)
26
-
27
- # Create RGBA image with transparency
28
- result = image.copy()
29
- result.putalpha(mask_image)
30
- return result
31
-
32
- # Gradio UI
33
- interface = gr.Interface(
34
- fn=remove_background,
35
- inputs=gr.Image(type="pil", label="Upload Image"),
36
- outputs=gr.Image(type="pil", label="Image with Transparent Background"),
37
- title="🪄 AI Background Remover (remove.bg Clone)",
38
- description="Removes background from images using U-2-Net model from Hugging Face.",
39
- )
40
 
41
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
2
  from PIL import Image
3
  import torch
4
  import numpy as np
5
+ import os
6
+ from torchvision import transforms
7
+ from u2net import U2NET # Load model class
8
+
9
+ # Load the model (download once, reuse)
10
+ model_path = "u2net.pth"
11
+ if not os.path.exists(model_path):
12
+ import requests
13
+ url = "https://huggingface.co/akhaliq/U-2-Net/resolve/main/u2net.pth"
14
+ with open(model_path, "wb") as f:
15
+ f.write(requests.get(url).content)
16
+
17
+ # Load model to CPU
18
+ net = U2NET(3,1)
19
+ net.load_state_dict(torch.load(model_path, map_location='cpu'))
20
+ net.eval()
21
+
22
+ # Preprocessing
23
+ transform = transforms.Compose([
24
+ transforms.Resize((320,320)),
25
+ transforms.ToTensor(),
26
+ transforms.Normalize([0.485, 0.456, 0.406],
27
+ [0.229, 0.224, 0.225])
28
+ ])
29
+
30
+ # Post-process output mask
31
+ def normalize_prediction(pred):
32
+ ma = torch.max(pred)
33
+ mi = torch.min(pred)
34
+ return (pred - mi) / (ma - mi)
35
+
36
+ # Main background remover function
37
+ def remove_bg(input_image):
38
+ image = input_image.convert("RGB")
39
+ orig_size = image.size
40
+ img_tensor = transform(image).unsqueeze(0)
41
+
42
  with torch.no_grad():
43
+ d1, *_ = net(img_tensor)
44
+ mask = normalize_prediction(d1[0][0])
45
+ mask = mask.squeeze().cpu().numpy()
46
+ mask = Image.fromarray((mask * 255).astype(np.uint8)).resize(orig_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Add alpha channel using mask
49
+ image.putalpha(mask)
50
+ return image
51
+
52
+ # Gradio app
53
+ gr.Interface(
54
+ fn=remove_bg,
55
+ inputs=gr.Image(type="pil", label="Upload Image"),
56
+ outputs=gr.Image(type="pil", label="Transparent PNG"),
57
+ title="🪄 Remove.bg Clone - AI Background Remover",
58
+ description="Upload any image to remove the background using U-2-Net (Hugging Face version)."
59
+ ).launch()