adityya7 commited on
Commit
37df904
·
verified ·
1 Parent(s): 7e486fb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ import tempfile
5
+
6
+ # Load the YOLOS object detection model
7
+ detector = pipeline("object-detection", model="hustvl/yolos-small")
8
+
9
+ # Define some colors to differentiate classes
10
+ COLORS = ["red", "blue", "green", "orange", "purple", "yellow", "cyan", "magenta"]
11
+
12
+ # Helper function to assign color per label
13
+ def get_color_for_label(label):
14
+ return COLORS[hash(label) % len(COLORS)]
15
+
16
+ # Main function: detect, draw, and return outputs
17
+ def detect_and_draw(image, threshold):
18
+ results = detector(image)
19
+ image = image.convert("RGB")
20
+ draw = ImageDraw.Draw(image)
21
+
22
+ try:
23
+ font = ImageFont.truetype("arial.ttf", 16)
24
+ except:
25
+ font = ImageFont.load_default()
26
+
27
+ annotations = []
28
+
29
+ for obj in results:
30
+ score = obj["score"]
31
+ if score < threshold:
32
+ continue
33
+
34
+ label = f"{obj['label']} ({score:.2f})"
35
+ box = obj["box"]
36
+ color = get_color_for_label(obj["label"])
37
+
38
+ draw.rectangle(
39
+ [(box["xmin"], box["ymin"]), (box["xmax"], box["ymax"])],
40
+ outline=color,
41
+ width=3,
42
+ )
43
+
44
+ draw.text((box["xmin"] + 5, box["ymin"] + 5), label, fill=color, font=font)
45
+
46
+ box_coords = (box["xmin"], box["ymin"], box["xmax"], box["ymax"])
47
+ annotations.append((box_coords, label))
48
+
49
+ # Save image for download
50
+ temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
51
+ image.save(temp_file.name)
52
+
53
+ # ✅ Return the (image, annotations) tuple and the path to the saved image
54
+ return (image, annotations), temp_file.name
55
+
56
+ # Gradio UI setup
57
+ demo = gr.Interface(
58
+ fn=detect_and_draw,
59
+ inputs=[
60
+ gr.Image(type="pil", label="Upload Image"),
61
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence Threshold"),
62
+ ],
63
+ outputs=[
64
+ gr.AnnotatedImage(label="Detected Image"),
65
+ gr.File(label="Download Processed 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
+ )
70
+
71
+ demo.launch()