DSatishchandra commited on
Commit
468ede7
Β·
verified Β·
1 Parent(s): 24bb53a

Update services/video_service.py

Browse files
Files changed (1) hide show
  1. services/video_service.py +31 -59
services/video_service.py CHANGED
@@ -1,61 +1,33 @@
1
  import cv2
2
- from PIL import Image
3
- import numpy as np
4
-
5
- class VideoService:
6
- def load_video(self, video_path):
7
- """Load video and return frames."""
8
- cap = cv2.VideoCapture(video_path)
9
- frames = []
10
- while cap.isOpened():
11
- ret, frame = cap.read()
12
- if not ret:
13
- break
14
- frames.append(frame)
 
 
 
 
 
 
 
15
  cap.release()
16
- return frames
17
-
18
- def frame_to_pil(self, frame):
19
- """Convert OpenCV frame to PIL Image."""
20
- frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
21
- return Image.fromarray(frame_rgb)
22
-
23
- def draw_detections(self, frame, detections):
24
- frame_copy = frame.copy()
25
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
26
- cv2.putText(
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