Aumkeshchy2003 commited on
Commit
6fb7418
·
verified ·
1 Parent(s): 6fea677

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -37
app.py CHANGED
@@ -43,22 +43,44 @@ model.eval()
43
 
44
  # Assign fixed colors to each class for consistent visualization
45
  np.random.seed(42) # For reproducible colors
46
- colors = np.random.uniform(0, 255, size=(len(model.names), 3))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Track performance metrics
49
  total_inference_time = 0
50
  inference_count = 0
51
 
52
  def detect_objects(image):
53
- """
54
- Process input image for object detection using YOLOv5
55
 
56
- Args:
57
- image: Input image as numpy array
58
-
59
- Returns:
60
- output_image: Image with detection results visualized
61
- """
62
  global total_inference_time, inference_count
63
 
64
  if image is None:
@@ -86,53 +108,78 @@ def detect_objects(image):
86
  # Extract detections from first (and only) image
87
  detections = results.pred[0].cpu().numpy()
88
 
89
- # Draw each detection on the output image
90
  for *xyxy, conf, cls in detections:
91
- # Extract coordinates and convert to integers
92
  x1, y1, x2, y2 = map(int, xyxy)
93
  class_id = int(cls)
94
 
95
- # Get color for this class
96
- color = colors[class_id].tolist()
97
 
98
- cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 4)
99
 
100
- # Create label with class name and confidence score
101
  label = f"{model.names[class_id]} {conf:.2f}"
102
 
103
- font_scale = 0.8
104
  font_thickness = 2
105
 
106
  (w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness)
107
-
108
- cv2.rectangle(output_image, (x1, y1 - h - 10), (x1 + w + 10, y1), color, -1)
 
 
 
109
 
110
  cv2.putText(output_image, label, (x1 + 5, y1 - 5),
111
  cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), font_thickness + 1)
 
112
  cv2.putText(output_image, label, (x1 + 5, y1 - 5),
113
  cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness)
114
 
115
  # Calculate FPS
116
  fps = 1 / inference_time
117
 
