Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import DetrImageProcessor, DetrForObjectDetection | |
| from PIL import Image, ImageDraw | |
| # Load pre-trained model and image processor | |
| model_name = "facebook/detr-resnet-50" | |
| model = DetrForObjectDetection.from_pretrained(model_name) | |
| processor = DetrImageProcessor.from_pretrained(model_name) | |
| # Define function for object detection | |
| def detect_objects(image): | |
| inputs = processor(images=image, return_tensors="pt") | |
| outputs = model(**inputs) | |
| # Get predictions | |
| target_sizes = [image.size[::-1]] # (height, width) | |
| results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0] | |
| # Draw bounding boxes on the image | |
| 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 | |
| # Create Gradio interface | |
| 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." | |
| ) | |
| # Launch the app | |
| if __name__ == "__main__": | |
| interface.launch() | |