Spaces:
Running
Running
File size: 1,709 Bytes
54e77cb 52832e3 da1a1f4 54e77cb 52832e3 54e77cb da1a1f4 54e77cb a97b66d 54e77cb da1a1f4 54e77cb 52832e3 54e77cb 7c70589 54e77cb 52832e3 54e77cb 52832e3 54e77cb 52832e3 a97b66d 4f2a2ab a97b66d 52832e3 a97b66d 54e77cb |
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 |
import gradio as gr
from loadimg import load_img
import spaces
from transformers import AutoModelForImageSegmentation
import torch
from torchvision import transforms
import uuid
import os
# Select device
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
torch.set_float32_matmul_precision(["high", "highest"][0])
# Load BiRefNet model
birefnet = AutoModelForImageSegmentation.from_pretrained(
"ZhengPeng7/BiRefNet", trust_remote_code=True
)
birefnet.to(device)
# Preprocessing
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 process(image):
image_size = image.size
input_images = transform_image(image).unsqueeze(0).to(device)
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
# Main function: image upload → preview + downloadable PNG
def fn(image):
im = load_img(image, output_type="pil").convert("RGB")
processed_image = process(im)
filename = f"/tmp/processed_{uuid.uuid4().hex}.png"
processed_image.save(filename)
return processed_image, filename
# Gradio interface
demo = gr.Interface(
fn,
inputs=gr.Image(label="Upload an image", sources=["upload"]),
outputs=[
gr.Image(label="Processed Preview"),
gr.File(label="Download PNG")
],
title="Background Removal Tool"
)
if __name__ == "__main__":
demo.launch(show_error=True) |