Video Pre-processing Module Tutorial
This Python module provides functionality for extracting frames from videos. The features of this module are:
- Creating a ‘./images’ folder, if it does not exist already.
- Reading all videos from a given videos folder and a specified video extension (default mp4).
- Saving all frames or one frame per second, from a video in corresponding images folder with the same video file name.
Dependencies
Before starting, make sure that you have the following libraries installed. If not, you can install them using pip:
pip install opencv-python numpy
Function: create_folder()
This function creates a folder at the specified directory if it does not exist already.
Input:
dir
: The directory where the folder should be created.
Function: main()
The main function runs when the Python file is called from the terminal. It verifies the existence of the videos folder, creates the output folder if it doesn’t exist, reads all video files from the videos folder, and for each video file, it creates an images sub-folder and saves frames according to the specified sampling mode.
Input
An argparse.Namespace
object that contains the following parameters:
videos_folder
: The directory containing the videos. This is a required parameter.video_format
: The format of the videos (e.g., mp4, avi). The default is ‘mp4’.image_format
: The format for the output images (e.g., jpg, png). The default is ‘jpg’.sampling_mode
: The mode for frame extraction. The choices are ‘fixed_frames’, ‘every_frame’, and ‘per_second’. The default is ‘every_frame’.num_frames
: The number of frames to extract. The default is 10.output_folder
: The path to save the extracted frames. The default is../data/ucf_sports_actions/frames
.
Example Usage
The typical usage from the command line would look like this:
python video_preprocessing.py --videos_folder ./videos/ --video_format mp4 --image_format jpg --sampling_mode per_second --num_frames 30 --output_folder ./frames/
This command will read MP4 videos from the ./videos/
directory, extract one frame per second up to 30 frames from each video, save them as JPG images, and save the result in the ./frames/
directory.
In case you want to use it inside another Python script, here is how you would do it:
import argparse
from video_preprocessing import main, create_folder
options = argparse.Namespace(
videos_folder='./videos/',
video_format='mp4',
image_format='jpg',
sampling_mode='per_second',
num_frames=30,
output_folder='./frames/'
)
main(options)
This module is handy for preprocessing video data for machine learning tasks. You can adjust the parameters to suit your specific needs.
* This tutorial has been made with the help of ChatGPT 4.0.