import gradio as gr from transformers import DetrImageProcessor, DetrForObjectDetection import torch from PIL import Image, ImageDraw import requests # Load model and processor model_name = "facebook/detr-resnet-50" processor = DetrImageProcessor.from_pretrained(model_name) model = DetrForObjectDetection.from_pretrained(model_name) # Define prediction function def detect_objects(image): # Preprocess image inputs = processor(images=image, return_tensors="pt") outputs = model(**inputs) # Process results target_sizes = torch.tensor([image.size[::-1]]) # (height, width) results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0] # Draw boxes 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) draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {round(score.item(), 2)}", fill="red") return image # Gradio interface demo = gr.Interface( fn=detect_objects, inputs=gr.Image(type="pil"), outputs=gr.Image(type="pil"), title="Object Detection with Bounding Boxes", description="Upload an image and the AI will detect and label objects with bounding boxes using a Hugging Face model." ) demo.launch()