Last active
July 6, 2021 13:52
-
-
Save JacopoDaeli/1788da2cef6217549a440ee186d47f68 to your computer and use it in GitHub Desktop.
Extract frames from pre-recored video with Python and OpenCV
This file contains hidden or 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 | |
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 |
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.
This might be helpful https://gist.github.com/priteshgohil/b0a3d0e247b47db02b15685b3e55e3af
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!