Extract Each Frame from a Video File using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.


First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3


In this tutorial, I will show you how to extract each frame from a video file using OpenCV with Python coding.


Python: cv2.VideoCapture(filename) → <VideoCapture object>

Open video file for video playing


  • filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, …)

Python: cv2.imwrite(filename, img[, params]) → retval

Saves an image to a specified file.


  • filename – Name of the file.
  • image – Image to be saved.
  • params
    • Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, …


  • Load the video file using cv2.VideoCapture()
  • Read video frames using
  • Write each frame using cv2.imwrite()
  • Release the VideoCapture object using cv2.VideoCapture.release()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import os

def extractFrames(pathIn, pathOut):

    cap = cv2.VideoCapture(pathIn)
    count = 0

    while (cap.isOpened()):

        # Capture frame-by-frame
        ret, frame =

        if ret == True:
            print('Read %d frame: ' % count, ret)
            cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)  # save frame as JPEG file
            count += 1

    # When everything done, release the capture

def main():
    extractFrames('bigbuckbunny720p5mb.mp4', 'data')

if __name__=="__main__":


Capture-1 Extract Each Frame from a Video File using OpenCV in Python

life2coding_icon [] Extract Each Frame from a Video File using OpenCV in Python

7 thoughts on “Extract Each Frame from a Video File using OpenCV in Python

  1. Kaleem Ullah

    Hello Sir! the above code is very much easy to implement and helpful. kindly can you help me how to extract frames with user defined size…?
    your help in this regard will be highly appreciated. I’m anticipating your kind help and showing my gratitude in advance.

    1. Life2Coding Post author

      What kind of defined size. Can you elaborate it a little bit. Then I may give you the modified code for that as well.

      1. Kaleem Ullah

        when i want to extract frames from video, it return frames having size of 1288*964 while i need frames having size of 640*480.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.