sumit400 commited on
Commit
f7c9712
1 Parent(s): f336de7

initial upload

Browse files
Files changed (2) hide show
  1. app.py +66 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+ from transformers import AutoModelForImageSegmentation
4
+ from PIL import Image
5
+ import requests
6
+ from io import BytesIO
7
+ import gradio as gr
8
+ # Set up CUDA if available
9
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+ torch.set_float32_matmul_precision("high")
11
+
12
+ # Load the model
13
+ birefnet = AutoModelForImageSegmentation.from_pretrained(
14
+ "ZhengPeng7/BiRefNet", trust_remote_code=True
15
+ )
16
+ birefnet.to(device)
17
+
18
+ # Define image transformations
19
+ transform_image = transforms.Compose([
20
+ transforms.Resize((256, 256)),
21
+ transforms.ToTensor(),
22
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
23
+ ])
24
+
25
+
26
+ def load_img(image_path_or_url):
27
+ if image_path_or_url.startswith('http'):
28
+ response = requests.get(image_path_or_url)
29
+ img = Image.open(BytesIO(response.content))
30
+ else:
31
+ img = Image.open(image_path_or_url)
32
+ return img.convert("RGB")
33
+
34
+ def process(image):
35
+ image_size = image.size
36
+ input_images = transform_image(image).unsqueeze(0).to(device)
37
+
38
+ with torch.no_grad():
39
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
40
+
41
+ pred = preds[0].squeeze()
42
+ pred_pil = transforms.ToPILImage()(pred)
43
+ mask = pred_pil.resize(image_size)
44
+
45
+ # Create a new image with transparency
46
+ transparent_image = Image.new("RGBA", image.size)
47
+ transparent_image.paste(image, (0, 0))
48
+ transparent_image.putalpha(mask) # Apply mask to the new image
49
+
50
+ return transparent_image # Return the new transparent image
51
+
52
+ def remove_background_gradio(image):
53
+ processed_img = process(image)
54
+ return processed_img
55
+
56
+
57
+ # Create the Gradio interface with drag-and-drop and paste functionality
58
+ demo = gr.Interface(
59
+ fn=remove_background_gradio,
60
+ inputs=gr.Image(type="pil"), # Remove 'source' argument
61
+ outputs=gr.Image(type="pil"),
62
+ title="RemoveBG",
63
+ description="Upload an image to remove its background (drag-and-drop or upload)."
64
+ )
65
+
66
+ demo.launch(share=True) # Launch the interface and get a shareable link
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ torchvision
4
+ Pillow
5
+ requests
6
+ kornia
7
+ timm
8
+ gradio