Extract frames from a video using OpenCV

In this article, we have presented the approach to Extract frames from a video using OpenCV.

Table of contents:

  1. Extract frames from a video using OpenCV
  2. Complete Python Code

Extract frames from a video using OpenCV

Import OpenCV library as it will be used to load a video and extract all frames from it:

import cv2

Load a local video using VideoCapture() function of OpenCV.

video_file = "<path>/video.avi"
videocap = cv2.VideoCapture(video_file)

Using read() over the video object of OpenCV, the next frame from the video is returned. It also returns a boolean variable named success. It has true or false value. If it is true, a frame is returned. If false is returned, no frame is returned or an error has occured.

success, image = videocap.read()

If true is returned, save the frame returned using imwrite() function of OpenCV over the frame / image.

cv2.imwrite("image.jpeg", image)

To save all frames from a video, you need to repeatedly read frames from a video and save them.

count = 1

while success:
    cv2.imwrite("image"+str(count)+".jpeg", image)
    success, image = videocap.read()
    count = count + 1

With this, all frames of a video will be saved.

Complete Python Code

Following is the complete Python code to extract frames from a video using OpenCV:

import cv2

video_file = "<path>/video.avi"
videocap = cv2.VideoCapture(video_file)
success, image = videocap.read()
count = 0

while success:
    cv2.imwrite("image"+str(count)+".jpeg", image)
    success, image = videocap.read()
    count = count + 1
    
print("Frames have been extracted")

With this article at OpenGenus, you must have the complete idea of how to extract frames from a video using OpenCV.