Spaces:
Sleeping
Sleeping
| import cv2 | |
| import os | |
| def video_to_keyframes(video_path, output_folder, frame_interval=1, prefix='frame'): | |
| """ | |
| Convert video to keyframes (individual frames) and save as images | |
| Args: | |
| video_path (str): Path to input video file | |
| output_folder (str): Directory to save extracted frames | |
| frame_interval (int): Extract every nth frame (1=every frame) | |
| prefix (str): Prefix for saved frame files | |
| """ | |
| # Create output directory if it doesn't exist | |
| os.makedirs(output_folder, exist_ok=True) | |
| # Open the video file | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| raise ValueError(f"Could not open video {video_path}") | |
| # Get video properties | |
| fps = cap.get(cv2.CAP_PROP_FPS) | |
| total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| duration = total_frames / fps | |
| print(f"Video Info:") | |
| print(f"- Path: {video_path}") | |
| print(f"- FPS: {fps}") | |
| print(f"- Total Frames: {total_frames}") | |
| print(f"- Duration: {duration:.2f} seconds") | |
| print(f"- Extracting every {frame_interval} frame(s)") | |
| frame_count = 0 | |
| saved_count = 0 | |
| while True: | |
| ret, frame = cap.read() | |
| # Stop if we've reached the end of the video | |
| if not ret: | |
| break | |
| # Only process frames at the specified interval | |
| if frame_count % frame_interval == 0: | |
| # Save frame as image file | |
| frame_filename = f"{prefix}_{saved_count:06d}.jpg" | |
| output_path = os.path.join(output_folder, frame_filename) | |
| cv2.imwrite(output_path, frame) | |
| saved_count += 1 | |
| # Print progress every 100 frames | |
| if saved_count % 100 == 0: | |
| print(f"Saved frame {saved_count} (original frame {frame_count})") | |
| frame_count += 1 | |
| # Release resources | |
| cap.release() | |