Python 3 OpenCV Script to Capture Frames From Video and Save it as PNG Image Files in Directory Full Project For Beginners

Python 3 OpenCV Script to Capture Frames From Video and Save it as PNG Image Files in Directory Full Project For Beginners

 

Welcome folks today in this tutorial we will be capturing frames from video and save it as png image files in a directory. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started we need to install the following libraries using the pip command as shown below

 

pip install opencv-python

 

After installing this library now make an app.py file and copy paste the following code

 

app.py

 

import os
import shutil
import sys
import cv2

class FrameCapture:
    '''
        Class definition to capture frames
    '''
    def __init__(self, file_path):
        '''
            initializing directory where the captured frames will be stored.
            Also truncating the directory where captured frames are stored, if exists.
        '''
        self.directory = "captured_frames"
        self.file_path = file_path
        if os.path.exists(self.directory):
            shutil.rmtree(self.directory)
        os.mkdir(self.directory)

    def capture_frames(self):
        '''
            This method captures the frames from the video file provided.
            This program makes use of openCV library
        '''
        cv2_object = cv2.VideoCapture(self.file_path)

        frame_number = 0
        frame_found = 1

        while frame_found:
            frame_found, image = cv2_object.read()
            capture = f'{self.directory}/frame{frame_number}.jpg'
            cv2.imwrite(capture, image)

            frame_number += 1

if __name__ == '__main__':
    file_path = sys.argv[1]
    fc = FrameCapture(file_path)
    fc.capture_frames()

 

See also  Python 3 Script to Download Image or PDF File From URL Using Requests and Validators Library Full Project For Beginners

 

Now you need to run this python script by passing an additional command line argument which will be path of the input video file as shown below

 

 

 

As you can see my video file video.mkv is present inside the same root directory of my project. I will pass it as an argument in the below command as shown below

 

python app.py video.mkv

 

And now after execution of this command this will create a output directory called captured_frames which will contain all the frames as png image files of the video. The command will take time according to the length of the video

 

 

 

Leave a Reply