apratim24 commited on
Commit
d7750ec
·
verified ·
1 Parent(s): 768f8dd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
3
+
4
+
5
+ # Use a pipeline as a high-level helper
6
+ from transformers import pipeline
7
+
8
+ # model_path = ("../Models/models--facebook--detr-resnet-50/snapshots"
9
+ # "/1d5f47bd3bdd2c4bbfa585418ffe6da5028b4c0b")
10
+
11
+ object_detector = pipeline("object-detection",
12
+ model="facebook/detr-resnet-50")
13
+
14
+ # object_detector = pipeline("object-detection",
15
+ # model=model_path)
16
+
17
+
18
+ def draw_bounding_boxes(image, detections, font_path=None, font_size=20):
19
+
20
+ # Make a copy of the image to draw on
21
+ draw_image = image.copy()
22
+ draw = ImageDraw.Draw(draw_image)
23
+
24
+ # Load custom font or default font if path not provided
25
+ if font_path:
26
+ font = ImageFont.truetype(font_path, font_size)
27
+ else:
28
+ # When font_path is not provided, load default font but it's size is fixed
29
+ font = ImageFont.load_default()
30
+ # Increase font size workaround by using a TTF font file, if needed, can download and specify the path
31
+
32
+ for detection in detections:
33
+ box = detection['box']
34
+ xmin = box['xmin']
35
+ ymin = box['ymin']
36
+ xmax = box['xmax']
37
+ ymax = box['ymax']
38
+
39
+ # Draw the bounding box
40
+ draw.rectangle([(xmin, ymin), (xmax, ymax)], outline="red", width=3)
41
+
42
+ # Optionally, you can also draw the label and score
43
+ label = detection['label']
44
+ score = detection['score']
45
+ text = f"{label} {score:.2f}"
46
+
47
+ # Draw text with background rectangle for visibility
48
+ if font_path: # Use the custom font with increased size
49
+ text_size = draw.textbbox((xmin, ymin), text, font=font)
50
+ else:
51
+ # Calculate text size using the default font
52
+ text_size = draw.textbbox((xmin, ymin), text)
53
+
54
+ draw.rectangle([(text_size[0], text_size[1]), (text_size[2], text_size[3])], fill="red")
55
+ draw.text((xmin, ymin), text, fill="white", font=font)
56
+
57
+ return draw_image
58
+
59
+
60
+ def detect_object(image):
61
+ raw_image = image
62
+ output = object_detector(raw_image)
63
+ processed_image = draw_bounding_boxes(raw_image, output)
64
+ return processed_image
65
+
66
+ demo = gr.Interface(fn=detect_object,
67
+ inputs=[gr.Image(label="Select Image",type="pil")],
68
+ outputs=[gr.Image(label="Processed Image", type="pil")],
69
+ title="Object Detector",
70
+ description="This application can be used to detect objects inside the provided input image.")
71
+ demo.launch()
72
+
73
+ # print(output)
74
+
75
+