Click here to Skip to main content
15,615,787 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to create a video of a sequence of images in python. I found this code online that works fine but I am having a small problem with the ordering of the images when being read in python although I have already used the sort() function. The ordering in the folder is ok. The name of images in the file is FRD 0, FRD 1, FRD 2, FRD 3......till FRD 200.

What I have tried:

# Import required library
import cv2
import os
import re

# Read the image folder
# Video name to be created
image_folder = 'D:\A.Project\FRD file'
video_name = 'video.avi'

# Get the list of images from specified directory.
# Read the images from the specified file
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
    return [
        if text.isdigit() else text.lower()
        for text in _nsre.split(s)]

sorted_images = sorted(images, key=natural_sort_key)

# Video codec, frame rate , frame size
video = cv2.VideoWriter(video_name, 0, 1, (width,height))

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

# Close all the frames
# When everything done, release the video
Updated 19-Apr-21 8:20am
Richard MacCutchan 19-Apr-21 11:48am    
" am having a small problem with the ordering of the images"
What problem?
newbie0 19-Apr-21 12:19pm    
The video I get is not following the order.
Richard MacCutchan 19-Apr-21 12:22pm    
If you expect people here to help you, then you need to explain your problem in proper detail. We have no idea what order you expect and what order you receive.
newbie0 19-Apr-21 13:09pm    
I have a file of 200 images. I wanted to create a video with these images. I can get the video using the coding that I posted. But the problem is the video is not showing the images by following the order, for example, image 1, image 2 ,image 3, instead it show something like image 1,image 4,image 10.......
Richard MacCutchan 20-Apr-21 3:26am    
Look at your compare function used by the sort. A quick test will show you what order it is creating.

1 solution

You're getting the list of files, but they are in the order returned by the file system.
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]

If your filenames are "image 1.png", "image 2.png", ... You're going to have to add a counting loop to your code to build the exact filename you need to deal with, in the order specified by your loop. You have done loops with an index value, right?
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900