Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,2 +1,65 @@
|
|
1 |
-
import
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from gradio_imageslider import ImageSlider
|
3 |
+
from loadimg import load_img
|
4 |
+
import spaces
|
5 |
+
from transformers import AutoModelForImageSegmentation
|
6 |
+
import torch
|
7 |
+
from torchvision import transforms
|
8 |
+
|
9 |
+
torch.set_float32_matmul_precision(["high", "highest"][0])
|
10 |
+
|
11 |
+
birefnet = AutoModelForImageSegmentation.from_pretrained(
|
12 |
+
"ZhengPeng7/BiRefNet", trust_remote_code=True
|
13 |
+
)
|
14 |
+
birefnet.to("cuda")
|
15 |
+
transform_image = transforms.Compose(
|
16 |
+
[
|
17 |
+
transforms.Resize((1024, 1024)),
|
18 |
+
transforms.ToTensor(),
|
19 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
20 |
+
]
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
@spaces.GPU
|
25 |
+
def fn(image):
|
26 |
+
if image is None or len(image) == 0:
|
27 |
+
return image
|
28 |
+
im = load_img(image, output_type="pil")
|
29 |
+
im = im.convert("RGB")
|
30 |
+
image_size = im.size
|
31 |
+
origin = im.copy()
|
32 |
+
image = load_img(im)
|
33 |
+
input_images = transform_image(image).unsqueeze(0).to("cuda")
|
34 |
+
# Prediction
|
35 |
+
with torch.no_grad():
|
36 |
+
preds = birefnet(input_images)[-1].sigmoid().cpu()
|
37 |
+
pred = preds[0].squeeze()
|
38 |
+
pred_pil = transforms.ToPILImage()(pred)
|
39 |
+
mask = pred_pil.resize(image_size)
|
40 |
+
image.putalpha(mask)
|
41 |
+
return (image, origin)
|
42 |
+
|
43 |
+
|
44 |
+
slider1 = ImageSlider(label="birefnet", type="pil")
|
45 |
+
slider2 = ImageSlider(label="birefnet", type="pil")
|
46 |
+
image = gr.Image(label="Upload an image")
|
47 |
+
text = gr.Textbox(label="Paste an image URL")
|
48 |
+
|
49 |
+
|
50 |
+
chameleon = load_img("butterfly.jpg", output_type="pil")
|
51 |
+
|
52 |
+
url = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg"
|
53 |
+
tab1 = gr.Interface(
|
54 |
+
fn, inputs=image, outputs=slider1, examples=[chameleon], api_name="image"
|
55 |
+
)
|
56 |
+
|
57 |
+
tab2 = gr.Interface(fn, inputs=text, outputs=slider2, examples=[url], api_name="text")
|
58 |
+
|
59 |
+
|
60 |
+
demo = gr.TabbedInterface(
|
61 |
+
[tab1, tab2], ["image", "text"], title="birefnet for background removal"
|
62 |
+
)
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
demo.launch()
|