Extract and Saving Frame from Videos in Python

In this post, we are going to learn and build a python program where we are going to extract and save frames from videos using the OpenCV library.


OpenCV is one of the most commonly used libraries for computer vision tasks, such as reading and saving images, face recognition, segmentation, etc. It provides us with a list of powerful functions that can be used in image and video analysis.

Related Article

Implementation

Here, we are going to load all the modules and functions that we are going to use in this python program.

import os
import numpy as np
import cv2
from glob import glob

Here the create_dir function is used to create a directory.

def create_dir(path):
    try:
        if not os.path.exists(path):
            os.makedirs(path)
    except OSError:
        print(f"ERROR: creating directory with name {path}")

The save_frame function is used to extract the frame from the video and save them in the given path. The function takes the three arguments:

  • video_path: Path for the video.
  • save_dir: It is the directory where the frame needs to be saved.
  • gap: It determines the number of frames to be left in while saving two frames.
def save_frame(video_path, save_dir, gap=10):
    name = video_path.split("/")[-1].split(".")[0]

    save_path = os.path.join(save_dir, name)
    create_dir(save_path)

    cap = cv2.VideoCapture(video_path)
    idx = 0

    while True:
        ret, frame = cap.read()

        if ret == False:
            cap.release()
            break

        if idx == 0:
            cv2.imwrite(f"{save_path}/{idx}.png", frame)
        else:
            if idx % gap == 0:
                cv2.imwrite(f"{save_path}/{idx}.png", frame)

        idx += 1

The main where the program execution starts.

if __name__ == "__main__":
    video_paths = glob("videos/*")
    save_dir = "save"

    for path in video_paths:
        save_frame(path, save_dir, gap=10)

Nikhil Tomar

I am an independent researcher in the field of Artificial Intelligence. I love to write about the technology I am working on.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *