Unlock the secrets of your code with our AI-powered Code Explainer. Take a look!
In today's tutorial, we will look at how to create videos from arrays of images; this could come in handy when you have made a lot of images for a timelapse or something similar and want to create a video from them.
Note that we also have a tutorial on doing the other way around, which is extracting images from video; you can check it out here.
We will make the script a command-line tool, utilizing the built-in argparse
library to parse the CLI
arguments. Let's get started!
We start by installing the necessary libraries; in this case, the only nonstandard library we need is OpenCV
, which we can install using pip
:
$ pip install opencv-python
At the top of our script, we import the necessary libraries:
import cv2
import argparse
import glob
from pathlib import Path
import shutil
Next, set up the argument parser
and parse the arguments:
# Create an ArgumentParser object to handle command-line arguments
parser = argparse.ArgumentParser(description='Create a video from a set of images')
# Define the command-line arguments
parser.add_argument('output', type=str, help='Output path for video file')
parser.add_argument('input', nargs='+', type=str, help='Glob pattern for input images')
parser.add_argument('-fps', type=int, help='FPS for video file', default=24)
# Parse the command-line arguments
args = parser.parse_args()
As you see, we have three available parameters. The first two are the output path and the input images, and the third is the FPS for the video, which is an option. The input images are a glob pattern, so you can use wildcards to match multiple files, for example, pictures/*.png
, to match all PNG files in the pictures
directory.
The input
is a list because on Linux, if you use wildcards in the input, the shell will expand the wildcards before the script runs, so we need to be able to handle multiple input files.
So, we loop over the input files and expand the globs. So, this script will work on both Windows and Linux:
# Create a list of all the input image files
FILES = []
for i in args.input:
FILES += glob.glob(i)
Continuing, we set up the video. We get the image dimensions from the first image and then create the video writer object. We also set the codec to mp4v
, the codec for the mp4 format:
# Get the filename from the output path
filename = Path(args.output).name
print(f'Creating video "{filename}" from images "{FILES}"')
# Load the first image to get the frame size
frame = cv2.imread(FILES[0])
height, width, layers = frame.shape
# Create a VideoWriter object to write the video file
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(filename=filename, fourcc=fourcc, fps=args.fps, frameSize=(width, height))
Then, we loop over the images and add them to the video. During this script phase, the video file will be in the current working directory:
# Loop through the input images and add them to the video
for image_path in FILES:
print(f'Adding image "{image_path}" to video "{args.output}"... ')
video.write(cv2.imread(image_path))
After that, we also need two calls and two functions to close the video-making process:
# Release the VideoWriter and move the output file to the specified location
cv2.destroyAllWindows()
video.release()
Because the video file is in the current directory, we move it to the output directory:
shutil.move(filename, args.output)
This script is very well suited for tasks like creating a timelapse video from a series of images because the images and the video aren't stored in memory, so you can make a video from many images without running out of memory.
You could also modify this script to import it from another script and use it as a function, but for now, we will keep it as a standalone script.
So that's it. Now, you know how to create a video from a list of images using OpenCV and Python. You can check the complete code here.
Learn also: How to Extract Audio from Video in Python.
Happy coding ♥
Just finished the article? Why not take your Python skills a notch higher with our Python Code Assistant? Check it out!
View Full Code Assist My Coding
Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!