Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageDraw,ImageFont
|
2 |
+
import gradio as gr
|
3 |
+
import torch
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
modelname= "SenseTime/deformable-detr-with-box-refine"
|
7 |
+
modelpath = 'models/models--SenseTime--deformable-detr-with-box-refine/snapshots/2e9e461623a8fdc296e19666c46c8a4389a3a6fe'
|
8 |
+
|
9 |
+
def draw_bounding_boxes(image, detections, color=(0, 255, 0), thickness=2, font_path=None, font_size=12):
|
10 |
+
draw = ImageDraw.Draw(image)
|
11 |
+
for detection in detections:
|
12 |
+
xmin, ymin, xmax, ymax = detection['box']['xmin'], detection['box']['ymin'], detection['box']['xmax'], detection['box']['ymax']
|
13 |
+
draw.rectangle(((xmin, ymin), (xmax, ymax)), outline=color, width=thickness)
|
14 |
+
if font_path:
|
15 |
+
try:
|
16 |
+
font = ImageFont.truetype(font_path, font_size)
|
17 |
+
label_text = f"{detection['label']}: {detection['score']:.2f}"
|
18 |
+
text_width, text_height = draw.textsize(label_text, font=font)
|
19 |
+
draw.rectangle(((xmin, ymin), (xmin + text_width + 5, ymin + text_height + 5)), fill=(0, 0, 0, 0.5)) # Semi-transparent black background
|
20 |
+
draw.text((xmin, ymin), label_text, fill=color, font=font)
|
21 |
+
except (IOError, OSError):
|
22 |
+
print(f"Warning: Could not load font '{font_path}'. Labels will not be drawn.")
|
23 |
+
return image
|
24 |
+
|
25 |
+
|
26 |
+
def hf_pipeline(model_name=None,model_path=None):
|
27 |
+
model = model_path if model_name == None else model_name
|
28 |
+
print(f"=============model: {model} =============")
|
29 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
30 |
+
image_detector = pipeline("object-detection", model=model,device=device)
|
31 |
+
return image_detector
|
32 |
+
|
33 |
+
|
34 |
+
def detect_image_withbox(image):
|
35 |
+
obj_detector = hf_pipeline(modelname)
|
36 |
+
detections = obj_detector(image)
|
37 |
+
image_with_boxes = draw_bounding_boxes(image.copy(), detections)
|
38 |
+
print(detections)
|
39 |
+
return image_with_boxes
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
demo = gr.Interface(fn=detect_image_withbox,
|
44 |
+
inputs=[gr.Image(label="Select Image",type="pil")],
|
45 |
+
outputs=[gr.Image(label="Processed Image With Boxes", type="pil")],
|
46 |
+
title="@SmartChoiceLearningHub HF Project 2 : Object Detector With Box",
|
47 |
+
description="This app detects objects in an image and draws bounding boxes around them.")
|
48 |
+
demo.launch()
|