File size: 6,958 Bytes
81b1a0e
 
 
 
 
6bafd2d
 
 
ab98f09
6284dc0
 
e797135
6bafd2d
 
 
 
 
63d9326
 
 
 
 
 
 
 
 
 
 
 
6bafd2d
 
 
 
 
 
 
 
5a7c5d5
 
 
 
 
 
6bafd2d
5a7c5d5
6bafd2d
5a7c5d5
6bafd2d
5a7c5d5
6bafd2d
5a7c5d5
6bafd2d
5a7c5d5
6bafd2d
 
 
5a7c5d5
 
 
6bafd2d
 
6be00d8
e797135
63d9326
53ff575
81b1a0e
621c740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bafd2d
621c740
 
 
81b1a0e
0972107
81b1a0e
1592dab
81b1a0e
c36a9d3
 
81b1a0e
 
6284dc0
81b1a0e
 
 
c36a9d3
eeef7f4
 
d967d62
 
 
c36a9d3
0972107
 
cb61e6f
c36a9d3
 
 
6bafd2d
c36a9d3
a0c2c56
0972107
cb61e6f
0972107
6bafd2d
0972107
 
 
6bafd2d
0972107
6bafd2d
 
eeef7f4
6bafd2d
ab98f09
 
6bafd2d
ab98f09
 
6bafd2d
0972107
6bafd2d
eeef7f4
8da09d2
6fc9c48
1ba1ac4
 
 
 
 
 
 
6b21c48
1ba1ac4
 
 
 
 
 
 
 
1f5deb3
1ba1ac4
5a7c5d5
 
6fc9c48
5a7c5d5
 
 
 
 
 
 
 
6fc9c48
 
 
 
 
 
 
1ba1ac4
 
6bafd2d
63d9326
3847cbf
 
97dda91
1f5deb3
3847cbf
 
 
 
 
 
63d9326
3847cbf
 
 
6fc9c48
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import os
import cv2
import numpy as np
import torch
import gradio as gr
import spaces
from gradio.themes.base import Base
from gradio.themes.utils import colors, fonts, sizes
from PIL import Image, ImageOps
from transformers import AutoModelForImageSegmentation
from torchvision import transforms

class WhiteTheme(Base):
    def __init__(
        self,
        *,
        primary_hue: colors.Color | str = colors.orange,
        font: fonts.Font | str | tuple[fonts.Font | str, ...] = (
            fonts.GoogleFont("Inter"),
            "ui-sans-serif",
            "system-ui",
            "sans-serif",
        ),
        font_mono: fonts.Font | str | tuple[fonts.Font | str, ...] = (
            fonts.GoogleFont("Inter"),
            "ui-monospace",
            "system-ui",
            "monospace",
        )
    ):
        super().__init__(
            primary_hue=primary_hue,
            font=font,
            font_mono=font_mono,
        )
        
        self.set(
            # Light mode specific colors
            background_fill_primary="*primary_50",
            background_fill_secondary="white",
            border_color_primary="*primary_300",
            
            # General colors that should stay constant
            body_background_fill="white",
            body_background_fill_dark="white",
            block_background_fill="white",
            block_background_fill_dark="white",
            panel_background_fill="white",
            panel_background_fill_dark="white",
            body_text_color="black",
            body_text_color_dark="black",
            block_label_text_color="black",
            block_label_text_color_dark="black",
            block_border_color="white",
            panel_border_color="white",
            input_border_color="lightgray",
            input_background_fill="white",
            input_background_fill_dark="white",
            shadow_drop="none"
        )

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

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

def refine_foreground(image, mask, r=90):
    if mask.size != image.size:
        mask = mask.resize(image.size)
    image = np.array(image) / 255.0
    mask = np.array(mask) / 255.0
    estimated_foreground = FB_blur_fusion_foreground_estimator_2(image, mask, r=r)
    image_masked = Image.fromarray((estimated_foreground * 255.0).astype(np.uint8))
    return image_masked

def FB_blur_fusion_foreground_estimator_2(image, alpha, r=90):
    alpha = alpha[:, :, None]
    F, blur_B = FB_blur_fusion_foreground_estimator(
        image, image, image, alpha, r)
    return FB_blur_fusion_foreground_estimator(image, F, blur_B, alpha, r=6)[0]

