Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -4,8 +4,6 @@ import gradio as gr
|
|
4 |
import cv2
|
5 |
import time
|
6 |
import os
|
7 |
-
import threading
|
8 |
-
from queue import Queue
|
9 |
from pathlib import Path
|
10 |
|
11 |
# Create cache directory for models
|
@@ -14,52 +12,54 @@ os.makedirs("models", exist_ok=True)
|
|
14 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
15 |
print(f"Using device: {device}")
|
16 |
|
17 |
-
#
|
18 |
model_path = Path("models/yolov5n.pt")
|
19 |
if model_path.exists():
|
20 |
print(f"Loading model from cache: {model_path}")
|
21 |
-
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True,
|
|
|
22 |
else:
|
23 |
print("Downloading YOLOv5n model and caching...")
|
24 |
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True).to(device)
|
25 |
torch.save(model.state_dict(), model_path)
|
26 |
|
27 |
-
# Model configurations
|
28 |
-
model.conf = 0.
|
29 |
-
model.iou = 0.45
|
30 |
-
model.classes = None
|
31 |
-
model.max_det = 20 # Limit detections for speed
|
32 |
|
|
|
33 |
if device.type == "cuda":
|
34 |
-
model.half()
|
|
|
35 |
else:
|
36 |
torch.set_num_threads(os.cpu_count())
|
37 |
|
38 |
model.eval()
|
39 |
|
40 |
-
# Precompute colors for bounding boxes
|
41 |
np.random.seed(42)
|
42 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
43 |
|
44 |
-
# Performance tracking
|
45 |
total_inference_time = 0
|
46 |
inference_count = 0
|
47 |
-
last_fps_values = [] # Store recent FPS values
|
48 |
|
49 |
def detect_objects(image):
|
50 |
-
"""Process a single image for object detection"""
|
51 |
global total_inference_time, inference_count
|
52 |
|
53 |
if image is None:
|
54 |
return None
|
55 |
|
|
|
|
|
|
|
|
|
56 |
start_time = time.time()
|
57 |
-
output_image = image.copy()
|
58 |
-
input_size = 640
|
59 |
|
60 |
-
#
|
|
|
|
|
61 |
with torch.no_grad():
|
62 |
-
results = model(
|
63 |
|
64 |
inference_time = time.time() - start_time
|
65 |
total_inference_time += inference_time
|
@@ -68,150 +68,64 @@ def detect_objects(image):
|
|
68 |
|
69 |
detections = results.pred[0].cpu().numpy()
|
70 |
|
71 |
-
# Draw detections
|
72 |
for *xyxy, conf, cls in detections:
|
73 |
x1, y1, x2, y2 = map(int, xyxy)
|
74 |
class_id = int(cls)
|
75 |
color = colors[class_id].tolist()
|
76 |
|
77 |
-
#
|
78 |
-
cv2.rectangle(output_image, (x1, y1), (x2, y2), color,
|
79 |
|
80 |
-
#
|
81 |
label = f"{model.names[class_id]} {conf:.2f}"
|
82 |
-
|
83 |
-
(
|
84 |
-
|
85 |
-
|
86 |
-
cv2.putText(output_image, label, (x1 + 5, y1 - 5),
|
87 |
-
cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)
|
88 |
-
|
89 |
-
fps = 1 / inference_time
|
90 |
-
|
91 |
-
# Stylish FPS display
|
92 |
-
overlay = output_image.copy()
|
93 |
-
cv2.rectangle(overlay, (10, 10), (300, 80), (0, 0, 0), -1)
|
94 |
-
output_image = cv2.addWeighted(overlay, 0.6, output_image, 0.4, 0)
|
95 |
-
cv2.putText(output_image, f"FPS: {fps:.2f}", (20, 40),
|
96 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, lineType=cv2.LINE_AA)
|
97 |
-
cv2.putText(output_image, f"Avg FPS: {1/avg_inference_time:.2f}", (20, 70),
|
98 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, lineType=cv2.LINE_AA)
|
99 |
-
|
100 |
-
return output_image
|
101 |
-
|
102 |
-
def process_webcam_frame(frame):
|
103 |
-
"""Process a single frame from webcam"""
|
104 |
-
global last_fps_values
|
105 |
-
|
106 |
-
if frame is None:
|
107 |
-
return None
|
108 |
-
|
109 |
-
start_time = time.time()
|
110 |
-
|
111 |
-
# Use a smaller size for real-time
|
112 |
-
input_size = 384
|
113 |
-
|
114 |
-
# Process the frame
|
115 |
-
with torch.no_grad():
|
116 |
-
results = model(frame, size=input_size)
|
117 |
-
|
118 |
-
# Calculate FPS
|
119 |
-
inference_time = time.time() - start_time
|
120 |
-
current_fps = 1 / inference_time if inference_time > 0 else 30
|
121 |
-
|
122 |
-
# Update FPS history (keep last 30 values)
|
123 |
-
last_fps_values.append(current_fps)
|
124 |
-
if len(last_fps_values) > 30:
|
125 |
-
last_fps_values.pop(0)
|
126 |
-
avg_fps = sum(last_fps_values) / len(last_fps_values)
|
127 |
|
128 |
-
#
|
129 |
-
|
130 |
-
|
131 |
-
# Draw detections
|
132 |
-
detections = results.pred[0].cpu().numpy()
|
133 |
-
for *xyxy, conf, cls in detections:
|
134 |
-
x1, y1, x2, y2 = map(int, xyxy)
|
135 |
-
class_id = int(cls)
|
136 |
-
color = colors[class_id].tolist()
|
137 |
-
|
138 |
-
# Draw rectangle and label
|
139 |
-
cv2.rectangle(output, (x1, y1), (x2, y2), color, 2, lineType=cv2.LINE_AA)
|
140 |
-
|
141 |
-
label = f"{model.names[class_id]} {conf:.2f}"
|
142 |
-
font_scale, font_thickness = 0.6, 1
|
143 |
-
(w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness)
|
144 |
-
|
145 |
-
cv2.rectangle(output, (x1, y1 - h - 5), (x1 + w + 5, y1), color, -1)
|
146 |
-
cv2.putText(output, label, (x1 + 3, y1 - 3),
|
147 |
-
cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)
|
148 |
|
149 |
-
#
|
150 |
-
|
151 |
-
cv2.putText(
|
152 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.
|
153 |
-
cv2.putText(
|
154 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.
|
155 |
|
156 |
-
return
|
157 |
-
|
158 |
-
def process_uploaded_image(image):
|
159 |
-
"""Process an uploaded image"""
|
160 |
-
return detect_objects(image)
|
161 |
|
162 |
-
#
|
163 |
example_images = ["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
|
164 |
os.makedirs("examples", exist_ok=True)
|
165 |
|
166 |
-
|
167 |
-
with gr.Blocks(title="YOLOv5 Object Detection - Real-time & Image Upload") as demo:
|
168 |
gr.Markdown("""
|
169 |
-
# YOLOv5 Object Detection
|
170 |
-
|
|
|
|
|
171 |
""")
|
172 |
|
173 |
-
with gr.
|
174 |
-
with gr.
|
175 |
-
gr.
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
|
|
|
|
|
|
|
|
183 |
|
184 |
-
|
185 |
-
|
186 |
-
fn=process_webcam_frame,
|
187 |
-
inputs=webcam,
|
188 |
-
outputs=webcam_output
|
189 |
-
)
|
190 |
|
191 |
-
|
192 |
-
|
193 |
-
### Image Upload Detection
|
194 |
-
Upload an image to detect objects.
|
195 |
-
""")
|
196 |
-
with gr.Row():
|
197 |
-
with gr.Column(scale=1):
|
198 |
-
input_image = gr.Image(label="Input Image", type="numpy")
|
199 |
-
submit_button = gr.Button("Submit", variant="primary")
|
200 |
-
clear_button = gr.Button("Clear")
|
201 |
-
|
202 |
-
with gr.Column(scale=1):
|
203 |
-
output_image = gr.Image(label="Detected Objects", type="numpy")
|
204 |
-
|
205 |
-
gr.Examples(
|
206 |
-
examples=example_images,
|
207 |
-
inputs=input_image,
|
208 |
-
outputs=output_image,
|
209 |
-
fn=process_uploaded_image,
|
210 |
-
cache_examples=True
|
211 |
-
)
|
212 |
-
|
213 |
-
# Set up event handlers
|
214 |
-
submit_button.click(fn=process_uploaded_image, inputs=input_image, outputs=output_image)
|
215 |
-
clear_button.click(lambda: (None, None), None, [input_image, output_image])
|
216 |
|
217 |
-
demo.launch(
|
|
|
4 |
import cv2
|
5 |
import time
|
6 |
import os
|
|
|
|
|
7 |
from pathlib import Path
|
8 |
|
9 |
# Create cache directory for models
|
|
|
12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
print(f"Using device: {device}")
|
14 |
|
15 |
+
# Load YOLOv5n model (corrected from original)
|
16 |
model_path = Path("models/yolov5n.pt")
|
17 |
if model_path.exists():
|
18 |
print(f"Loading model from cache: {model_path}")
|
19 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True,
|
20 |
+
source="local", path=str(model_path)).to(device)
|
21 |
else:
|
22 |
print("Downloading YOLOv5n model and caching...")
|
23 |
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True).to(device)
|
24 |
torch.save(model.state_dict(), model_path)
|
25 |
|
26 |
+
# Model configurations
|
27 |
+
model.conf = 0.6
|
28 |
+
model.iou = 0.45
|
29 |
+
model.classes = None
|
|
|
30 |
|
31 |
+
# Optimizations
|
32 |
if device.type == "cuda":
|
33 |
+
model.half()
|
34 |
+
torch.backends.cudnn.benchmark = True
|
35 |
else:
|
36 |
torch.set_num_threads(os.cpu_count())
|
37 |
|
38 |
model.eval()
|
39 |
|
|
|
40 |
np.random.seed(42)
|
41 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
42 |
|
|
|
43 |
total_inference_time = 0
|
44 |
inference_count = 0
|
|
|
45 |
|
46 |
def detect_objects(image):
|
|
|
47 |
global total_inference_time, inference_count
|
48 |
|
49 |
if image is None:
|
50 |
return None
|
51 |
|
52 |
+
# Convert RGB to BGR for OpenCV operations
|
53 |
+
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
54 |
+
output_image = image_bgr.copy()
|
55 |
+
|
56 |
start_time = time.time()
|
|
|
|
|
57 |
|
58 |
+
# Convert to RGB for model inference
|
59 |
+
img_rgb = cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
|
60 |
+
|
61 |
with torch.no_grad():
|
62 |
+
results = model(img_rgb, size=320) # Reduced input size for speed
|
63 |
|
64 |
inference_time = time.time() - start_time
|
65 |
total_inference_time += inference_time
|
|
|
68 |
|
69 |
detections = results.pred[0].cpu().numpy()
|
70 |
|
|
|
71 |
for *xyxy, conf, cls in detections:
|
72 |
x1, y1, x2, y2 = map(int, xyxy)
|
73 |
class_id = int(cls)
|
74 |
color = colors[class_id].tolist()
|
75 |
|
76 |
+
# Draw bounding boxes
|
77 |
+
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 2, lineType=cv2.LINE_AA)
|
78 |
|
79 |
+
# Draw labels
|
80 |
label = f"{model.names[class_id]} {conf:.2f}"
|
81 |
+
(w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)
|
82 |
+
cv2.rectangle(output_image, (x1, y1 - 20), (x1 + w, y1), color, -1)
|
83 |
+
cv2.putText(output_image, label, (x1, y1 - 5),
|
84 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, lineType=cv2.LINE_AA)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
# Convert back to RGB for Gradio
|
87 |
+
output_image_rgb = cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
+
# Draw performance metrics
|
90 |
+
fps = 1 / inference_time
|
91 |
+
cv2.putText(output_image_rgb, f"FPS: {fps:.1f}", (10, 30),
|
92 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, lineType=cv2.LINE_AA)
|
93 |
+
cv2.putText(output_image_rgb, f"Avg FPS: {1/avg_inference_time:.1f}", (10, 60),
|
94 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, lineType=cv2.LINE_AA)
|
95 |
|
96 |
+
return output_image_rgb
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
# Example images
|
99 |
example_images = ["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
|
100 |
os.makedirs("examples", exist_ok=True)
|
101 |
|
102 |
+
with gr.Blocks(title="Real-time YOLOv5 Object Detection") as demo:
|
|
|
103 |
gr.Markdown("""
|
104 |
+
# Real-time YOLOv5 Object Detection
|
105 |
+
- Real-time webcam detection (30+ FPS on GPU)
|
106 |
+
- Image upload capability
|
107 |
+
- Performance optimized with half-precision and CUDA acceleration
|
108 |
""")
|
109 |
|
110 |
+
with gr.Tab("🎥 Real-time Webcam"):
|
111 |
+
with gr.Row():
|
112 |
+
webcam = gr.Image(source="webcam", streaming=True, label="Live Webcam Feed")
|
113 |
+
live_output = gr.Image(label="Detection Results")
|
114 |
+
webcam.stream(fn=detect_objects, inputs=webcam, outputs=live_output)
|
115 |
+
|
116 |
+
with gr.Tab("📸 Image Upload"):
|
117 |
+
with gr.Row():
|
118 |
+
with gr.Column():
|
119 |
+
input_image = gr.Image(type="numpy", label="Input Image")
|
120 |
+
gr.Examples(examples=example_images, inputs=input_image)
|
121 |
+
with gr.Row():
|
122 |
+
submit_btn = gr.Button("Detect Objects", variant="primary")
|
123 |
+
clear_btn = gr.Button("Clear")
|
124 |
|
125 |
+
with gr.Column():
|
126 |
+
output_image = gr.Image(type="numpy", label="Processed Image")
|
|
|
|
|
|
|
|
|
127 |
|
128 |
+
submit_btn.click(fn=detect_objects, inputs=input_image, outputs=output_image)
|
129 |
+
clear_btn.click(lambda: (None, None), outputs=[input_image, output_image])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
+
demo.launch()
|