Spaces:
Sleeping
Sleeping
Update services/video_service.py
Browse files- services/video_service.py +37 -44
services/video_service.py
CHANGED
|
@@ -1,57 +1,50 @@
|
|
|
|
|
| 1 |
import cv2
|
| 2 |
import os
|
| 3 |
|
| 4 |
-
# Global
|
| 5 |
-
|
| 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 |
-
PRELOADED_FRAMES = []
|
| 11 |
|
| 12 |
def preload_video():
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
cap
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
else:
|
| 23 |
-
break
|
| 24 |
-
cap.release()
|
| 25 |
-
cap = None
|
| 26 |
|
| 27 |
def get_next_video_frame():
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
ret, frame = cap.read()
|
| 42 |
if not ret:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
ret, frame = cap.read()
|
| 47 |
-
if not ret:
|
| 48 |
-
raise RuntimeError(f"Cannot read video {video_files[video_index]}")
|
| 49 |
-
break
|
| 50 |
-
|
| 51 |
-
frame = cv2.resize(frame, (320, 240)) # Reduce resolution for faster processing
|
| 52 |
return frame
|
| 53 |
|
| 54 |
def reset_video_index():
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# services/video_service.py
|
| 2 |
import cv2
|
| 3 |
import os
|
| 4 |
|
| 5 |
+
# Global variables
|
| 6 |
+
video_path = "sample.mp4" # Default video file
|
|
|
|
|
|
|
| 7 |
cap = None
|
| 8 |
+
frame_index = 0
|
|
|
|
| 9 |
|
| 10 |
def preload_video():
|
| 11 |
+
"""
|
| 12 |
+
Preload the video file.
|
| 13 |
+
"""
|
| 14 |
+
global cap
|
| 15 |
+
if not os.path.exists(video_path):
|
| 16 |
+
raise FileNotFoundError(f"Video file {video_path} not found.")
|
| 17 |
+
cap = cv2.VideoCapture(video_path)
|
| 18 |
+
if not cap.isOpened():
|
| 19 |
+
raise RuntimeError("Failed to open video file.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def get_next_video_frame():
|
| 22 |
+
"""
|
| 23 |
+
Get the next frame from the video.
|
| 24 |
+
Returns:
|
| 25 |
+
numpy array: Video frame
|
| 26 |
+
"""
|
| 27 |
+
global cap, frame_index
|
| 28 |
+
if cap is None:
|
| 29 |
+
raise RuntimeError("Video not preloaded. Call preload_video() first.")
|
| 30 |
+
|
| 31 |
+
ret, frame = cap.read()
|
| 32 |
+
if not ret:
|
| 33 |
+
# Loop the video
|
| 34 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 35 |
+
frame_index = 0
|
| 36 |
ret, frame = cap.read()
|
| 37 |
if not ret:
|
| 38 |
+
raise RuntimeError("Failed to read video frame.")
|
| 39 |
+
|
| 40 |
+
frame_index += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
return frame
|
| 42 |
|
| 43 |
def reset_video_index():
|
| 44 |
+
"""
|
| 45 |
+
Reset the video frame index.
|
| 46 |
+
"""
|
| 47 |
+
global frame_index
|
| 48 |
+
frame_index = 0
|
| 49 |
+
if cap is not None:
|
| 50 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|