Program to extract frames using OpenCV in Python?

OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.

With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & reorganization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.

In this exercise we are going to implement frame by frame video processing. The input video can be live camera video or video stored in your local machine. We are going to create frames from the video stored in our local machine & then store the frames in our local drive.

As opencv is not a standard python library, so we need to install it. We can install it using pip very easily:

pip install opencv-python
Collecting opencv-python
Downloading (22.1MB)
100% |████████████████████████████████| 22.1MB 141kB/s
Requirement already satisfied: numpy>=1.11.3 in c:\python\python361\lib\site-packages (from opencv-python) (1.13.0)
Installing collected packages: opencv-python
Successfully installed opencv-python-

My video file is stored in the f: drive, which I want to convert into frames (thumbnails) and then store the frames in my chosen location.

Code: Program to read a video file and extract frames from it.

#Import libraries
import cv2
import os
#Function to extract frames
def extractFrames(pathIn, pathOut):
   #directory path, where my video images will be stored
   #Capture vidoe from video file
   cap = cv2.VideoCapture(pathIn)
#Counter Variable
count = 0

while (cap.isOpened()):
   # Capture frame-by-frame
   ret, frame =
   if ret == True:
      print('Read %d frame: ' % count, ret)
      # save frame as JPEG file
      cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)
      count += 1
# When everything done, release the capture
def main():
   extractFrames(r'f:/I Miss You.mp4' , 'data')
if __name__=="__main__":


We can see, a data folder is created in my desktop(destination path) and the frames from the video are stored inside the folder.

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started