The Wayback Machine - https://web.archive.org/web/20241121053833/https://www.geeksforgeeks.org/python-create-video-using-multiple-images-using-opencv/
Open In App

Python | Create video using multiple images using OpenCV

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Creating videos from multiple images is a great way for creating time-lapse videos. In this tutorial, we’ll explore how to create a video from multiple images using Python and OpenCV. Creating a video from images involves combining multiple image frames, each captured at a specific moment in time, into a single video file. This process requires:

  • Standardizing the dimensions of each frame, setting the frame rate, and defining a video codec.
  • By resizing images to a uniform dimension, setting a consistent frame rate, and appending each frame in sequence, OpenCV can create smooth videos.

Installing OpenCV and Pillow

To create videos using images, you’ll need the following Python libraries:

  • OpenCV (cv2): Essential for handling image and video-related tasks.
  • Pillow (PIL): Useful for opening, resizing, and handling images before they are processed by OpenCV.
pip install opencv-python pillow

Creating a Video from Multiple Images Using Python OpenCV

Preparing Images for Video Generation

OpenCV requires all frames to have the same dimensions for smooth playback. Before creating a video, you should ensure that all your images have the same width and height. Tasks for preparing images:

  • Calculate the average width and height of all images.
  • Resize images to a standardized dimension.
  • Save these resized images in a temporary directory (optional) or directly use them in the video generation process.

Using the Pillow library makes resizing simple and efficient, while OpenCV handles the video encoding and writing. Let’s import necessary Libraries, Set path to the Google Drive folder and count the number of images in the directory.

We have uploaded all images in drive folder, please refer to the folder for images path : https://drive.google.com/drive/folders/14Z3iASRYhob9cDohpVU-pcN9LgZ2Imqp

Python
import os
import cv2
from PIL import Image

# path to the Google Drive folder with images
path = "/content/drive/My Drive/Images"
os.chdir(path)

mean_height = 0
mean_width = 0

# Counting the number of images in the directory
num_of_images = len([file for file in os.listdir('.') if file.endswith((".jpg", ".jpeg", ".png"))])
print("Number of Images:", num_of_images)

Output:

Number of Images: 7

Standardizing Image Dimensions with Pillow (PIL)

To start, we’ll calculate the mean width and height of all images in the folder and then using the calculated mean dimensions, we’ll resize all images so they fit consistently into the video frames. The Pillow library allows us to resize images with the resize method, ensuring high-quality resizing.

Python
# Calculating the mean width and height of all images
for file in os.listdir('.'):
    if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"):
        im = Image.open(os.path.join(path, file))
        width, height = im.size
        mean_width += width
        mean_height += height

# Averaging width and height
mean_width = int(mean_width / num_of_images)
mean_height = int(mean_height / num_of_images)

# Resizing all images to the mean width and height
for file in os.listdir('.'):
    if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"):
        im = Image.open(os.path.join(path, file))
        # Use Image.LANCZOS instead of Image.ANTIALIAS for downsampling
        im_resized = im.resize((mean_width, mean_height), Image.LANCZOS)
        im_resized.save(file, 'JPEG', quality=95)
        print(f"{file} is resized")

Output:

Copy of 3d_1515.jpg is resized
Copy of 3d_1535.jpg is resized
Copy of 3d_1539.jpg is resized
Copy of 3d_1550.jpg is resized
Copy of 3d_1563.jpg is resized
Copy of 3d_1566.jpg is resized
Copy of 3d_1579.jpg is resized

Using OpenCV to Generate Video from Resized Images

With resized images ready, we can now use OpenCV to create a video. The VideoWriter function initializes the video file, while the write method appends each image frame to the video.

Python
# Function to generate video
def generate_video():
    image_folder = path
    video_name = 'mygeneratedvideo.avi'

    images = [img for img in os.listdir(image_folder) if img.endswith((".jpg", ".jpeg", ".png"))]
    print("Images:", images)

    # Set frame from the first image
    frame = cv2.imread(os.path.join(image_folder, images[0]))
    height, width, layers = frame.shape

    # Video writer to create .avi file
    video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 1, (width, height))

    # Appending images to video
    for image in images:
        video.write(cv2.imread(os.path.join(image_folder, image)))

    # Release the video file
    video.release()
    cv2.destroyAllWindows()
    print("Video generated successfully!")