118
- fps_overlay = output_image.copy()
119
- cv2.rectangle(fps_overlay, (5, 5), (250, 80), (0, 0, 0), -1)
120
- # Apply the overlay with transparency
121
- alpha = 0.7
122
- output_image = cv2.addWeighted(fps_overlay, alpha, output_image, 1 - alpha, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
- # Display FPS with larger font
125
- cv2.putText(output_image, f"FPS: {fps:.2f}", (10, 35),
126
- cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
127
- cv2.putText(output_image, f"Avg FPS: {1/avg_inference_time:.2f}", (10, 70),
128
- cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
 
 
 
129
 
130
  return output_image
131
 
132
  # Define example images - these will be stored in the same directory as this script
133
  example_images = [
134
- "examples/spring_street_after.jpg",
135
- "examples/pexels-hikaique-109919.jpg"
136
  ]
137
 
138
  # Make sure example directory exists
@@ -150,20 +197,19 @@ with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
150
  - Confidence threshold: 0.3
151
  - IoU threshold: 0.3
152
 
153
- Simply upload an image and click Submit to see the detections!
154
  """)
155
 
156
  with gr.Row():
157
  with gr.Column(scale=1):
158
  input_image = gr.Image(label="Input Image", type="numpy")
159
  with gr.Row():
160
- submit_button = gr.Button("Submit", variant="primary")
161
- clear_button = gr.Button("Clear")
162
 
163
  with gr.Column(scale=1):
164
  output_image = gr.Image(label="Detected Objects", type="numpy")
165
 
166
- # Example gallery
167
  gr.Examples(
168
  examples=example_images,
169
  inputs=input_image,
@@ -172,10 +218,16 @@ with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
172
  cache_examples=True # Cache for faster response
173
  )
174
 
175
- # Set up button event handlers
176
  submit_button.click(fn=detect_objects, inputs=input_image, outputs=output_image)
177
- clear_button.click(lambda: None, None, [input_image, output_image])
178
-
 
 
 
 
 
 
 
179
 
180
  # Launch for Hugging Face Spaces
181
  demo.launch()
 
43
 
44
  # Assign fixed colors to each class for consistent visualization
45
  np.random.seed(42) # For reproducible colors
46
+ # Generate more attractive, vibrant colors
47
+ colors = []
48
+ for i in range(len(model.names)):
49
+ # Use HSV color space for more vibrant colors
50
+ hue = i / len(model.names)
51
+ # Full saturation and value for vivid colors
52
+ saturation = 0.9
53
+ value = 1.0
54
+ # Convert HSV to RGB
55
+ h = hue * 360
56
+ s = saturation
57
+ v = value
58
+ c = v * s
59
+ x = c * (1 - abs((h / 60) % 2 - 1))
60
+ m = v - c
61
+
62
+ if h < 60:
63
+ r, g, b = c, x, 0
64
+ elif h < 120:
65
+ r, g, b = x, c, 0
66
+ elif h < 180:
67
+ r, g, b = 0, c, x
68
+ elif h < 240:
69
+ r, g, b = 0, x, c
70
+ elif h < 300:
71
+ r, g, b = x, 0, c
72
+ else:
73
+ r, g, b = c, 0, x
74
+
75
+ r, g, b = (r + m) * 255, (g + m) * 255, (b + m) * 255
76
+ colors.append([int(b), int(g), int(r)]) # OpenCV uses BGR
77
 
78
  # Track performance metrics
79
  total_inference_time = 0
80
  inference_count = 0
81
 
82
  def detect_objects(image):
 
 
83
 
 
 
 
 
 
 
84
  global total_inference_time, inference_count
85
 
86
  if image is None:
 
108
  # Extract detections from first (and only) image
109
  detections = results.pred[0].cpu().numpy()
110
 
 
111
  for *xyxy, conf, cls in detections:
 
112
  x1, y1, x2, y2 = map(int, xyxy)
113
  class_id = int(cls)
114
 
115
+ color = colors[class_id]
 
116
 
117
+ cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 3)
118
 
 
119
  label = f"{model.names[class_id]} {conf:.2f}"
120
 
121
+ font_scale = 0.7
122
  font_thickness = 2
123
 
124
  (w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness)
125
+
126
+ alpha = 0.7
127
+ overlay = output_image.copy()
128
+ cv2.rectangle(overlay, (x1, y1 - h - 10), (x1 + w + 10, y1), color, -1)
129
+ output_image = cv2.addWeighted(overlay, alpha, output_image, 1 - alpha, 0)
130
 
131
  cv2.putText(output_image, label, (x1 + 5, y1 - 5),
132
  cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), font_thickness + 1)
133
+
134
  cv2.putText(output_image, label, (x1 + 5, y1 - 5),
135
  cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness)
136
 
137
  # Calculate FPS
138
  fps = 1 / inference_time
139
 
140
+
141
+ h, w = output_image.shape[:2]
142
+
143
+ overlay = output_image.copy()
144
+
145
+ fps_bg_height = 90
146
+ fps_bg_width = 200
147
+ fps_bg_corner = 15
148
+
149
+ for i in range(fps_bg_height):
150
+ alpha = 0.8 - (i / fps_bg_height * 0.3)
151
+ color_value = int(220 * (1 - i / fps_bg_height))
152
+ cv2.rectangle(overlay,
153
+ (10, 10 + i),
154
+ (fps_bg_width, 10 + i),
155
+ (40, color_value, 40),
156
+ -1)
157
+
158
+ cv2.addWeighted(overlay, 0.8, output_image, 0.2, 0, output_image,
159
+ dst=output_image[10:10+fps_bg_height, 10:10+fps_bg_width])
160
+
161
+ cv2.rectangle(output_image,
162
+ (10, 10),
163
+ (fps_bg_width, 10 + fps_bg_height),
164
+ (255, 255, 255),
165
+ 2,
166
+ cv2.LINE_AA)
167
 
168
+ cv2.putText(output_image, "Performance", (20, 35),
169
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
170
+
171
+ cv2.putText(output_image, f"Current: {fps:.1f} FPS", (20, 65),
172
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
173
+
174
+ cv2.putText(output_image, f"Average: {1/avg_inference_time:.1f} FPS", (20, 90),
175
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
176
 
177
  return output_image
178
 
179
  # Define example images - these will be stored in the same directory as this script
180
  example_images = [
181
+ "spring_street_after.jpg",
182
+ "pexels-hikaique-109919.jpg"
183
  ]
184
 
185
  # Make sure example directory exists
 
197
  - Confidence threshold: 0.3
198
  - IoU threshold: 0.3
199
 
200
+ Upload an image, then click Submit to see the detections!
201
  """)
202
 
203
  with gr.Row():
204
  with gr.Column(scale=1):
205
  input_image = gr.Image(label="Input Image", type="numpy")
206
  with gr.Row():
207
+ clear_button = gr.Button("Clear", size="sm")
208
+ submit_button = gr.Button("Submit", variant="primary", size="lg")
209
 
210
  with gr.Column(scale=1):
211
  output_image = gr.Image(label="Detected Objects", type="numpy")
212
 
 
213
  gr.Examples(
214
  examples=example_images,
215
  inputs=input_image,
 
218
  cache_examples=True # Cache for faster response
219
  )
220
 
 
221
  submit_button.click(fn=detect_objects, inputs=input_image, outputs=output_image)
222
+ clear_button.click(
223
+ fn=lambda: (None, None),
224
+ outputs=[input_image, output_image],
225
+ queue=False
226
+ ).then(
227
+ fn=detect_objects,
228
+ inputs=input_image,
229
+ outputs=output_image
230
+ )
231
 
232
  # Launch for Hugging Face Spaces
233
  demo.launch()