Created
October 10, 2023 13:39
-
-
Save JasonSKK/628dad7bfac89dd1bee057c66d181366 to your computer and use it in GitHub Desktop.
Extract frames from a video at specified intervals using FFmpeg. Evaluation of the differences between consecutive frames and saving only those frames that exhibit significant changes. The difference is determined by calculating the mean absolute pixel difference. Frames with a difference exceeding a given threshold are stored as PNG images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import os | |
def extract_different_frames(video_path, output_dir, threshold=30): | |
cap = cv2.VideoCapture(video_path) | |
prev_frame = None | |
frame_count = 0 | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
break | |
if prev_frame is not None: | |
# Calculate absolute difference between the frames | |
diff = cv2.absdiff(prev_frame, frame) | |
mean_diff = diff.mean() | |
# If the difference exceeds the threshold, save the frame | |
if mean_diff > threshold: | |
frame_count += 1 | |
frame_filename = os.path.join(output_dir, f'frame{frame_count:04d}.png') | |
cv2.imwrite(frame_filename, frame) | |
prev_frame = frame | |
cap.release() | |
if __name__ == "__main__": | |
video_path = "~/Desktop/video.mp4" | |
output_dir = "frames" | |
threshold = 30 # Adjust the threshold as needed | |
if not os.path.exists(output_dir): | |
os.makedirs(output_dir) | |
extract_different_frames(video_path, output_dir, threshold) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment