vsaez's picture
Add first version of object detection
221337b verified
raw
history blame
1.45 kB
import gradio as gr
from PIL import Image, ImageDraw
from transformers import DetrImageProcessor, DetrForObjectDetection
import torch
# Load DETR model and processor from Hugging Face
model_name = "facebook/detr-resnet-50"
processor = DetrImageProcessor.from_pretrained(model_name)
model = DetrForObjectDetection.from_pretrained(model_name)
# Main function: takes an image and returns it with boxes and labels
def detect_objects(image):
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
# Convert model output to usable detection results
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(
outputs, threshold=0.9, target_sizes=target_sizes
)[0]
# Draw bounding boxes and labels on a copy of the image
image_with_boxes = image.copy()
draw = ImageDraw.Draw(image_with_boxes)
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(x, 2) for x in box.tolist()]
draw.rectangle(box, outline="red", width=3)
label_text = f"{model.config.id2label[label.item()]}: {round(score.item(), 2)}"
draw.text((box[0], box[1]), label_text, fill="white")
return image_with_boxes
# Gradio interface
app = gr.Interface(
fn=detect_objects,
inputs=gr.Image(type="pil"),
outputs=gr.Image()
)
# Run app
if __name__ == "__main__":
app.launch()