File size: 5,129 Bytes
4b2e55f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25fd03
1ba239b
 
 
4b2e55f
 
 
 
1ba239b
 
4b2e55f
 
 
1ba239b
 
 
4b2e55f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba239b
4b2e55f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
#######################################################################################
#
# MIT License
#
# Copyright (c) [2025] [leonelhs@gmail.com]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#######################################################################################

# This file implements an API endpoint for DIS background image removal system.
#
# Source code is based on or inspired by several projects.
# For more details and proper attribution, please refer to the following resources:
#
# - [DIS] - [https://github.com/xuebinqin/DIS]

import gradio as gr
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from huggingface_hub import hf_hub_download
from torch.autograd import Variable
from torchvision.transforms.functional import normalize

# project imports
from models.isnet import ISNetDIS

REPO_ID = "leonelhs/removators"

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

net = ISNetDIS()

model_path = hf_hub_download(repo_id=REPO_ID, filename='isnet.pth')
net.load_state_dict(torch.load(model_path, map_location=device))
net.to(device)
net.eval()

def im_preprocess(im,size):
    if len(im.shape) < 3:
        im = im[:, :, np.newaxis]
    if im.shape[2] == 1:
        im = np.repeat(im, 3, axis=2)
    im_tensor = torch.tensor(im.copy(), dtype=torch.float32)
    im_tensor = torch.transpose(torch.transpose(im_tensor,1,2),0,1)
    if len(size)<2:
        return im_tensor, im.shape[0:2]
    else:
        im_tensor = torch.unsqueeze(im_tensor,0)
        im_tensor = F.interpolate(im_tensor, size, mode="bilinear")
        im_tensor = torch.squeeze(im_tensor,0)

    return im_tensor.type(torch.uint8), im.shape[0:2]


def predict(image):
    """
        Remove the background from an image.
        The function extracts the foreground and generates both a background-removed
        image and a binary mask.

        Parameters:
            image (string): File path to the input image.
        Returns:
            paths (tuple): paths for background-removed image and cutting mask.
    """

    im_tensor, shapes = im_preprocess(image, [1024, 1024])
    shapes = torch.from_numpy(np.array(shapes)).unsqueeze(0)

    im_tensor = torch.divide(im_tensor, 255.0)
    im_tensor = normalize(im_tensor, mean=[0.5, 0.5, 0.5], std=[1.0, 1.0, 1.0]).unsqueeze(0)
    im_tensor_v = Variable(im_tensor, requires_grad=False)  # wrap inputs in Variable
    ds_val = net(im_tensor_v)[0]  # list of 6 results
    prediction = ds_val[0][0, :, :, :]  # B x 1 x H x W    # we want the first one which is the most accurate prediction
    ## recover the prediction spatial size to the original image size
    size = (shapes[0][0], shapes[0][1])
    prediction = F.interpolate(torch.unsqueeze(prediction, 0), size, mode='bilinear')
    prediction = torch.squeeze(prediction)

    ma = torch.max(prediction)
    mi = torch.min(prediction)
    prediction = (prediction - mi) / (ma - mi)  # max = 1

    torch.cuda.empty_cache()
    mask = (prediction.detach().cpu().numpy() * 255).astype(np.uint8)  # it is the mask we need

    mask = Image.fromarray(mask).convert('L')
    image_rgb = Image.fromarray(image).convert("RGB")
    image_rgb.putalpha(mask)
    return image_rgb, mask

article = "<div><center>Unofficial demo from:<a href='https://github.com/xuebinqin/DIS'>DIS</<></center></div>"

with gr.Blocks(title="DIS") as app:
    gr.Markdown("## Dichotomous Image Segmentation")
    with gr.Row():
        with gr.Column(scale=1):
            inp = gr.Image(type="numpy", label="Upload Image")
            btn_predict = gr.Button("Remove background")
        with gr.Column(scale=2):
            with gr.Row():
                with gr.Column(scale=1):
                    out = gr.Image(type="filepath", label="Output image")
                    with gr.Accordion("See intermediates", open=False):
                        out_mask = gr.Image(type="filepath", label="Mask")

    btn_predict.click(predict, inputs=inp, outputs=[out, out_mask])
    gr.HTML(article)

app.launch(share=False, debug=True, show_error=True, mcp_server=True, pwa=True)
app.queue()