Extract images from a video in Python

In this article, we will be learning how to extract images from a video in Python. Looking at the diversity of modules and versatility of use, one such module is OpenCV. It is one of the prominent modules for video manipulation. Moreover, it is an important module for image analysis or technologies like facial recognition.

Furthermore, OpenCV is one of the Python programming languages which performs the image processing tasks and is widely in development for many applications like motion detection, skin detection, facial recognition, and few COVID-19 projects like mask detection and social distance detection. Due to the advancement of technologies, OpenCV has provided with much important functions to make the development easier.

For the current project, we will use methods like-

  1. VideoCapture(path) – which reads the path of input .mp4 video.
  2. read() – it reads the data upon the object calls.
  3. imwrite(name, image) – saves the images of the frames of a video to the specified location.

For example, we will now Extract images from a video in Python of a short video named sample-mp4-file.mp4.

Here is the code to extract images:-

#Importing cv2 module
import cv2 
# Function which take path as input and extract images of the video 
def ExtractImages(path): 
    # Path to video file --- capture_image is the object which calls read
    capture_image = cv2.VideoCapture(path) 

    #keeping a count for each frame captured  
    frame_count = 0
    while (True): 
        #Reading each frame
        con,frames = capture_image.read() 
        #con will test until last frame is extracted
        if con:
            #giving names to each frame and printing while extracting
            name = str(frame_count)+'.jpg'
            print('Capturing --- '+name)
            # Extracting images and saving with name 
            cv2.imwrite(name, frames) 

            frame_count = frame_count + 1
path = r"C:\Users\KIRA\Desktop\case study\sample-mp4-file.mp4"

Consequently, the images of the video are obtained:

images from a video in Python


Leave a Reply