RamaManna commited on
Commit
88cb4b7
·
verified ·
1 Parent(s): 3fec7f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -0
app.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import DetrImageProcessor, DetrForObjectDetection
3
+ import torch
4
+ from PIL import Image, ImageDraw
5
+ import requests
6
+
7
+ # Load model and processor
8
+ model_name = "facebook/detr-resnet-50"
9
+ processor = DetrImageProcessor.from_pretrained(model_name)
10
+ model = DetrForObjectDetection.from_pretrained(model_name)
11
+
12
+ # Define prediction function
13
+ def detect_objects(image):
14
+ # Preprocess image
15
+ inputs = processor(images=image, return_tensors="pt")
16
+ outputs = model(**inputs)
17
+
18
+ # Process results
19
+ target_sizes = torch.tensor([image.size[::-1]]) # (height, width)
20
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
21
+
22
+ # Draw boxes
23
+ draw = ImageDraw.Draw(image)
24
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
25
+ box = [round(i, 2) for i in box.tolist()]
26
+ draw.rectangle(box, outline="red", width=3)
27
+ draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {round(score.item(), 2)}", fill="red")
28
+
29
+ return image
30
+
31
+ # Gradio interface
32
+ demo = gr.Interface(
33
+ fn=detect_objects,
34
+ inputs=gr.Image(type="pil"),
35
+ outputs=gr.Image(type="pil"),
36
+ title="Object Detection with Bounding Boxes",
37
+ description="Upload an image and the AI will detect and label objects with bounding boxes using a Hugging Face model."
38
+ )
39
+
40
+ demo.launch()