DSatishchandra commited on
Commit
0d70434
·
verified ·
1 Parent(s): 59f8356

Create services/video_service.py

Browse files
Files changed (1) hide show
  1. services/video_service.py +52 -0
services/video_service.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Draw bounding boxes and labels on frame."""
25
+ frame_copy = frame.copy()
26
+ for detection in detections:
27
+ score = detection["score"]
28
+ label = detection["label"]
29
+ box = detection["box"]
30
+ x1, y1, x2, y2 = box["xmin"], box["ymin"], box["xmax"], box["ymax"]
31
+ cv2.rectangle(frame_copy, (x1, y1), (x2, y2), (0, 255, 0), 2)
32
+ cv2.putText(
33
+ frame_copy,
34
+ f"{label}: {score:.2f}",
35
+ (x1, y1 - 10),
36
+ cv2.FONT_HERSHEY_SIMPLEX,
37
+ 0.5,
38
+ (0, 255, 0),
39
+ 2
40
+ )
41
+ return frame_copy
42
+
43
+ def save_video(self, frames, output_path, fps=30):
44
+ """Save frames as a video."""
45
+ if not frames:
46
+ return
47
+ height, width, _ = frames[0].shape
48
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
49
+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
50
+ for frame in frames:
51
+ out.write(frame)
52
+ out.release()