#OpenCV – Open a video file ๐ŸŽฅ and save each frame as a PNG ๐Ÿ–ผ file to a folder ๐Ÿ“‚#Python

Buy Me A Coffee

Hi !

This is a non-usual scenario, however I’m on a point where I need to extract all the frames from a video file. The reason: some of these frames will be used to train a Machine Learning model.

There are tools that can do this, however it’s a nice moment to do some OpenCV code. Let’s go for it. A couple of remarks

  • Video file must be in the same folder as python file, and the name is defined in video_file, line 11
  • I resize the frame to 640 x 480, remove line 20 and fix vars name
  • There is a live preview of the video, comment line 27 to avoid this
  • You can stop the process at any time pressing the Q letter
# Bruno Capuano 2020
# open a video file and save each frame as a PNG file to a folder

import cv2
import os

# Camera Settings
camera_Width  = 640 # 1024 # 1280 # 640
camera_Heigth = 480 # 780  # 960  # 480
frameSize = (camera_Width, camera_Heigth)
video_file = "03.mp4"
video_capture = cv2.VideoCapture(video_file)

i = 0
while video_capture.isOpened():

    ret, frameOrig = video_capture.read()
    if ret == True:
        # resize frame, optional you may not need this
        frame = cv2.resize(frameOrig, frameSize)

        i += 1
        imgNumber = str(i).zfill(5)
        frameImageFileName = str(f'03\image{imgNumber}.png')
        cv2.imwrite(frameImageFileName, frameOrig)

        cv2.imshow('Video', frame)

    # key controller
    key = cv2.waitKey(1) & 0xFF    
    if key == ord("q"):


Happy coding!


El Bruno

More posts in my blog ElBruno.com.

More info in https://beacons.ai/elbruno


Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: