Spaces:
Sleeping
Sleeping
Upload video_utils.py
Browse files- utils/video_utils.py +42 -0
utils/video_utils.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frame extraction and video writing utilities."""
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"extract_frames_from_video",
|
| 9 |
+
"save_frames_to_video",
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def extract_frames_from_video(video_path: str, target_fps: int = 30) -> List[np.ndarray]:
|
| 14 |
+
cap = cv2.VideoCapture(video_path)
|
| 15 |
+
if not cap.isOpened():
|
| 16 |
+
raise IOError(f"Cannot open video: {video_path}")
|
| 17 |
+
|
| 18 |
+
original_fps = cap.get(cv2.CAP_PROP_FPS) or target_fps
|
| 19 |
+
frame_interval = max(1, round(original_fps / target_fps))
|
| 20 |
+
|
| 21 |
+
frames, count = [], 0
|
| 22 |
+
while True:
|
| 23 |
+
ret, frame = cap.read()
|
| 24 |
+
if not ret:
|
| 25 |
+
break
|
| 26 |
+
if count % frame_interval == 0:
|
| 27 |
+
frames.append(frame)
|
| 28 |
+
count += 1
|
| 29 |
+
cap.release()
|
| 30 |
+
return frames
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save_frames_to_video(frames: List[np.ndarray], output_path: str, fps: int = 30):
|
| 34 |
+
if not frames:
|
| 35 |
+
raise ValueError("No frames to save")
|
| 36 |
+
|
| 37 |
+
height, width = frames[0].shape[:2]
|
| 38 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 39 |
+
writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 40 |
+
for frm in frames:
|
| 41 |
+
writer.write(frm)
|
| 42 |
+
writer.release()
|