import cv2 import numpy as np from PIL import Image def sample_frames(video_path: str, n_frames: int = 5) -> list[Image.Image]: """Sample n_frames uniformly across the video. Returns RGB PIL images.""" cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise ValueError("Could not open video file") total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if total <= 0: cap.release() raise ValueError("Video has no readable frames") n = min(n_frames, total) indices = np.linspace(0, total - 1, n, dtype=int) frames = [] for idx in indices: cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx)) ok, frame = cap.read() if not ok: continue frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(Image.fromarray(frame)) cap.release() if not frames: raise ValueError("No frames could be decoded from video") return frames