0

Essentially I have a directory of with images with the following naming convention frame{framenumber}.jpeg. However, when I implement the function below which aims to stitch these images into a video using the cv2 package there's this unanticipated behaviour where the files are read in the following order: ['frame0.jpg', 'frame1.jpg', frame10.jpg', '100.jpg', '101.jpg', '102.jpg', '103.jpg', 'frame104.jpg', 'frame105.jpg', 'frame106.jpg', 'frame107.jpg', 'frame108.jpg', 'frame109.jpg', 'frame11.jpg', 'frame110.jpg',...] so at it no chronological and it looks kinda funny because at least every 10 frame is from a completely different segment of the video. Is there an obvious solution to this problem (some better way of reading in the images of some naming convention I'm not aware of)?

def makevideo():
    img_array = []
    filenames = [] 
    for filename in glob.glob(r'D:\Uni work\Engineering Mathematics Work\MDM3\Mojo\mojo_sperm_tracking_data_bristol\tp49\*.jpg'):
        img = cv2.imread(filename)
        height, width, layers = img.shape
        size = (width,height)
        filenames.append(filename)
        img_array.append(img)
    
    print(filenames)   
    out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, size)

    for i in range(len(img_array)):
        out.write(img_array[i])
    out.release()

Thanks in advance!

1 Answers1

0

Files on the filesystem are not sorted. You need thesort the resulting filenames yourself using the sorted() function:

import re
numbers = re.compile(r'(\d+)')
def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

 for filename in sorted(glob.glob(r'D:\Uni work\Engineering Mathematics Work\MDM3\Mojo\mojo_sperm_tracking_data_bristol\tp49\*.jpg'), key=numericalSort):
Ceopee
  • 316
  • 4
  • 12
  • I have tried implementing your solution but unfortunately, it gives the same result as before. The only way I can think of is to use zero-filled numbers since it's the numbers <100 that are problematic. – ConsistentC Feb 02 '21 at 12:40