|
|
import gradio as gr |
|
|
from gradio_imageslider import ImageSlider |
|
|
from loadimg import load_img |
|
|
import spaces |
|
|
from transformers import AutoModelForImageSegmentation |
|
|
import torch |
|
|
from torchvision import transforms |
|
|
from PIL import Image |
|
|
|
|
|
torch.set_float32_matmul_precision(["high", "highest"][0]) |
|
|
|
|
|
|
|
|
birefnet = AutoModelForImageSegmentation.from_pretrained( |
|
|
"ZhengPeng7/BiRefNet", trust_remote_code=True |
|
|
) |
|
|
birefnet.to("cpu") |
|
|
|
|
|
|
|
|
transform_image = transforms.Compose( |
|
|
[ |
|
|
transforms.Resize((1024, 1024)), |
|
|
transforms.ToTensor(), |
|
|
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), |
|
|
] |
|
|
) |
|
|
|
|
|
|
|
|
def process(image): |
|
|
"""Segment person/body from image with transparent background""" |
|
|
image_size = image.size |
|
|
input_images = transform_image(image).unsqueeze(0).to("cpu") |
|
|
|
|
|
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 = image.convert("RGBA") |
|
|
image.putalpha(mask) |
|
|
|
|
|
return image |
|
|
|
|
|
|
|
|
def fn(image): |
|
|
im = load_img(image, output_type="pil") |
|
|
im = im.convert("RGB") |
|
|
origin = im.copy() |
|
|
result = process(im) |
|
|
return result |
|
|
|
|
|
|
|
|
def process_file(f): |
|
|
"""Process uploaded file and save output as PNG with transparency""" |
|
|
name_path = f.rsplit(".", 1)[0] + ".png" |
|
|
im = load_img(f, output_type="pil") |
|
|
im = im.convert("RGB") |
|
|
transparent = process(im) |
|
|
transparent.save(name_path, "PNG") |
|
|
return name_path |
|
|
|
|
|
|
|
|
|
|
|
slider1 = gr.Image() |
|
|
slider2 = ImageSlider(label="birefnet", type="pil") |
|
|
image = gr.Image(label="Upload an image") |
|
|
image2 = gr.Image(label="Upload an image", type="filepath") |
|
|
text = gr.Textbox(label="Paste an image URL") |
|
|
png_file = gr.File(label="Output PNG file") |
|
|
|
|
|
|
|
|
chameleon = load_img("butterfly.jpg", output_type="pil") |
|
|
|
|
|
|
|
|
tab3 = gr.Interface( |
|
|
process_file, |
|
|
inputs=image2, |
|
|
outputs=png_file, |
|
|
examples=["butterfly.jpg"], |
|
|
api_name="png", |
|
|
) |
|
|
|
|
|
|
|
|
demo = gr.TabbedInterface([tab3], ["PNG Output"], title="Body Extractor") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch(share=True) |
|
|
|