Spaces:
Running
Running
File size: 1,066 Bytes
dfdcd97 a3ee867 e0d4d2f 49e0cdb |
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 |
import gradio as gr
import torch
from PIL import Image
from torchvision import transforms
# Load pre-trained U-Net model
model = torch.hub.load('nvidia/DeepLearningExamples:torchhub', 'unet', pretrained=True)
# Define a function to segment an image
def segment_image(image):
# Preprocess image
image = Image.fromarray(image)
image = transforms.Compose([
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])(image)
# Run segmentation model
output = model(image.unsqueeze(0))
output = torch.argmax(output, dim=1)
# Postprocess output
output = output.squeeze(0).cpu().numpy()
output = Image.fromarray(output.astype('uint8'))
return output
# Create Gradio app
demo = gr.Interface(
fn=segment_image,
inputs=gr.Image(type="pil"),
outputs=gr.Image(type="pil"),
title="Segment Anything",
description="Segment any image using a pre-trained U-Net model"
)
# Launch Gradio app
demo.launch() |