Amandeep01 commited on
Commit
a09e5e0
·
verified ·
1 Parent(s): a462288

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ from PIL import Image, ImageDraw, ImageFont
4
+
5
+ # Load the YOLOS object detection model
6
+ detector = pipeline("object-detection", model="hustvl/yolos-small")
7
+
8
+ # Define some colors to differentiate classes
9
+ COLORS = ["red", "blue", "green", "orange", "purple", "yellow", "cyan", "magenta"]
10
+
11
+ # Helper function to assign color per label
12
+ def get_color_for_label(label):
13
+ return COLORS[hash(label) % len(COLORS)]
14
+
15
+ # Main function: detect, draw, and return outputs
16
+ def detect_and_draw(image, threshold):
17
+ try:
18
+ # Perform object detection
19
+ results = detector(image)
20
+ image = image.convert("RGB")
21
+ draw = ImageDraw.Draw(image)
22
+
23
+ # Try to load a font for annotations, else use default
24
+ try:
25
+ font = ImageFont.truetype("arial.ttf", 16)
26
+ except:
27
+ font = ImageFont.load_default()
28
+
29
+ annotations = []
30
+
31
+ for obj in results:
32
+ score = obj["score"]
33
+ if score < threshold:
34
+ continue
35
+
36
+ label = f"{obj['label']} ({score:.2f})"
37
+ box = obj["box"]
38
+ color = get_color_for_label(obj["label"])
39
+
40
+ # Draw the bounding box and label
41
+ draw.rectangle(
42
+ [(box["xmin"], box["ymin"]), (box["xmax"], box["ymax"])],
43
+ outline=color,
44
+ width=3,
45
+ )
46
+
47
+ draw.text((box["xmin"] + 5, box["ymin"] + 5), label, fill=color, font=font)
48
+
49
+ box_coords = (box["xmin"], box["ymin"], box["xmax"], box["ymax"])
50
+ annotations.append((box_coords, label))
51
+
52
+ return image, annotations
53
+
54
+ except Exception as e:
55
+ return f"Error during detection: {e}", None
56
+
57
+ # Gradio UI setup
58
+ demo = gr.Interface(
59
+ fn=detect_and_draw,
60
+ inputs=[
61
+ gr.Image(type="pil", label="Upload Image"),
62
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence Threshold"),
63
+ ],
64
+ outputs=[
65
+ gr.AnnotatedImage(label="Detected Image"),
66
+ ],
67
+ title="YOLOS Object Detection",
68
+ description="Upload an image to detect objects using the YOLOS-small model. Adjust the confidence threshold using the slider.",
69
+ live=True
70
+ )
71
+
72
+ demo.launch()