File size: 1,182 Bytes
6ee1f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""Frame extraction and video writing utilities."""

import cv2
import numpy as np
from typing import List

__all__ = [
    "extract_frames_from_video",
    "save_frames_to_video",
]


def extract_frames_from_video(video_path: str, target_fps: int = 30) -> List[np.ndarray]:
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise IOError(f"Cannot open video: {video_path}")

    original_fps = cap.get(cv2.CAP_PROP_FPS) or target_fps
    frame_interval = max(1, round(original_fps / target_fps))

    frames, count = [], 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if count % frame_interval == 0:
            frames.append(frame)
        count += 1
    cap.release()
    return frames


def save_frames_to_video(frames: List[np.ndarray], output_path: str, fps: int = 30):
    if not frames:
        raise ValueError("No frames to save")

    height, width = frames[0].shape[:2]
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    for frm in frames:
        writer.write(frm)
    writer.release()