SuriRaja commited on
Commit
659239d
·
1 Parent(s): 1383abf

Update services/video_service.py

Browse files
Files changed (1) hide show
  1. services/video_service.py +27 -19
services/video_service.py CHANGED
@@ -1,30 +1,38 @@
1
- import os
2
- import random
3
  import cv2
 
4
 
 
5
  VIDEO_DIR = "data"
 
 
 
 
 
6
 
7
- def get_random_video_frame():
8
- video_files = [f for f in os.listdir(VIDEO_DIR) if f.endswith('.mp4')]
9
- if not video_files:
10
- raise Exception("No videos found in the data folder!")
11
-
12
- video_path = os.path.join(VIDEO_DIR, random.choice(video_files))
13
- cap = cv2.VideoCapture(video_path)
14
 
15
- if not cap.isOpened():
16
- raise Exception(f"Failed to open video: {video_path}")
17
 
18
- frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
19
- if frame_count == 0:
20
- raise Exception(f"No frames found in video: {video_path}")
 
 
21
 
22
- random_frame = random.randint(0, frame_count - 1)
23
- cap.set(cv2.CAP_PROP_POS_FRAMES, random_frame)
24
- ret, frame = cap.read()
25
- cap.release()
26
 
27
  if not ret:
28
- raise Exception(f"Failed to read frame at {random_frame} from {video_path}")
 
 
 
 
 
 
 
29
 
30
  return frame
 
 
 
1
  import cv2
2
+ import os
3
 
4
+ # Directory containing sample videos
5
  VIDEO_DIR = "data"
6
+ video_files = sorted([
7
+ os.path.join(VIDEO_DIR, f)
8
+ for f in os.listdir(VIDEO_DIR)
9
+ if f.endswith(".mp4") or f.endswith(".avi") or f.endswith(".mov")
10
+ ])
11
 
12
+ # Globals
13
+ current_video_index = 0
14
+ current_cap = None
 
 
 
 
15
 
16
+ def get_next_video_frame():
17
+ global current_video_index, current_cap
18
 
19
+ # Initialize capture if none
20
+ if current_cap is None:
21
+ if not video_files:
22
+ raise RuntimeError("No videos found in the 'data' folder.")
23
+ current_cap = cv2.VideoCapture(video_files[current_video_index])
24
 
25
+ # Read frame
26
+ ret, frame = current_cap.read()
 
 
27
 
28
  if not ret:
29
+ # Video ended, move to next
30
+ current_cap.release()
31
+ current_video_index = (current_video_index + 1) % len(video_files)
32
+ current_cap = cv2.VideoCapture(video_files[current_video_index])
33
+ ret, frame = current_cap.read()
34
+
35
+ if not ret:
36
+ raise RuntimeError("Failed to read frame from video.")
37
 
38
  return frame