Search code examples
pythonimageopencvvideoframe

how to make a video from extracted frames?


I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

import cv2
import os


image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

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

cv2.destroyAllWindows()
video.release()

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.


Solution

    1. Print your images list and look at the order of your images? Are they sorted?
    2. What's the filename of your images? It's helpful to choose an increasing number like 00001.jpg and 00002.jpg instead of 1.jpg and 2.jpg this can mess up sorting.

      1. Sort the images after reading from os.listdir('.'): This is an example with pathlib library.
    for filename in sorted([e for e in path.iterdir() if e.is_file() and str(e).endswith(".png")]):
        print(filename)
        img = cv2.imread(str(filename))
        img_array.append(img)
    

    Or just using: for filename in sorted(os.listdir(path))