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 thePillow
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
Pythonimportosimportcv2fromPILimportImage# path to the Google Drive folder with imagespath="/content/drive/My Drive/Images"os.chdir(path)mean_height=0mean_width=0# Counting the number of images in the directorynum_of_images=len([fileforfileinos.listdir('.')iffile.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 theresize
method, ensuring high-quality resizing.
Python# Calculating the mean width and height of all imagesforfileinos.listdir('.'):iffile.endswith(".jpg")orfile.endswith(".jpeg")orfile.endswith("png"):im=Image.open(os.path.join(path,file))width,height=im.sizemean_width+=widthmean_height+=height# Averaging width and heightmean_width=int(mean_width/num_of_images)mean_height=int(mean_height/num_of_images)# Resizing all images to the mean width and heightforfileinos.listdir('.'):iffile.endswith(".jpg")orfile.endswith(".jpeg")orfile.endswith("png"):im=Image.open(os.path.join(path,file))# Use Image.LANCZOS instead of Image.ANTIALIAS for downsamplingim_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. TheVideoWriter
function initializes the video file, while thewrite
method appends each image frame to the video.
Python# Function to generate videodefgenerate_video():image_folder=pathvideo_name='mygeneratedvideo.avi'images=[imgforimginos.listdir(image_folder)ifimg.endswith((".jpg",".jpeg",".png"))]print("Images:",images)# Set frame from the first imageframe=cv2.imread(os.path.join(image_folder,images[0]))height,width,layers=frame.shape# Video writer to create .avi filevideo=cv2.VideoWriter(video_name,cv2.VideoWriter_fourcc(*'DIVX'),1,(width,height))# Appending images to videoforimageinimages:video.write(cv2.imread(os.path.join(image_folder,image)))# Release the video filevideo.release()cv2.destroyAllWindows()print("Video generated successfully!")# Calling the function to generate the videogenerate_video()
Output:
OpenCV to Generate Video from Resized ImagesNote: 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 librariesimportosimportcv2fromPILimportImage# Set path to the Google Drive folder with imagespath="/content/drive/My Drive/Images"os.chdir(path)mean_height=0mean_width=0# Counting the number of images in the directorynum_of_images=len([fileforfileinos.listdir('.')iffile.endswith((".jpg",".jpeg",".png"))])print("Number of Images:",num_of_images)# Calculating the mean width and height of all imagesforfileinos.listdir('.'):iffile.endswith(".jpg")orfile.endswith(".jpeg")orfile.endswith("png"):im=Image.open(os.path.join(path,file))width,height=im.sizemean_width+=widthmean_height+=height# Averaging width and heightmean_width=int(mean_width/num_of_images)mean_height=int(mean_height/num_of_images)# Resizing all images to the mean width and heightforfileinos.listdir('.'):iffile.endswith(".jpg")orfile.endswith(".jpeg")orfile.endswith("png"):im=Image.open(os.path.join(path,file))# Use Image.LANCZOS instead of Image.ANTIALIAS for downsamplingim_resized=im.resize((mean_width,mean_height),Image.LANCZOS)im_resized.save(file,'JPEG',quality=95)print(f"{file} is resized")# Function to generate videodefgenerate_video():image_folder=pathvideo_name='mygeneratedvideo.avi'images=[imgforimginos.listdir(image_folder)ifimg.endswith((".jpg",".jpeg",".png"))]print("Images:",images)# Set frame from the first imageframe=cv2.imread(os.path.join(image_folder,images[0]))height,width,layers=frame.shape# Video writer to create .avi filevideo=cv2.VideoWriter(video_name,cv2.VideoWriter_fourcc(*'DIVX'),1,(width,height))# Appending images to videoforimageinimages:video.write(cv2.imread(os.path.join(image_folder,image)))# Release the video filevideo.release()cv2.destroyAllWindows()print("Video generated successfully!")# Calling the function to generate the videogenerate_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.