Skip to content

Instantly share code, notes, and snippets.

@JasonSKK
Created October 10, 2023 13:39
Show Gist options
  • Save JasonSKK/628dad7bfac89dd1bee057c66d181366 to your computer and use it in GitHub Desktop.
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
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