Spaces:
Build error
Build error
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import gradio as grfrom transformers import DetrImageProcessor, DetrForObjectDetectionimport torchfrom PIL import Image, ImageDrawimport requests
# Load model and processormodel_name = "facebook/detr-resnet-50"processor = DetrImageProcessor.from_pretrained(model_name)model = DetrForObjectDetection.from_pretrained(model_name)
# Define prediction functiondef 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 interfacedemo = 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()app.pyAdded+40