|
import gradio as gr |
|
from transformers import DetrImageProcessor, DetrForObjectDetection |
|
from PIL import Image, ImageDraw |
|
|
|
|
|
model_name = "facebook/detr-resnet-50" |
|
model = DetrForObjectDetection.from_pretrained(model_name) |
|
processor = DetrImageProcessor.from_pretrained(model_name) |
|
|
|
|
|
def detect_objects(image): |
|
inputs = processor(images=image, return_tensors="pt") |
|
outputs = model(**inputs) |
|
|
|
|
|
target_sizes = [image.size[::-1]] |
|
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0] |
|
|
|
|
|
draw = ImageDraw.Draw(image) |
|
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): |
|
box = [round(i, 2) for i in box.tolist()] |
|
draw.rectangle(box, outline="red", width=3) |
|
label_name = model.config.id2label[label.item()] |
|
draw.text((box[0], box[1]), f"{label_name} ({score:.2f})", fill="red") |
|
|
|
return image |
|
|
|
|
|
interface = gr.Interface( |
|
fn=detect_objects, |
|
inputs=gr.Image(type="pil"), |
|
outputs=gr.Image(type="pil"), |
|
title="Object Detection App", |
|
description="Upload an image to detect objects using the DETR model." |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
interface.launch() |
|
|