Spaces:
Sleeping
Sleeping
checking in app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image, ImageDraw, ImageFont
|
3 |
+
|
4 |
+
# Use a pipeline as a high-level helper
|
5 |
+
from transformers import pipeline
|
6 |
+
|
7 |
+
object_detector = pipeline("object-detection", model="facebook/detr-resnet-50")
|
8 |
+
|
9 |
+
|
10 |
+
def draw_detections(image, detections):
|
11 |
+
draw = ImageDraw.Draw(image)
|
12 |
+
font = ImageFont.load_default()
|
13 |
+
|
14 |
+
for obj in detections:
|
15 |
+
score = obj['score']
|
16 |
+
label = obj['label']
|
17 |
+
box = obj['box']
|
18 |
+
xmin, ymin, xmax, ymax = box['xmin'], box['ymin'], box['xmax'], box['ymax']
|
19 |
+
|
20 |
+
# Draw the bounding box
|
21 |
+
draw.rectangle(((xmin, ymin), (xmax, ymax)), outline="red", width=2)
|
22 |
+
|
23 |
+
# Draw the label and score
|
24 |
+
text = f"{label}: {score:.2f}"
|
25 |
+
text_bbox = draw.textbbox((xmin, ymin), text, font=font)
|
26 |
+
text_location = (xmin, ymin - (text_bbox[3] - text_bbox[1])) if ymin - (text_bbox[3] - text_bbox[1]) > 0 else (xmin, ymin + (text_bbox[3] - text_bbox[1]))
|
27 |
+
draw.rectangle(((xmin, text_location[1]), (xmin + (text_bbox[2] - text_bbox[0]), text_location[1] + (text_bbox[3] - text_bbox[1]))), fill="red")
|
28 |
+
draw.text((xmin, text_location[1]), text, fill="white", font=font)
|
29 |
+
|
30 |
+
return image
|
31 |
+
|
32 |
+
def detect_object_and_draw_boundary(image_path):
|
33 |
+
raw_image = Image.open(image_path)
|
34 |
+
model_output = object_detector(raw_image)
|
35 |
+
bounary_image = draw_detections(raw_image, model_output)
|
36 |
+
return bounary_image
|
37 |
+
|
38 |
+
gr.close_all()
|
39 |
+
|
40 |
+
|
41 |
+
demo = gr.Interface(detect_object_and_draw_boundary,
|
42 |
+
inputs=[gr.File(file_types=['jpg','png','gif'], label='Upload an image to detect objects in it.')],
|
43 |
+
|
44 |
+
outputs=[gr.Image(label='Image with boundries of the detected objects')],
|
45 |
+
title="Gen AI Learning Project 6: Object detection and drawing boundry.",
|
46 |
+
description="This Application uses 'facebook/detr-resnet-5' to detect objects in the uploaded image and draw boundry around them.")
|
47 |
+
demo.launch()
|