Creating a Video from Images Using Python

python_create_video_from_images

Turning a series of images into a video is a common requirement in animation, data visualization, and media production. Python offers powerful libraries like OpenCV and Moviepy, making it easy to automate combining images into high-quality video files.

In this article, we’ll guide you through using these libraries to create videos efficiently. Additionally, we’ll see how Cloudinary can store your images and seamlessly generate videos through its API. So let’s get started!

In this article:

How Can You Use Python to Create Video from Images?

Creating a video from images in Python involves combining multiple image files into a video format. As mentioned above, Python provides several libraries and tools to simplify this process. Here’s some commonly used options:

  • OpenCV: An open-source library offering comprehensive tools for image and video processing. It supports various video formats and allows precise video creation and editing control.
  • Moviepy: A user-friendly library for video editing that simplifies tasks like creating videos from images, adding audio tracks, and applying effects. It is ideal for rapid prototyping and straightforward video tasks.
  • FFmpeg: A powerful command-line tool with Python bindings available. FFmpeg is renowned for its versatility and extensive format support, making it suitable for complex video processing tasks.
  • Pillow: Primarily an image processing library, Pillow can be used with other tools like OpenCV or Moviepy to handle image processing before creating videos.
  • Cloudinary: A cloud-based service that provides an API for managing and transforming media. With Cloudinary, you can upload images and generate videos directly from them, leveraging its powerful cloud-based processing and delivery capabilities.

Each tool offers different strengths, so you can choose the one that best suits your project’s requirements and workflows.

python_create_video_from_images

Building Our Own Python Tool to Create Video From Images With OpenCV

Let’s look at how to convert a series of images into a video using OpenCV.

To begin, start by importing the necessary libraries. We need OpenCV for video creation and OS for file handling. We will also need to specify the directory where your images are stored and the path where you want to save the output video:

import cv2
import os

# Define input and output paths

image_folder = './images/'  # Replace with the path to your images

video_name = 'output_video.mp4' # Name of the output video file

Next, we list all the image files in the specified directory using the OS library. We will also use OpenCV to get the dimensions of the video by reading the dimensions of the first image to obtain its size:

# Get list of images
images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]

# Read the first image to get the size
first_image = cv2.imread(os.path.join(image_folder, images[0]))
height, width, _ = first_image.shape

Finally, create a VideoWriter object and specify the codec (e.g.,'mp4v' for mp4 video formats), frame rate, and resolution. Now loop through each image, read it, and write it to the video file. After completion, release the VideoWriter object to finalize the video file:

# Initialize video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Use 'mp4v' for MP4 format
video = cv2.VideoWriter(video_name, fourcc, 20, (width, height))

# Add images to the video
for image in images:
    img_path = os.path.join(image_folder, image)
    frame = cv2.imread(img_path)
    video.write(frame)

# Release the video writer
video.release()
cv2.destroyAllWindows()

How to Create Video From Images With Cloudinary

Cloudinary is a powerful cloud-based media management platform that simplifies creating video content from still images. Its intuitive API and user-friendly interface make it accessible to users of all technical backgrounds, allowing you to generate videos without the complexities of coding or server configurations.

Let’s examine how Cloudinary makes it easy to create videos from images. For this tutorial, we’ll use images extracted from blue-sports-car.mp4, which is in the Cloudinary demo cloud.

To convert images to a video, we will first initialize our Cloudinary API and define the images that we need to upload to the Cloudinary cloud.

import cloudinary
from cloudinary import uploader
import os

cloudinary.config(
    cloud_name="your_cloud_name",
    api_key="your_api_key",
    api_secret="your_api_secret"
)

# Define input and output paths
image_folder = './images/'  # Replace with the path to your images
video_name = 'output_video.mp4'        # Name of the output video file

# Define image paths and public IDs
image_public_ids = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
tag = 'my_gif'

Here, in addition to the Cloudinary credentials, we define a path containing our images and give the output file a name. We also use OS to iterate over the images in the image folder and add them to a list.

Next, we iterate over the public IDs of our images and upload them to the Cloudinary cloud.

# Upload images with a shared tag
for public_id in image_public_ids:
    uploader.upload(image_folder + f"{public_id}", public_id=public_id, tags=[tag])

Finally, we use the Cloudinary uploader’s multi() method to convert our images to an mp4 format. We then print the URL of our video on the terminal.

# Create the video
result = uploader.multi(tag, format="mp4")
video_url = result["url"]

