Python | Create video using multiple images using OpenCV (original) (raw)

Last Updated : 15 Nov, 2024

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:

Installing OpenCV and Pillow

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

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:

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.