There are different libraries in python for processing images and videos. We can read videos using python modules like moviepy, opencv, sckit video etc. These libraries also provide tools to write videos in required specification. In this tutorial we are using pillow to read images scikit video to write frames to a video. To get started, you must have python installed and install these libraries.

pip install pillow scikit-video numpy

http://www.scikit-video.org/stable/

If you have alread images stored in a numpy array, you can simple write them in output mp4 file.

import skvideo.io
import numpy as np

# we create frames using numpy random method
outputdata = np.random.random(size=(5, 720, 1280, 3)) * 255
outputdata = outputdata.astype(np.uint8)

# save array to output file
skvideo.io.vwrite("outputvideo.mp4", outputdata)

Now if we want to customize writer and we need to writer data using writer, we can create a video writer using scikit video. We will provide video save path and frames per second with video encoding quality and preset. You can change these settings according to your requirements and also you can view complete options on scikit video library homepage.

import skvideo.io

# save path and fps
video_save_path = "output.mp4"
fps = 30
# create writer using FFmpegWriter
writer = skvideo.io.FFmpegWriter(video_save_path, 
                        inputdict={'-r': str(fps)},
                        outputdict={'-r': str(fps), '-c:v': 'libx264', '-preset': 'ultrafast', '-pix_fmt': 'yuv444p'})

Now we iterate over all images in directory and read images using pillow. After we read an image, we can convert it to numpy array and write using writer.writeFrame() method.

import numpy as np
import os
from PIL import Image

base_path = "IMAGES_DIRECTORY"
# iterate over each image using os module
for img in os.listdir(base_path):
    image = Image.open(os.path.join(base_path, img)) # read image
    image = np.array(image, dtype=np.uint8) #convert to unit8 numpy array
    
    # write frame
    writer.writeFrame(image)

# close writer
writer.close()

This will write it to path we provided while writing video file. There are different options available for input and output dictionary of writer that we can futher explore.tpg