print(video_url)

As you can see, Cloudinary makes it very easy to convert images into video. In addition to its simplicity, Cloudinary gives you granular control over other aspects of your assets, allowing you to add transformations or other effects you may want to define.

With Cloudinary’s efficient processing and optimization capabilities, you can easily create high-quality videos from your image assets. Here is what our final video looks like:

python_create_video_from_images

Make an Impact, Not a Slideshow

Creating videos from images is a transformative way to present information and tell stories more dynamically than static slideshows ever could. Python offers powerful libraries that enable you to convert images into high-quality videos with precision and ease. These tools provide a range of functionalities, from simple image sequencing to complex video editing, catering to various needs and expertise levels.

For those looking to streamline their video creation process even further, Cloudinary offers an excellent solution. Cloudinary’s cloud-based service not only simplifies the process of creating videos from images through its robust API but also handles video storage, optimization, and delivery with remarkable efficiency.

So are you ready to elevate your video creation workflow? Create an account today and discover how effortless and powerful video production can be.

More from Cloudinary:

Video Uploads With Cloudinary

Reducing the Size of Animated GIFs and Converting Them to WebM or MP4 Through Automation

QUICK TIPS
Matthew Noyes
Cloudinary Logo Matthew Noyes

In my experience, here are tips that can help you better manage and optimize your process for creating videos from images using Python:

  1. Choose the right frame rate based on your content
    When creating a video from images, the frame rate (fps) plays a significant role in how smooth your video looks. For animations or fast sequences, a higher frame rate like 24-30 fps is recommended. For slideshows or slow transitions, 10-15 fps is sufficient. Adjust the frame rate dynamically based on your content to control video pacing.
  2. Pre-process images for consistency
    Ensure all images are the same dimensions before converting them into a video. Use PIL (Pillow) to resize or crop images as needed. Any size inconsistency can result in a distorted or uneven video output. Consistent dimensions also make the VideoWriter initialization in OpenCV or other tools much smoother.
  3. Use imutils for image sequence sorting
    When dealing with a large number of sequentially named images, use the imutils.paths module for proper ordering. This module handles the sorting of filenames more effectively, avoiding mismatches in order that could break the video’s continuity.
  4. Optimize image formats before video generation
    If file size or quality is a concern, convert images to a more efficient format like WEBP or apply JPEG compression before adding them to the video. This reduces the overall memory usage and helps maintain a consistent video quality without overwhelming storage resources.
  5. Experiment with different codecs for optimal quality and compatibility
    The fourcc codec parameter in OpenCV (cv2.VideoWriter_fourcc) greatly impacts the output quality and format compatibility. While mp4v is widely supported, XVID or H264 may offer better quality or compression. Test different codecs to find the best fit for your application.
  6. Add dynamic overlays and text using MoviePy
    If you need to include text overlays, transitions, or additional effects, consider using MoviePy instead of OpenCV. MoviePy provides more advanced video editing features like text annotation, image fading, and scene transitions, making it ideal for creating polished videos.
  7. Consider the timing and order of frames
    For presentations or narrative-driven videos, adjust the display time for each frame by duplicating frames or manually setting the frame duration. For example, an intro image might be displayed longer, whereas subsequent images transition faster. This technique can help create a more professional, dynamic video.
  8. Integrate audio tracks for a richer experience
    Use moviepy.editor.VideoFileClip to add background music or narration to your video. Matching the timing of audio and visuals can significantly enhance the viewing experience. Use set_audio and concatenate_audioclips to synchronize audio with specific frames.
  9. Implement error handling and progress tracking
    When dealing with large image sets, it’s useful to include error handling and log messages. Use try-except blocks to catch errors during image loading or video frame insertion. Additionally, implement a progress bar (using tqdm) to monitor the conversion process, especially for large datasets.
  10. Use Cloudinary’s animated transformations for advanced sequences
    Cloudinary’s API offers advanced options for creating videos from images, such as setting specific delays between frames, adding captions, and integrating smooth transitions. Explore Cloudinary’s animated transformations, like applying filters, fades, and text overlays directly through the API, to create dynamic, server-side rendered videos with minimal local processing.

These tips will streamline your video creation process and help you produce professional, high-quality videos from images using Python. Leveraging Cloudinary’s features can further optimize and automate the entire workflow, making your image-to-video transformations more efficient and visually impactful.

Last updated: Oct 3, 2024