Demo-2025 / utils /video.py
zye0616's picture
initial commit
2ab6e0a
raw
history blame
1.18 kB
from typing import List, Tuple
import cv2
import numpy as np
def extract_frames(video_path: str) -> Tuple[List[np.ndarray], float, int, int]:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError("Unable to open video.")
fps = cap.get(cv2.CAP_PROP_FPS) or 0.0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frames: List[np.ndarray] = []
success, frame = cap.read()
while success:
frames.append(frame)
success, frame = cap.read()
cap.release()
if not frames:
raise ValueError("Video decode produced zero frames.")
return frames, fps, width, height
def write_video(frames: List[np.ndarray], output_path: str, fps: float, width: int, height: int) -> None:
if not frames:
raise ValueError("No frames available for writing.")
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(output_path, fourcc, fps or 1.0, (width, height))
if not writer.isOpened():
raise ValueError("Failed to open VideoWriter.")
for frame in frames:
writer.write(frame)
writer.release()