OriLib commited on
Commit
a3f48ee
1 Parent(s): 584189d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def fn(image):
24
+ im = load_img(image, output_type="pil")
25
+ im = im.convert("RGB")
26
+ origin = im.copy()
27
+ image = process(im)
28
+ return (image, origin)
29
+
30
+ @spaces.GPU
31
+ def process(image):
32
+ image_size = image.size
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
42
+
43
+ def process_file(f):
44
+ name_path = f.rsplit(".",1)[0]+".png"
45
+ im = load_img(f, output_type="pil")
46
+ im = im.convert("RGB")
47
+ transparent = process(im)
48
+ transparent.save(name_path)
49
+ return name_path
50
+
51
+ slider1 = ImageSlider(label="birefnet", type="pil")
52
+ slider2 = ImageSlider(label="birefnet", type="pil")
53
+ image = gr.Image(label="Upload an image")
54
+ image2 = gr.Image(label="Upload an image",type="filepath")
55
+ text = gr.Textbox(label="Paste an image URL")
56
+ png_file = gr.File(label="output png file")
57
+
58
+
59
+ chameleon = load_img("butterfly.jpg", output_type="pil")
60
+
61
+ url = "http://farm9.staticflickr.com/8488/8228323072_76eeddfea3_z.jpg"
62
+ # url = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg"
63
+ tab1 = gr.Interface(
64
+ fn, inputs=image, outputs=slider1, examples=[chameleon], api_name="image"
65
+ )
66
+
67
+ tab2 = gr.Interface(fn, inputs=text, outputs=slider2, examples=[url], api_name="text")
68
+ tab3 = gr.Interface(process_file, inputs=image2, outputs=png_file, examples=["butterfly.jpg"], api_name="png")
69
+
70
+
71
+ demo = gr.TabbedInterface(
72
+ [tab1, tab2,tab3], ["image", "text","png"], title="birefnet for background removal"
73
+ )
74
+
75
+ if __name__ == "__main__":
76
+ demo.launch(show_error=True)