Skip to content

Instantly share code, notes, and snippets.

@JacopoDaeli
Last active July 6, 2021 13:52
Show Gist options
  • Save JacopoDaeli/1788da2cef6217549a440ee186d47f68 to your computer and use it in GitHub Desktop.
Save JacopoDaeli/1788da2cef6217549a440ee186d47f68 to your computer and use it in GitHub Desktop.
Extract frames from pre-recored video with Python and OpenCV
import cv2
def video_to_frames(video_filename):
"""Extract frames from video"""
cap = cv2.VideoCapture(video_filename)
video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
frames = []
if cap.isOpened() and video_length > 0:
frame_ids = [0]
if video_length >= 4:
frame_ids = [0,
round(video_length * 0.25),
round(video_length * 0.5),
round(video_length * 0.75),
video_length - 1]
count = 0
success, image = cap.read()
while success:
if count in frame_ids:
frames.append(image)
success, image = cap.read()
count += 1
return frames
@priteshgohil
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment