Skip to content

Instantly share code, notes, and snippets.

@JacopoDaeli
Last active July 6, 2021 13:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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
@bingyand
Copy link

bingyand commented Jun 3, 2020

Hi there, thank you so much for your code, it works great! But just wondering if it's possible to extract frames from all videos in a folder? I am a beginner in coding, so I got stuck on this problem for a while. It would you much appreciated if you could shed some light!

@mabubaker1947
Copy link

Hi there, thank you so much for your code, it works great! But just wondering if it's possible to extract frames from all videos in a folder? I am a beginner in coding, so I got stuck on this problem for a while. It would you much appreciated if you could shed some light!

Yes @bingyand, you can export images with cv2.imwrite("Image name",image) to write in the current directory.

@priteshgohil
Copy link

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