Extracting images from videos in Python

Counters | File handling | Python Methods and Functions

Image analysis is a very common field in computer vision. It is the extraction of meaningful information from videos or images. The OpenCv library can be used to perform several operations on video.

Required modules:

 import cv2 import os 

Function used:

VideoCapture (File_path): Read the video (.mp4 format)

read (): Read data depending upon the type of object that calls

imwrite (filename, img [, params]): Saves an image to a specified file.

Below is the implementation:

# Import all required libraries

import cv2

import os

# Read the video at the specified path

cam = cv2.VideoCapture ( "C: Users Admin PycharmProjects project_1 openCV.mp4" )


try :


# create a folder named data

if not os.path.exists ( ' data' ):

os.makedirs ( 'data ' )

# if not created, then issue an error

except OSError:

  print ( ' Error: Creating directory of data' )

# Frame

currentframe = 0


while ( True ):


# read from frame

ret, frame = cam.read ()


if ret:

< code class = "undefined spaces">  # if there is still video, continue creating images

name = '. / data / frame' + str (currentframe) + '.jpg'

  print ( 'Creating ...' + name)


  # write extracted images

cv2.imwrite (name, frame )


  # increment counter to make it

  # show how many frames were created

currentframe + = 1

else :


# Free all space and windows as soon as done
cam.release ()
cv2.destroyAllWindows ()


All extracted images will be saved to folder named "data" on the system.