Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,64 +3,104 @@ import numpy as np
|
|
3 |
import gradio as gr
|
4 |
import cv2
|
5 |
import time
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
7 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
8 |
-
|
9 |
-
|
10 |
-
#
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
if device.type == "cuda":
|
14 |
-
model.half()
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
17 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
)
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import gradio as gr
|
4 |
import cv2
|
5 |
import time
|
6 |
+
import os
|
7 |
+
from pathlib import Path
|
8 |
+
|
9 |
+
# Create cache directory for models
|
10 |
+
os.makedirs("models", exist_ok=True)
|
11 |
+
|
12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
+
print(f"Using device: {device}")
|
14 |
+
|
15 |
+
# Load YOLOv5 Nano model
|
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", "custom", path=str(model_path), source="local").to(device)
|
20 |
+
else:
|
21 |
+
print("Downloading YOLOv5n model and caching...")
|
22 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True).to(device)
|
23 |
+
torch.save(model.state_dict(), model_path)
|
24 |
+
|
25 |
+
# Optimize model for speed
|
26 |
+
model.conf = 0.3 # Lower confidence threshold
|
27 |
+
model.iou = 0.3 # Non-Maximum Suppression IoU threshold
|
28 |
+
model.classes = None # Detect all classes
|
29 |
+
|
30 |
if device.type == "cuda":
|
31 |
+
model.half() # Use FP16 for faster inference
|
32 |
+
else:
|
33 |
+
torch.set_num_threads(os.cpu_count())
|
34 |
+
|
35 |
+
model.eval()
|
36 |
+
|
37 |
+
# Pre-generate colors for bounding boxes
|
38 |
+
np.random.seed(42)
|
39 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
40 |
+
|
41 |
+
def process_video(video_path):
|
42 |
+
cap = cv2.VideoCapture(video_path)
|
43 |
+
|
44 |
+
if not cap.isOpened():
|
45 |
+
return "Error: Could not open video file."
|
46 |
+
|
47 |
+
frame_width = int(cap.get(3))
|
48 |
+
frame_height = int(cap.get(4))
|
49 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
50 |
+
|
51 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
52 |
+
output_path = "output_video.mp4"
|
53 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))
|
54 |
+
|
55 |
+
total_frames = 0
|
56 |
+
total_time = 0
|
57 |
+
|
58 |
+
while cap.isOpened():
|
59 |
+
ret, frame = cap.read()
|
60 |
+
if not ret:
|
61 |
+
break # Break if no more frames
|
62 |
+
|
63 |
+
start_time = time.time()
|
64 |
+
|
65 |
+
# Convert frame for YOLOv5
|
66 |
+
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
67 |
+
results = model(img, size=640)
|
68 |
+
|
69 |
+
inference_time = time.time() - start_time
|
70 |
+
total_time += inference_time
|
71 |
+
total_frames += 1
|
72 |
+
|
73 |
+
detections = results.pred[0].cpu().numpy()
|
74 |
+
|
75 |
+
for *xyxy, conf, cls in detections:
|
76 |
+
x1, y1, x2, y2 = map(int, xyxy)
|
77 |
+
class_id = int(cls)
|
78 |
+
color = colors[class_id].tolist()
|
79 |
+
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3, lineType=cv2.LINE_AA)
|
80 |
+
label = f"{model.names[class_id]} {conf:.2f}"
|
81 |
+
cv2.putText(frame, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
|
82 |
+
|
83 |
+
# Calculate FPS
|
84 |
+
avg_fps = total_frames / total_time if total_time > 0 else 0
|
85 |
+
cv2.putText(frame, f"FPS: {avg_fps:.2f}", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
86 |
+
|
87 |
+
out.write(frame)
|
88 |
+
|
89 |
+
cap.release()
|
90 |
+
out.release()
|
91 |
+
|
92 |
+
return output_path
|
93 |
+
|
94 |
+
# Gradio Interface
|
95 |
+
with gr.Blocks(title="Real-Time YOLOv5 Video Detection") as demo:
|
96 |
+
gr.Markdown("# Real-Time YOLOv5 Video Detection (30+ FPS)")
|
97 |
+
|
98 |
+
with gr.Row():
|
99 |
+
video_input = gr.Video(label="Upload Video")
|
100 |
+
process_button = gr.Button("Process Video")
|
101 |
+
|
102 |
+
video_output = gr.Video(label="Processed Video")
|
103 |
+
|
104 |
+
process_button.click(fn=process_video, inputs=video_input, outputs=video_output)
|
105 |
+
|
106 |
+
demo.launch()
|