Python OpenCV - Create Video from Images


Python OpenCV cv2 - Create Video from Images

In this tutorial, we shall learn how to create a video from image numpy arrays.

We shall go through two examples. The first one reads images from the file system and creates a video. The second example creates a video directly from the programmatically generated numpy arrays.

To create a video from Image Arrays, follow the below sequence of steps.

  1. Initialize a Video Writer with the following items specified.
    • Output Video File Name
    • fourcc code that specifies the codec
    • Number of Frames per Second
    • Video Frame Size
  2. Write each image array to the Video Writer object.
  3. Release the Video Writer.

Examples

1. Create video from images in a folder

In this example, we shall read images, present in a folder, one by one. Then we shall use Video Writer to write each image, in a loop, to the video output file.

Python Program

import cv2
import numpy as np
import glob

frameSize = (500, 500)

out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)

for filename in glob.glob('D:/images/*.jpg'):
    img = cv2.imread(filename)
    out.write(img)

out.release()
  • 'output_video.avi' is the video output file name.
  • cv2.VideoWriter_fourcc(*'DIVX') is the codec.
  • 60 is the number of frames per second. So, 60 images shall be used to create a video of duration one second. You may change this value as per the requirement.
  • frameSize = (500, 500) defines the width and height of the output video.

In the above program, the for loop reads all the .jpg files one by one to a numpy array using cv2.imread(). And the image numpy array is written to video file using Video Writer.

Please note that the order of images that is written to the video file depends on how glob reads the files from the folder.

You may control the order of files you read in the for loop, thus controlling the order of images in the video.

2. Create video from Numpy Arrays

In this example, we shall create an Python array of numpy arrays. We shall then use it

Python Program

import cv2
import numpy as np
 

frameSize = (500, 500)

out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)

for i in range(0,255):
    img = np.ones((500, 500, 3), dtype=np.uint8)*i
    out.write(img)

out.release()

Summary

In this tutorial of Python Examples, we learned how to write images to a Video file using Python OpenCV cv2 library.