Commit
•
b2e0420
1
Parent(s):
7416059
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,74 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
# Function to perform object detection on an image
|
8 |
def detect_objects(image):
|
9 |
-
#
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
#
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
#
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Hugging Face's logo
|
2 |
+
Search models, datasets, users...
|
3 |
+
|
4 |
+
Spaces:
|
5 |
|
6 |
+
Epitech
|
7 |
+
/
|
8 |
+
Object-Detection
|
9 |
+
|
10 |
+
like
|
11 |
+
1
|
12 |
+
App
|
13 |
+
Files
|
14 |
+
Community
|
15 |
+
Object-Detection
|
16 |
+
/
|
17 |
+
app.py
|
18 |
+
paulmondon
|
19 |
+
Add requirements.txt
|
20 |
+
a72c3ec
|
21 |
+
raw
|
22 |
+
history
|
23 |
+
blame
|
24 |
+
contribute
|
25 |
+
delete
|
26 |
+
1.6 kB
|
27 |
+
from transformers import DetrImageProcessor, DetrForObjectDetection
|
28 |
+
import torch
|
29 |
+
from PIL import Image, ImageDraw
|
30 |
+
import gradio as gr
|
31 |
+
import requests
|
32 |
+
import random
|
33 |
|
|
|
34 |
def detect_objects(image):
|
35 |
+
# Load the pre-trained DETR model
|
36 |
+
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
|
37 |
+
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
|
38 |
+
|
39 |
+
inputs = processor(images=image, return_tensors="pt")
|
40 |
+
outputs = model(**inputs)
|
41 |
+
|
42 |
+
# convert outputs (bounding boxes and class logits) to COCO API
|
43 |
+
# let's only keep detections with score > 0.9
|
44 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
45 |
+
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
|
46 |
+
|
47 |
+
# Draw bounding boxes and labels on the image
|
48 |
+
draw = ImageDraw.Draw(image)
|
49 |
+
for i, (score, label, box) in enumerate(zip(results["scores"], results["labels"], results["boxes"])):
|
50 |
+
box = [round(i, 2) for i in box.tolist()]
|
51 |
+
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
52 |
+
draw.rectangle(box, outline=color, width=3)
|
53 |
+
label_text = f"{model.config.id2label[label.item()]}: {round(score.item(), 2)}"
|
54 |
+
draw.text((box[0], box[1]), label_text, fill=color)
|
55 |
+
|
56 |
+
return image
|
57 |
+
|
58 |
+
|
59 |
+
def upload_image(file):
|
60 |
+
image = Image.open(file.name)
|
61 |
+
image_with_boxes = detect_objects(image)
|
62 |
+
return image_with_boxes
|
63 |
+
|
64 |
+
iface = gr.Interface(
|
65 |
+
fn=upload_image,
|
66 |
+
inputs="file",
|
67 |
+
outputs="image",
|
68 |
+
title="Object Detection",
|
69 |
+
description="Upload an image and detect objects using DETR model.",
|
70 |
+
allow_flagging=False
|
71 |
+
)
|
72 |
+
|
73 |
+
iface.launch()
|
74 |
+
|