Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from PIL import Image, ImageDraw, ImageFont
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
# for local in cache file
|
7 |
+
# model_path = "../models/models--facebook--detr-resnet-50/snapshots/1d5f47bd3bdd2c4bbfa585418ffe6da5028b4c0b"
|
8 |
+
|
9 |
+
pipe = pipeline("object-detection", model="facebook/detr-resnet-50")
|
10 |
+
|
11 |
+
object_detector = pipeline("object-detection", model="facebook/detr-resnet-50")
|
12 |
+
|
13 |
+
def draw_detections_on_image(pil_image, detections):
|
14 |
+
draw = ImageDraw.Draw(pil_image)
|
15 |
+
|
16 |
+
try:
|
17 |
+
font = ImageFont.truetype("arial.ttf", 14)
|
18 |
+
except:
|
19 |
+
font = ImageFont.load_default()
|
20 |
+
|
21 |
+
for det in detections:
|
22 |
+
score = det.get('score', 0)
|
23 |
+
label = det.get('label', 'Object')
|
24 |
+
box = det['box']
|
25 |
+
xmin, ymin, xmax, ymax = box['xmin'], box['ymin'], box['xmax'], box['ymax']
|
26 |
+
|
27 |
+
draw.rectangle([xmin, ymin, xmax, ymax], outline='red', width=2)
|
28 |
+
text = f"{label} {score:.2f}"
|
29 |
+
bbox = font.getbbox(text)
|
30 |
+
text_width = bbox[2] - bbox[0]
|
31 |
+
text_height = bbox[3] - bbox[1]
|
32 |
+
text_background = [xmin, ymin - text_height, xmin + text_width, ymin]
|
33 |
+
draw.rectangle(text_background, fill='red')
|
34 |
+
draw.text((xmin, ymin - text_height), text, fill='white', font=font)
|
35 |
+
|
36 |
+
return pil_image
|
37 |
+
|
38 |
+
def detect_object(image):
|
39 |
+
try:
|
40 |
+
row_image = image
|
41 |
+
output = object_detector(row_image)
|
42 |
+
processed_image = draw_detections_on_image(row_image, output)
|
43 |
+
return processed_image
|
44 |
+
except Exception as e:
|
45 |
+
# Handle network issues or other exceptions
|
46 |
+
print(f"Error during object detection: {e}")
|
47 |
+
return "An error occurred during object detection. Please check your network connection and try again."
|
48 |
+
|
49 |
+
demo = gr.Interface(
|
50 |
+
fn=detect_object,
|
51 |
+
inputs=gr.Image(label="Select to upload image", type="pil"),
|
52 |
+
outputs=gr.Image(label="Processed Image", type="pil"),
|
53 |
+
title="@cygon: Object detector",
|
54 |
+
description="THIS SIMPLE APP CAN BE USED TO SAMPLE AND DETECT VARIOUS OBJECTS USING IMAGES.",
|
55 |
+
)
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
demo.launch(share=True) # Enables public sharing
|