|
import gradio as gr |
|
from loadimg import load_img |
|
import spaces |
|
from transformers import AutoModelForImageSegmentation |
|
import torch |
|
from torchvision import transforms |
|
|
|
torch.set_float32_matmul_precision("high") |
|
|
|
|
|
birefnet = AutoModelForImageSegmentation.from_pretrained( |
|
"ZhengPeng7/BiRefNet", trust_remote_code=True |
|
) |
|
birefnet.to("cuda") |
|
|
|
|
|
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("cuda") |
|
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 |
|
|
|
|
|
def from_upload(image): |
|
im = load_img(image, output_type="pil").convert("RGB") |
|
origin = im.copy() |
|
processed = process(im) |
|
return (processed, origin) |
|
|
|
def from_url(url): |
|
im = load_img(url, output_type="pil").convert("RGB") |
|
origin = im.copy() |
|
processed = process(im) |
|
return (processed, origin) |
|
|
|
def process_file(f): |
|
name_path = f.rsplit(".", 1)[0] + ".png" |
|
im = load_img(f, output_type="pil").convert("RGB") |
|
transparent = process(im) |
|
transparent.save(name_path) |
|
return name_path |
|
|
|
|
|
tab1 = gr.Interface(from_upload, inputs=gr.Image(), outputs=[gr.Image(label="Processed"), gr.Image(label="Original")], title="Upload Image") |
|
tab2 = gr.Interface(from_url, inputs=gr.Textbox(label="Paste Image URL"), outputs=[gr.Image(label="Processed"), gr.Image(label="Original")], title="From URL") |
|
tab3 = gr.Interface(process_file, inputs=gr.Image(type="filepath"), outputs=gr.File(), title="Save Transparent PNG") |
|
|
|
demo = gr.TabbedInterface([tab1, tab2, tab3], ["Upload", "URL", "Save PNG"], title="Background Removal with BiRefNet") |
|
|
|
if __name__ == "__main__": |
|
demo.launch(show_error=True) |
|
|