Spaces:
Running
Running
File size: 1,450 Bytes
221337b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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()
|