import os import cv2 from pathlib import Path def extract_frames(video_path, output_dir, fps=2): os.makedirs(output_dir, exist_ok=True) vidcap = cv2.VideoCapture(video_path) video_name = Path(video_path).stem count = 0 frame_id = 1 success, image = vidcap.read() failed = 0 while success: if int(vidcap.get(cv2.CAP_PROP_POS_FRAMES)) % max(1, int(vidcap.get(cv2.CAP_PROP_FPS) // fps)) == 0: frame_name = f"{video_name}_{frame_id:04d}.png" out_path = os.path.abspath(os.path.join(output_dir, frame_name)) ok = cv2.imwrite(out_path, image) if not ok: print(f"[ERROR] Failed to write frame: {out_path}") failed += 1 elif frame_id <= 5: print(f"[DEBUG] Wrote frame: {out_path}") frame_id += 1 success, image = vidcap.read() count += 1 vidcap.release() print(f"Extracted {frame_id-1} frames from {video_path}. Failed writes: {failed}") if __name__ == "__main__": video_dir = "videos" frames_dir = "frames" for video_file in os.listdir(video_dir): if video_file.lower().endswith(('.mp4', '.avi', '.mov')): extract_frames(os.path.join(video_dir, video_file), frames_dir)