File size: 4,766 Bytes
81b1a0e
 
 
 
 
 
 
b59df1c
81b1a0e
e797135
 
 
6be00d8
e797135
81b1a0e
69b7015
81b1a0e
327742a
 
 
 
 
 
 
81b1a0e
f406b44
81b1a0e
327742a
81b1a0e
 
 
 
 
 
 
 
 
a10635a
 
 
 
 
 
 
 
81b1a0e
d967d62
 
 
 
 
 
 
fbe03e2
e797135
b59df1c
d38161e
1352148
8bcc400
66fad2f
 
1352148
 
8bcc400
 
1352148
b59df1c
8aa2ae3
327742a
 
81b1a0e
 
327742a
81b1a0e
f406b44
81b1a0e
 
 
 
 
 
69b7015
81b1a0e
 
 
 
 
 
 
cf6fe1a
 
440356f
81b1a0e
e797135
81b1a0e
 
fbe03e2
de5ed42
 
 
 
 
 
 
81b1a0e
 
b59df1c
 
 
a10635a
b59df1c
e797135
81b1a0e
 
ec6f3d6
 
81b1a0e
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import os
from glob import glob
import cv2
import numpy as np
from PIL import Image
import torch
from torchvision import transforms
from transformers import AutoModelForImageSegmentation
import gradio as gr
import spaces
from gradio_imageslider import ImageSlider

torch.set_float32_matmul_precision('high')
torch.jit.script = lambda f: f

device = "cuda" if torch.cuda.is_available() else "cpu"


def array_to_pil_image(image, size=(1024, 1024)):
    image = cv2.resize(image, size, interpolation=cv2.INTER_LINEAR)
    image = Image.fromarray(image).convert('RGB')
    return image


class ImagePreprocessor():
    def __init__(self, resolution=(1024, 1024)) -> None:
        self.transform_image = transforms.Compose([
            # transforms.Resize(resolution),    # 1. keep consistent with the cv2.resize used in training 2. redundant with that in path_to_image()
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        ])

    def proc(self, image):
        image = self.transform_image(image)
        return image


usage_to_weights_file = {
    'General': 'BiRefNet',
    'Portrait': 'BiRefNet-portrait',
    'DIS': 'BiRefNet-DIS5K',
    'HRSOD': 'BiRefNet-HRSOD',
    'COD': 'BiRefNet-COD',
    'DIS-TR_TEs': 'BiRefNet-DIS5K-TR_TEs'
}

from transformers import AutoModelForImageSegmentation
weights_path = 'General'
birefnet = AutoModelForImageSegmentation.from_pretrained('/'.join(('zhengpeng7', usage_to_weights_file[weights_path])), trust_remote_code=True)
birefnet.to(device)
birefnet.eval()
birefnet.weights_path = weights_path


@spaces.GPU
def predict(image, resolution, weights_file):
    global birefnet
    if birefnet.weights_path != weights_file:
        # Load BiRefNet with chosen weights
        _weights_file = '/'.join(('zhengpeng7', usage_to_weights_file[weights_file] if weights_file is not None else 'BiRefNet'))
        print('Change weights to:', _weights_file)
        print('\t', weights_file, birefnet.weights_path)
        birefnet = birefnet.from_pretrained(_weights_file)
        birefnet.to(device)
        birefnet.eval()
        birefnet.weights_path = weights_file

    resolution = f"{image.shape[1]}x{image.shape[0]}" if resolution == '' else resolution
    # Image is a RGB numpy array.
    resolution = [int(int(reso)//32*32) for reso in resolution.strip().split('x')]
    images = [image]
    image_shapes = [image.shape[:2] for image in images]
    images = [array_to_pil_image(image, resolution) for image in images]

    image_preprocessor = ImagePreprocessor(resolution=resolution)
    images_proc = []
    for image in images:
        images_proc.append(image_preprocessor.proc(image))
    images_proc = torch.cat([image_proc.unsqueeze(0) for image_proc in images_proc])

    with torch.no_grad():
        scaled_preds_tensor = birefnet(images_proc.to(device))[-1].sigmoid()   # BiRefNet needs an sigmoid activation outside the forward.
    preds = []
    for image_shape, pred_tensor in zip(image_shapes, scaled_preds_tensor):
        if device == 'cuda':
            pred_tensor = pred_tensor.cpu()
        preds.append(torch.nn.functional.interpolate(pred_tensor.unsqueeze(0), size=image_shape, mode='bilinear', align_corners=True).squeeze().numpy())
    image_preds = []
    for image, pred in zip(images, preds):
        image = image.resize(pred.shape[::-1])
        pred = np.repeat(np.expand_dims(pred, axis=-1), 3, axis=-1)
        image_preds.append((pred * image).astype(np.uint8))

    return image, image_preds[0]


examples = [[_] for _ in glob('examples/*')][:]

# Add the option of resolution in a text box.
for idx_example, example in enumerate(examples):
    examples[idx_example].append('1024x1024')
examples.append(examples[-1].copy())
examples[-1][1] = '512x512'

demo = gr.Interface(
    fn=predict,
    inputs=[
        'image',
        gr.Textbox(lines=1, placeholder="Type the resolution (`WxH`) you want, e.g., `512x512`. Higher resolutions can be much slower for inference.", label="Resolution"),
        gr.Radio(list(usage_to_weights_file.keys()), label="Weights", info="Choose the weights you want.")
    ],
    outputs=ImageSlider(),
    examples=examples,
    title='Online demo for `Bilateral Reference for High-Resolution Dichotomous Image Segmentation`',
    description=('Upload a picture, our model will extract a highly accurate segmentation of the subject in it. :)'
                 '\nThe resolution used in our training was `1024x1024`, which is thus the suggested resolution to obtain good results!\n Ours codes can be found at https://github.com/ZhengPeng7/BiRefNet.\n We also maintain the HF model of BiRefNet at https://huggingface.co/ZhengPeng7/birefnet for easier access.')
)
demo.launch(debug=True)