Spaces:
Sleeping
Sleeping
Create video_processor.py
Browse files- video_processor.py +52 -0
video_processor.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import os
|
3 |
+
import tempfile
|
4 |
+
|
5 |
+
def process_video(video_path, clip_duration=10, target_fps=25):
|
6 |
+
"""
|
7 |
+
Processes the input video:
|
8 |
+
- Trims the last `clip_duration` seconds
|
9 |
+
- Samples frames at `target_fps`
|
10 |
+
|
11 |
+
Returns:
|
12 |
+
frames: List of BGR frames
|
13 |
+
metadata: Dict with original FPS, trimmed duration, frame count
|
14 |
+
"""
|
15 |
+
cap = cv2.VideoCapture(video_path)
|
16 |
+
if not cap.isOpened():
|
17 |
+
raise IOError("Cannot open video file.")
|
18 |
+
|
19 |
+
orig_fps = cap.get(cv2.CAP_PROP_FPS)
|
20 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
21 |
+
duration = total_frames / orig_fps
|
22 |
+
|
23 |
+
# Calculate starting point for last `clip_duration` seconds
|
24 |
+
start_time = max(0, duration - clip_duration)
|
25 |
+
start_frame = int(start_time * orig_fps)
|
26 |
+
|
27 |
+
# Set video to start point
|
28 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
|
29 |
+
|
30 |
+
# Read and sample frames
|
31 |
+
frames = []
|
32 |
+
frame_interval = int(orig_fps // target_fps) if target_fps < orig_fps else 1
|
33 |
+
frame_idx = 0
|
34 |
+
|
35 |
+
while True:
|
36 |
+
ret, frame = cap.read()
|
37 |
+
if not ret:
|
38 |
+
break
|
39 |
+
if frame_idx % frame_interval == 0:
|
40 |
+
frames.append(frame)
|
41 |
+
frame_idx += 1
|
42 |
+
|
43 |
+
cap.release()
|
44 |
+
|
45 |
+
metadata = {
|
46 |
+
"original_fps": orig_fps,
|
47 |
+
"sampled_fps": target_fps,
|
48 |
+
"clip_duration": clip_duration,
|
49 |
+
"sampled_frames": len(frames)
|
50 |
+
}
|
51 |
+
|
52 |
+
return frames, metadata
|