Save video frames as images with OpenCV

15-03-2019

To read a frame we'll use the method read() from the VideoCapture class then this frame can be saved with the imwrite method.

import cv2

video = cv2.VideoCapture("./video_file.mp4")

success, image = video.read()

if success:
    cv2.imwrite("frame.jpg", image)

The method read() returns two values, success is a boolean that tell us if a frame has been grabbed and the image value is the frame itself. Then using the method imwrite we'll save that frame as an image file.

To save more than one frame or even all frames as images we need to put the read() into a loop, for instance:

import cv2

video = cv2.VideoCapture("./video_file.mp4")

# Read the first frame
success, image = video.read()
frame_id = 0

while success:
    cv2.imwrite("frame{}.jpg".format(frame_id), image)
    success, image = video.read()
    frame_id += 1

I created a script to save a percentage of the video frames as images. Check it out the frames-extractor script.