def FB_blur_fusion_foreground_estimator(image, F, B, alpha, r=90):
    if isinstance(image, Image.Image):
        image = np.array(image) / 255.0
    blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None]
    blurred_FA = cv2.blur(F * alpha, (r, r))
    blurred_F = blurred_FA / (blurred_alpha + 1e-5)
    blurred_B1A = cv2.blur(B * (1 - alpha), (r, r))
    blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
    F = blurred_F + alpha * (image - alpha * blurred_F - (1 - alpha) * blurred_B)
    F = np.clip(F, 0, 1)
    return F, blurred_B

class ImagePreprocessor():
    def __init__(self, resolution=(1024, 1024)) -> None:
        self.transform_image = transforms.Compose([
            transforms.Resize(resolution),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406],
                                 [0.229, 0.224, 0.225]),
        ])

    def proc(self, image: Image.Image) -> torch.Tensor:
        image = self.transform_image(image)
        return image

# Load the model
birefnet = AutoModelForImageSegmentation.from_pretrained(
    'zhengpeng7/BiRefNet-matting', trust_remote_code=True)
birefnet.to(device)
birefnet.eval()

def remove_background_wrapper(image):
    if image is None:
        raise gr.Error("Please upload an image.")
    image_ori = Image.fromarray(image).convert('RGB')
    foreground, background, pred_pil, reverse_mask = remove_background(image_ori)
    return foreground, background, pred_pil, reverse_mask

@spaces.GPU
def remove_background(image_ori):
    original_size = image_ori.size
    image_preprocessor = ImagePreprocessor(resolution=(1024, 1024))
    image_proc = image_preprocessor.proc(image_ori)
    image_proc = image_proc.unsqueeze(0)
    
    with torch.no_grad():
        preds = birefnet(image_proc.to(device))[-1].sigmoid().cpu()
    pred = preds[0].squeeze()
    
    pred_pil = transforms.ToPILImage()(pred)
    pred_pil = pred_pil.resize(original_size, Image.BICUBIC)
    
    reverse_mask = ImageOps.invert(pred_pil)
    
    foreground = image_ori.copy()
    foreground.putalpha(pred_pil)
    
    background = image_ori.copy()
    background.putalpha(reverse_mask)
    
    torch.cuda.empty_cache()
    
    return foreground, background, pred_pil, reverse_mask

# Custom CSS for button styling with additional light mode enforcement
custom_css = """
@keyframes gradient-animation {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}

#submit-button {
    background: linear-gradient(
        135deg,
        #e0f7fa, #e8f5e9, #fff9c4, #ffebee,
        #f3e5f5, #e1f5fe, #fff3e0, #e8eaf6
    );
    background-size: 400% 400%;
    animation: gradient-animation 15s ease infinite;
    border-radius: 12px;
    color: black;
}

/* Force light mode styles */
:root, :root[data-theme='light'], :root[data-theme='dark'] {
    --body-background-fill: white !important;
    --background-fill-primary: white !important;
    --background-fill-secondary: white !important;
    --block-background-fill: white !important;
    --panel-background-fill: white !important;
    --body-text-color: black !important;
    --block-label-text-color: black !important;
}

/* Additional overrides for dark mode */
@media (prefers-color-scheme: dark) {
    :root {
        color-scheme: light;
    }
}
"""

with gr.Blocks(css=custom_css, theme=WhiteTheme()) as demo:
    # Interface setup with input and output
    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="numpy", sources=['upload'], label="Upload Image")
            btn = gr.Button("Process Image", elem_id="submit-button")
        with gr.Column():
            output_foreground = gr.Image(type="pil", label="Foreground")
            output_background = gr.Image(type="pil", label="Background")
            output_foreground_mask = gr.Image(type="pil", label="Foreground Mask")
            output_background_mask = gr.Image(type="pil", label="Background Mask")

    # Link the button to the processing function
    btn.click(fn=remove_background_wrapper, inputs=image_input, outputs=[
        output_foreground, output_background, output_foreground_mask, output_background_mask])

    demo.launch(debug=True)