To optimize the comparison and make it faster, instead of hashing the entire frame, you could use a simpler and faster method by comparing the pixel data directly or using a reduced representation of the frame. Here's how you can adjust the code to use a direct comparison:
Simplified Direct Comparison
You can use NumPy to compare frames directly, which can be quite efficient since it leverages optimized array operations:
import cv2
import os
from pathlib import Path
import numpy as np
def video_to_frames(video_path, output_folder, frame_size=(512, 512)):
"""
Extracts frames from a video and saves them as images if they differ from the previous frame.
Args:
video_path (str): Path to the input video file.
output_folder (str): Directory where extracted frames will be saved.
frame_size (tuple): Desired size of output frames (width, height).
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Open the video file
cap = cv2.VideoCapture(video_path)
frame_count = 0
success, previous_frame = cap.read()
if success:
# Resize the initial frame
previous_frame = cv2.resize(previous_frame, frame_size)
# Save the initial frame
frame_filename = os.path.join(output_folder, f"{Path(video_path).stem}_{frame_count:06d}.png")
cv2.imwrite(frame_filename, previous_frame)
frame_count += 1
while success:
success, frame = cap.read()
if success:
# Resize the current frame
frame = cv2.resize(frame, frame_size)
# Compare current frame with previous frame
if not np.array_equal(frame, previous_frame):
# Save the frame as it is different from the previous frame
frame_filename = os.path.join(output_folder, f"{Path(video_path).stem}_{frame_count:06d}.png")
cv2.imwrite(frame_filename, frame)
frame_count += 1
# Update the previous frame
previous_frame = frame
cap.release()
print(f"Extracted {frame_count} unique frames from {video_path} to {output_folder}")
# Example usage
video_to_frames('input_video.mp4', 'output_directory')
Key Optimizations:
-
Direct Comparison with np.array_equal: This function quickly checks if two arrays (frames) are identical. It is generally faster than hashing the entire frame.
-
Early Initial Frame Handling: The first frame is automatically saved and used as the baseline for subsequent comparisons.
Benefits:
-
Performance: Direct pixel comparison using NumPy is highly efficient due to optimizations in numerical libraries.
-
Simplicity: Eliminates hashing overhead, simplifying the process.
This approach is generally efficient, but keep in mind that video compression artifacts could result in nearly identical frames being slightly different, leading to more frames being saved compared to using a lossy hash method that groups visually identical frames.