Home > Back-end >  OpenCV - Creating a video from a set of images in a directory
OpenCV - Creating a video from a set of images in a directory

Time:10-21

I am trying to create a video from a sequence of images. Below is my code.

import os
import cv2

mean_width = 6000
mean_height = 4000

def generate_video():
    image_folder = 'C:/New folder/Images/q/'
    video_name = 'myvideo.avi'
    os.chdir("C:/New folder/Images/q/")

    images = [img for img in os.listdir(image_folder)
              if img.endswith(".jpg") or
              img.endswith(".jpeg") or
              img.endswith("png")]#I'll use my own function for that, just easier to read

    frame = cv2.imread(os.path.join(image_folder, images[0]))   
    height, width, layers = frame.shape
    video = cv2.VideoWriter(video_name, 0, 0.25, (width, height))#0.25 so one image is 4 seconds

    for image in images:        
    video.write(cv2.imread(os.path.join(image_folder, image)))

    cv2.destroyAllWindows()
    video.release()
generate_video()

The above code however creating the video just with one image. There are 5 other images as well in the folder C:/New folder/Images/q/ but the video is generated only for the first one. Can someone please advise if anything is missing here ? Seems like the for loop is not working

CodePudding user response:

To make a video you need your images to have the same resolution. If some images have different sizes cv2.VideoWriter quietly skips them without any errors.

So you may need to resize your images to fixed size:

for image in images:
    image = cv2.imread(os.path.join(image_folder, image))
    image = cv2.resize(image, (width, height))
    video.write(image)

An example to reproduce this behavior:

import cv2
import numpy as np

fc = cv2.VideoWriter_fourcc(*"mp4v")
video = cv2.VideoWriter("1.mp4", fc, 0.25, (500, 500))

for idx in range(10):
    color = np.random.randint(0, 255, size=3)
    if idx in [0, 2, 3]:  # only 3 frames will be in the final video
        image = np.full((500, 500, 3), fill_value=color, dtype=np.uint8)
    else:
        # slighly different size
        image = np.full((400, 500, 3), fill_value=color, dtype=np.uint8)

    video.write(image)
  • Related