# Calling the function to generate the video
generate_video()

Output:

Generated-Video

OpenCV to Generate Video from Resized Images

Note: This is just a snapshot of output, refer to link below for full output, https://drive.google.com/drive/folders/14Z3iASRYhob9cDohpVU-pcN9LgZ2Imqp

Full Code Implementation

Python
# Importing libraries
import os
import cv2
from PIL import Image

# Set path to the Google Drive folder with images
path = "/content/drive/My Drive/Images"
os.chdir(path)

mean_height = 0
mean_width = 0

# Counting the number of images in the directory
num_of_images = len([file for file in os.listdir('.') if file.endswith((".jpg", ".jpeg", ".png"))])
print("Number of Images:", num_of_images)

# Calculating the mean width and height of all images
for file in os.listdir('.'):
    if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"):
        im = Image.open(os.path.join(path, file))
        width, height = im.size
        mean_width += width
        mean_height += height

# Averaging width and height
mean_width = int(mean_width / num_of_images)
mean_height = int(mean_height / num_of_images)

# Resizing all images to the mean width and height
for file in os.listdir('.'):
    if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"):
        im = Image.open(os.path.join(path, file))
        # Use Image.LANCZOS instead of Image.ANTIALIAS for downsampling
        im_resized = im.resize((mean_width, mean_height), Image.LANCZOS)
        im_resized.save(file, 'JPEG', quality=95)
        print(f"{file} is resized")


# Function to generate video
def generate_video():
    image_folder = path
    video_name = 'mygeneratedvideo.avi'

    images = [img for img in os.listdir(image_folder) if img.endswith((".jpg", ".jpeg", ".png"))]
    print("Images:", images)

    # Set frame from the first image
    frame = cv2.imread(os.path.join(image_folder, images[0]))
    height, width, layers = frame.shape

    # Video writer to create .avi file
    video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 1, (width, height))

    # Appending images to video
    for image in images:
        video.write(cv2.imread(os.path.join(image_folder, image)))

    # Release the video file
    video.release()
    cv2.destroyAllWindows()
    print("Video generated successfully!")

# Calling the function to generate the video
generate_video()

Creating a video from images with Python and OpenCV is a powerful way to automate video generation tasks. This method is particularly useful in applications like time-lapse video creation, visualization, and scientific research.





Previous Article
Next Article

Similar Reads

