Sirapatrwan commited on
Commit
5410b69
Β·
verified Β·
1 Parent(s): 4c7abac

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
15
+ birefnet.to(device)
16
+ transform_image = transforms.Compose(
17
+ [
18
+ transforms.Resize((1024, 1024)),
19
+ transforms.ToTensor(),
20
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
21
+ ]
22
+ )
23
+
24
+
25
+ # @spaces.GPU
26
+ def fn(image):
27
+ im = load_img(image, output_type="pil")
28
+ im = im.convert("RGB")
29
+ image_size = im.size
30
+ origin = im.copy()
31
+ image = load_img(im)
32
+ input_images = transform_image(image).unsqueeze(0).to(device)
33
+ # Prediction
34
+ with torch.no_grad():
35
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
36
+ pred = preds[0].squeeze()
37
+ pred_pil = transforms.ToPILImage()(pred)
38
+ mask = pred_pil.resize(image_size)
39
+ image.putalpha(mask)
40
+ # return (image, origin)
41
+ image.save("img.png","PNG")
42
+ return (image , "img.png")
43
+
44
+
45
+ img1 = gr.Image(type= "pil", image_mode="RGBA")
46
+ image = gr.Image(label="Upload an image")
47
+ file = gr.File()
48
+
49
+
50
+ chameleon = load_img("chameleon.jpg", output_type="pil")
51
+
52
+ url = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg"
53
+ demo = gr.Interface(
54
+ fn, inputs=image, outputs=[img1,file], 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 (WIP πŸ› οΈ, works for linux)"
62
+ # )
63
+
64
+ if __name__ == "__main__":
65
+ demo.launch()