Spaces:
Runtime error
Runtime error
File size: 8,151 Bytes
81b1a0e 4adc5f9 6284dc0 ab98f09 6284dc0 e797135 6be00d8 e797135 81b1a0e 53ff575 81b1a0e 621c740 81b1a0e 0972107 81b1a0e 1592dab 81b1a0e 6284dc0 81b1a0e 0972107 d967d62 cb61e6f 8da09d2 0972107 fbe03e2 cb61e6f a0c2c56 0972107 cb61e6f 0972107 1acca69 0972107 741bf59 ab98f09 0972107 a0c2c56 ab98f09 1acca69 0972107 ab98f09 8da09d2 ab98f09 0972107 ab98f09 8da09d2 bca5302 8da09d2 a0829f0 8da09d2 a0c2c56 a0829f0 bca5302 8da09d2 bca5302 a0c2c56 a0829f0 a0c2c56 bca5302 8da09d2 bca5302 8da09d2 0972107 ea720f8 |
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
import os
import cv2
import numpy as np
import torch
import gradio as gr
import spaces
from PIL import Image, ImageOps
from transformers import AutoModelForImageSegmentation
from torchvision import transforms
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
birefnet = AutoModelForImageSegmentation.from_pretrained('zhengpeng7/BiRefNet-matting', trust_remote_code=True)
birefnet.to(device)
birefnet.eval()
@spaces.GPU
def remove_background(image):
if image is None:
raise gr.Error("Please upload an image.")
image_ori = Image.fromarray(image).convert('RGB')
original_size = image_ori.size
# Preprocess the image
image_preprocessor = ImagePreprocessor(resolution=(1024, 1024))
image_proc = image_preprocessor.proc(image_ori)
image_proc = image_proc.unsqueeze(0)
# Prediction
with torch.no_grad():
preds = birefnet(image_proc.to(device))[-1].sigmoid().cpu()
pred = preds[0].squeeze()
# Process Results
pred_pil = transforms.ToPILImage()(pred)
pred_pil = pred_pil.resize(original_size, Image.BICUBIC) # Resize mask to original size
# Create reverse mask
reverse_mask = Image.new('L', original_size)
reverse_mask.paste(ImageOps.invert(pred_pil))
# Create foreground image (object with transparent background)
foreground = image_ori.copy()
foreground.putalpha(pred_pil)
# Create background image
background = image_ori.copy()
background.putalpha(reverse_mask)
torch.cuda.empty_cache()
# Save all images
mask_path = "mask.png"
pred_pil.save(mask_path)
reverse_mask_path = "reverse_mask.png"
reverse_mask.save(reverse_mask_path)
foreground_path = "foreground.png"
foreground.save(foreground_path)
background_path = "background.png"
background.save(background_path)
return mask_path, reverse_mask_path, foreground_path, background_path
license_text = """
MIT License
Copyright (c) 2024 ZhengPeng
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.
"""
css = """
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.gradio-container {
background: white;
}
#component-0 button {
font-family: inherit !important;
font-size: 16px !important;
font-weight: bold !important;
color: #000000 !important;
background: linear-gradient(
135deg,
#e0f7fa, #e8f5e9, #fff9c4, #ffebee,
#f3e5f5, #e1f5fe, #fff3e0, #e8eaf6
) !important;
background-size: 400% 400% !important;
animation: gradient-animation 15s ease infinite !important;
border: 2px solid black !important;
border-radius: 10px !important;
}
#component-0 button:hover {
background: linear-gradient(
135deg,
#b2ebf2, #c8e6c9, #fff176, #ffcdd2,
#e1bee7, #b3e5fc, #ffe0b2, #c5cae9
) !important;
background-size: 400% 400% !important;
animation: gradient-animation 15s ease infinite !important;
}
@keyframes gradient-animation {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
footer {
text-align: center;
margin-top: 20px;
}
.license-link {
color: #007bff;
text-decoration: none;
cursor: pointer;
}
.license-link:hover {
text-decoration: underline;
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 600px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
"""
js = """
function setupLicenseModal() {
var modal = document.createElement('div');
modal.className = 'modal';
modal.innerHTML = `
<div class="modal-content">
<span class="close">×</span>
<h2>License</h2>
<pre>${license_text}</pre>
</div>
`;
document.body.appendChild(modal);
var link = document.createElement('a');
link.href = '#';
link.className = 'license-link';
link.textContent = 'License';
link.onclick = function(e) {
e.preventDefault();
modal.style.display = 'block';
};
var footer = document.createElement('footer');
footer.appendChild(link);
document.body.appendChild(footer);
var span = modal.querySelector('.close');
span.onclick = function() {
modal.style.display = 'none';
};
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
};
}
if (window.gradio_config.version.startsWith('3')) {
setupLicenseModal();
} else {
document.addEventListener('DOMContentLoaded', setupLicenseModal);
}
"""
iface = gr.Interface(
fn=remove_background,
inputs=gr.Image(type="numpy"),
outputs=[
gr.Image(type="filepath", label="Mask"),
gr.Image(type="filepath", label="Reverse Mask"),
gr.Image(type="filepath", label="Foreground"),
gr.Image(type="filepath", label="Background")
],
allow_flagging="never",
css=css,
js=js,
elem_id="remove-background"
)
if __name__ == "__main__":
iface.launch(debug=True) |