Spaces:
Sleeping
Sleeping
import gradio as gr | |
import numpy as np | |
from PIL import Image, ImageDraw | |
import torch | |
from transformers import AutoProcessor, CLIPSegForImageSegmentation | |
# Load the CLIPSeg model and processor | |
processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") | |
model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined") | |
def segment_everything(image): | |
inputs = processor(text=["object"], images=[image], padding="max_length", return_tensors="pt") | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
preds = outputs.logits.squeeze().sigmoid() | |
segmentation = (preds.numpy() * 255).astype(np.uint8) | |
return Image.fromarray(segmentation) | |
def segment_box(image, box): | |
x1, y1, x2, y2 = map(int, box) | |
mask = Image.new('L', image.size, 0) | |
draw = ImageDraw.Draw(mask) | |
draw.rectangle([x1, y1, x2, y2], fill=255) | |
inputs = processor(text=["object in box"], images=[image], mask_pixels=mask, padding="max_length", return_tensors="pt") | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
preds = outputs.logits.squeeze().sigmoid() | |
segmentation = (preds.numpy() * 255).astype(np.uint8) | |
return Image.fromarray(segmentation) | |
def update_image(image, segmentation, tool): | |
if segmentation is None: | |
return image | |
blended = Image.blend(image.convert('RGBA'), segmentation.convert('RGBA'), 0.5) | |
return blended | |
with gr.Blocks() as demo: | |
gr.Markdown("# Segment Anything-like Demo") | |
with gr.Row(): | |
with gr.Column(scale=1): | |
input_image = gr.Image(label="Input Image", tool="select") | |
with gr.Row(): | |
everything_btn = gr.Button("Everything") | |
box_btn = gr.Button("Box") | |
with gr.Column(scale=1): | |
output_image = gr.Image(label="Segmentation Result") | |
everything_btn.click( | |
fn=segment_everything, | |
inputs=[input_image], | |
outputs=[output_image] | |
) | |
box_btn.click( | |
fn=segment_box, | |
inputs=[input_image, input_image.sel], | |
outputs=[output_image] | |
) | |
output_image.change( | |
fn=update_image, | |
inputs=[input_image, output_image, gr.State("last_tool")], | |
outputs=[output_image] | |
) | |
demo.launch() |