CSB261's picture
Update app.py
cda3f0b verified
raw
history blame
2.79 kB
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
torch.set_float32_matmul_precision(["high", "highest"][0])
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 fn(image):
if image is None or len(image) == 0:
return image, None # ์›๋ณธ ์ด๋ฏธ์ง€๋„ ๋ฐ˜ํ™˜
im = load_img(image, output_type="pil")
im = im.convert("RGB")
image_size = im.size
origin = im.copy()
image = load_img(im)
input_images = transform_image(image).unsqueeze(0).to("cuda")
# Prediction
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, origin # ๋ณ€ํ™˜๋œ ์ด๋ฏธ์ง€์™€ ์›๋ณธ ์ด๋ฏธ์ง€ ๋ฐ˜ํ™˜
def save_image(image):
if image is not None:
image.save("output.png")
return "output.png"
return None
with gr.Blocks() as demo:
image = gr.Image(label="Upload an image")
text = gr.Textbox(label="Paste an image URL")
download_button = gr.Button("Download Image")
output_file = gr.File()
slider1 = ImageSlider(label="birefnet", type="pil")
slider2 = ImageSlider(label="birefnet", type="pil")
chameleon = load_img("butterfly.jpg", output_type="pil")
example_image2 = load_img("example2.jpg", output_type="pil") # ๋‘ ๋ฒˆ์งธ ์˜ˆ์ œ ์ด๋ฏธ์ง€
example_image3 = load_img("example3.jpg", output_type="pil") # ์„ธ ๋ฒˆ์งธ ์˜ˆ์ œ ์ด๋ฏธ์ง€
url1 = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg"
url2 = "https://example.com/example2.jpg" # ๋‘ ๋ฒˆ์งธ ์˜ˆ์ œ URL
url3 = "https://example.com/example3.jpg" # ์„ธ ๋ฒˆ์งธ ์˜ˆ์ œ URL
with gr.Tab("Image Upload"):
tab1 = gr.Interface(
fn, inputs=image, outputs=[slider1, output_file],
examples=[chameleon, example_image2, example_image3], api_name="image"
)
with gr.Tab("Image URL"):
tab2 = gr.Interface(
fn, inputs=text, outputs=[slider2, output_file],
examples=[url1, url2, url3], api_name="text"
)
def process_download(image):
return save_image(image[0])
download_button.click(process_download, inputs=slider1, outputs=output_file)
if __name__ == "__main__":
demo.launch()