Spaces:
Runtime error
Runtime error
Update services/video_service.py
Browse files- services/video_service.py +31 -59
services/video_service.py
CHANGED
|
@@ -1,61 +1,33 @@
|
|
| 1 |
import cv2
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
cap.release()
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
frame_copy,
|
| 28 |
-
timestamp,
|
| 29 |
-
(10, 30),
|
| 30 |
-
cv2.FONT_HERSHEY_SIMPLEX,
|
| 31 |
-
0.7,
|
| 32 |
-
(255, 255, 255),
|
| 33 |
-
2
|
| 34 |
-
)
|
| 35 |
-
for detection in detections:
|
| 36 |
-
score = detection["score"]
|
| 37 |
-
label = detection["label"]
|
| 38 |
-
box = detection["box"]
|
| 39 |
-
x1, y1, x2, y2 = box["xmin"], box["ymin"], box["xmax"], box["ymax"]
|
| 40 |
-
cv2.rectangle(frame_copy, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 41 |
-
cv2.putText(
|
| 42 |
-
frame_copy,
|
| 43 |
-
f"{label}: {score:.2f}",
|
| 44 |
-
(x1, y1 - 10),
|
| 45 |
-
cv2.FONT_HERSHEY_SIMPLEX,
|
| 46 |
-
0.5,
|
| 47 |
-
(0, 255, 0),
|
| 48 |
-
2
|
| 49 |
-
)
|
| 50 |
-
return frame_copy
|
| 51 |
-
|
| 52 |
-
def save_video(self, frames, output_path, fps=30):
|
| 53 |
-
"""Save frames as a video."""
|
| 54 |
-
if not frames:
|
| 55 |
-
return
|
| 56 |
-
height, width, _ = frames[0].shape
|
| 57 |
-
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 58 |
-
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 59 |
-
for frame in frames:
|
| 60 |
-
out.write(frame)
|
| 61 |
-
out.release()
|
|
|
|
| 1 |
import cv2
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# Global state
|
| 5 |
+
VIDEO_DIR = "data"
|
| 6 |
+
video_files = [os.path.join(VIDEO_DIR, file) for file in sorted(os.listdir(VIDEO_DIR)) if file.endswith((".mp4", ".avi"))]
|
| 7 |
+
video_index = 0
|
| 8 |
+
cap = None
|
| 9 |
+
|
| 10 |
+
def get_next_video_frame():
|
| 11 |
+
global cap, video_index
|
| 12 |
+
|
| 13 |
+
if not video_files:
|
| 14 |
+
raise RuntimeError("No video files found in the 'data' directory.")
|
| 15 |
+
|
| 16 |
+
if cap is None or not cap.isOpened():
|
| 17 |
+
cap = cv2.VideoCapture(video_files[video_index])
|
| 18 |
+
|
| 19 |
+
ret, frame = cap.read()
|
| 20 |
+
|
| 21 |
+
if not ret:
|
| 22 |
cap.release()
|
| 23 |
+
video_index = (video_index + 1) % len(video_files)
|
| 24 |
+
cap = cv2.VideoCapture(video_files[video_index])
|
| 25 |
+
ret, frame = cap.read()
|
| 26 |
+
if not ret:
|
| 27 |
+
raise RuntimeError(f"Cannot read video {video_files[video_index]}")
|
| 28 |
+
|
| 29 |
+
return frame
|
| 30 |
+
|
| 31 |
+
def reset_video_index():
|
| 32 |
+
global video_index
|
| 33 |
+
video_index = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|