| import cv2 | |
| import os | |
| from pathlib import Path | |
| def extract_frames(video_path, output_dir): | |
| """Extract all frames from video.""" | |
| cap = cv2.VideoCapture(video_path) | |
| fps = cap.get(cv2.CAP_PROP_FPS) | |
| total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
| height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
| print(f"Video info: {width}x{height}, {fps:.2f} FPS, {total_frames} frames") | |
| os.makedirs(output_dir, exist_ok=True) | |
| frame_idx = 0 | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| frame_filename = os.path.join(output_dir, f"frame_{frame_idx:06d}.jpg") | |
| cv2.imwrite(frame_filename, frame) | |
| frame_idx += 1 | |
| if frame_idx % 100 == 0: | |
| print(f"Extracted {frame_idx}/{total_frames} frames") | |
| cap.release() | |
| print(f"✅ Extracted {frame_idx} frames to {output_dir}") | |
| return fps, width, height, frame_idx | |
| def create_video_from_frames(frames_dir, output_path, fps, width, height): | |
| """Compile frames into an MP4 video.""" | |
| fourcc = cv2.VideoWriter_fourcc(*'mp4v') | |
| out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) | |
| frame_files = sorted([f for f in os.listdir(frames_dir) if f.endswith('.jpg')]) | |
| print(f"Compiling {len(frame_files)} frames into {output_path}...") | |
| for i, frame_file in enumerate(frame_files): | |
| frame = cv2.imread(os.path.join(frames_dir, frame_file)) | |
| out.write(frame) | |
| if (i + 1) % 100 == 0: | |
| print(f"Written {i+1}/{len(frame_files)} frames") | |
| out.release() | |
| print(f"✅ Video saved to {output_path}") | |