File size: 1,257 Bytes
003d203
 
 
0e6c023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
003d203
 
 
e7bef73
 
 
 
0e6c023
 
 
 
 
 
 
 
 
 
 
 
bfe437f
0e6c023
 
 
 
94386db
0e6c023
 
003d203
0e6c023
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import gradio as gr
import spaces
import torch
from loadimg import load_img
from torchvision import transforms
from transformers import AutoModelForImageSegmentation

torch.set_float32_matmul_precision(["high", "highest"][0])

birefnet = AutoModelForImageSegmentation.from_pretrained(
    "ZhengPeng7/BiRefNet", trust_remote_code=True
)
birefnet.to("cuda")

transform_image = transforms.Compose(
    [
        transforms.Resize((1024, 1024)),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ]
)


@spaces.GPU
def rmbg(image,url):
    if image is None : 
        image = url
    image = load_img(image).convert("RGB")
    image_size = image.size
    input_images = transform_image(image).unsqueeze(0).to("cuda")
    # Prediction
    with torch.no_grad():
        preds = birefnet(input_images)[-1].sigmoid().cpu()
    pred = preds[0].squeeze()
    pred_pil = transforms.ToPILImage()(pred)
    mask = pred_pil.resize(image_size)
    image.putalpha(mask)
    return image


rmbg_tab = gr.Interface(fn=rmbg, inputs=["image","text"], outputs=["image"], api_name="rmbg")

demo = gr.TabbedInterface(
    [rmbg_tab],
    ["remove background"],
    title="Utilities that require GPU",
)


demo.launch()