Python - Process images of a video using OpenCV
Processing a video means, performing operations on the video frame by frame. Frames are nothing but just the particular instance of the video in a single point of time. We may have multiple frames even in a single second. Frames can be treated as similar to an image.So, whatever operations we can perform on images can be performed on frames as well
4 min read
Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
How to Display Multiple Images in One Window using OpenCV Python?
Prerequisites: Opencv In this article, we will show how to display Multiple Images In One window using OpenCV in Python. Approach Import moduleLoad the Multiple images using cv2.imread()Concatenate the images using concatenate(), with axis value provided as per orientation requirementDisplay all the images using cv2.imshow()Wait for keyboard button
1 min read
Resize Multiple Images using OpenCV-Python
In this article, we are going to write a python script using the OpenCV library to Resize Multiple Images and save them as an image file. Resizing the image refers to the growth of the images. Measurement works best in the use of multiple images and in machine learning applications. It helps to reduce the number of pixels from an image and that has
2 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Python | Denoising of colored images using opencv
Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images. Syntax: cv2.fastNlMeansDenoisingColor
1 min read
How to Detect Shapes in Images in Python using OpenCV?
Prerequisites: OpenCV OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function
3 min read
How to subtract two images using Python-OpenCV ?
In this article, we are going to see how to subtract two images using OpenCV in Python. Now, before getting into the topic we shall discuss some of the use cases of Arithmetic operations. Arithmetic operations like addition and subtraction can help us to make images brighter or darker. Specifically, subtraction of two images has a lot of purposes i
3 min read
Drawing with Mouse on Images using Python-OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will try to draw on images with the help of the mo
3 min read
Measure similarity between images using Python-OpenCV
Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let's find out which data image is more similar to the test image using python and OpenCV library in Python.Let's first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray
2 min read
Concatenate images using OpenCV in Python
To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as: hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical.Implementation using hconcat() and vconcat() on Arra
3 min read
Adding borders to the images using Python - OpenCV
Image processing is an interesting field in today's era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc. In this article, we will discuss how to add borders
1 min read
Cropping Faces from Images using OpenCV - Python
Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces. We will use a pre-trained Haar Cascade model to detect faces from the image. A haar cascade is the object dete
3 min read
How to Blur Faces in Images using OpenCV in Python?
Prerequisite: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the num
2 min read
Color Identification in Images using Python - OpenCV
An open-source library in Python, OpenCV is basically used for image and video processing. Not only supported by any system, such as Windows, Linux, Mac, etc. but also it can be run in any programming language like Python, C++, Java, etc. OpenCV also allows you to identify color in images. Don’t you know how to find these colors in images? Color Re
3 min read
Dividing Images Into Equal Parts Using OpenCV In Python
In this article, we are going to see how to divide images into equal parts using OpenCV in Python. We are familiar with python lists and list slicing in one dimension. But here in the case of images, we will be using 2D list comprehension since images are a 2D matrix of pixel intensity. Image Used: C/C++ Code import cv2 img = cv2.imread('img.jpg')
3 min read
Creating Hybrid Images Using OpenCV Library | Python
Hybrid image, or "multi-scale image", is an exciting concept in computer vision. They are created by blending one image's high-frequency components with another's low-frequency components. The result is an image that appears as one when viewed from a distance but shows a different image when viewed up close. The following are the steps for creating
4 min read
Python | Grayscaling of Images using OpenCV
Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white. Importance of grayscaling Dimension reduction: For example, In RGB images there are three color channels and three dimensions while grayscale images are single-dimensional.Reduce
5 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Python OpenCV - Depth map from Stereo Images
OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV Depth Map : A depth map is a picture where every pixel has depth information(rather than RG
2 min read
Watermarking images with OpenCV and Python
In this article, we are going to see how to make watermarking images using OpenCV in Python. Watermark is intentionally left Text/Logo onto the image. Watermarks are generally used by artists to protect the copyright of the image. Using watermarks we can ensure that the owner of the image is the person who imprinted the watermark on the image. Let'
4 min read
Detecting low contrast images with OpenCV, scikit-image, and Python
In this article, we are going to see how to detect low contrast images with OpenCV, scikit-image using Python A low contrast image has the minimal distinction between light and dark parts, making it difficult to tell where an object's boundary begins and the scene's background begins. For example The left one is low contrast and the right one is a
2 min read
Python | Play a video in reverse mode using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
3 min read
Converting Color video to grayscale using OpenCV in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
1 min read
Python - Displaying real time FPS at which webcam/video file is processed using OpenCV
We will be displaying the real-time processing FPS of the video file or webcam depending upon our choice.FPS or frame per second or frame rate can be defined as number of frames displayed per second. A video can be assumed as a collection of images or we can say frames which are displayed at some rate to produce motion. if you wish to identify the
4 min read
Get video duration using Python - OpenCV
OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. Prerequisites: Opencv moduledatetime moduleInstallation Opencv can be downloaded by running the
1 min read
How to draw Filled rectangle to every frame of video by using Python-OpenCV?
In this article, we will discuss how to draw a filled rectangle on every frame of video through OpenCV in Python. Stepwise Implementation:Import the required libraries into the working space.Read the video on which you have to write. Syntax: cap = cv2.VideoCapture("path") Create an output file using cv2.VideoWriter_fourcc() method. Here you will ha
2 min read
Python | Play a video using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos.  Let’s see how to play a video using the OpenCV Python. To capture a video, we need to create a VideoCapture object. VideoCapture have the d
2 min read
Draw geometric shapes on images using OpenCV
OpenCV provides many drawing functions to draw geometric shapes and write text on images. Let's see some of the drawing functions and draw geometric shapes on images using OpenCV. Some of the drawing functions are : cv2.line() : Used to draw line on an image. cv2.rectangle() : Used to draw rectangle on an image. cv2.circle() : Used to draw circle o
3 min read
three90RightbarBannerImg