如何修复以随机顺序写入视频的图像

How to Fix Images Being Written to Video in Random Order

我正在尝试编写 271 张已经按数字顺序排列的模拟图像('0.jpg','1.jpg', ..., '271.jpg' ) 成视频。 cv2.videoWriter 似乎以随机顺序写入所有这些图像,生成的视频与模拟中应该发生的情况不一致。

我已经尝试过使用 glob,其结果与使用 os.path

的结果相同
import numpy as np
import os
from os.path import isfile, join

pathIn= 'path/simulation/'
pathOut = 'video.avi'

fps = 10 

frame_array = []

files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]

# for sorting the file names properly
files.sort(key = lambda x: x[5:-4])
files.sort()
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]

for i in range(len(files)):
    filename=pathIn + files[i]
    # reading each file
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)

    # inserting the frames into an image array
    frame_array.append(img)

out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)

for i in range(len(frame_array)):
    # writing to a image array
    out.write(frame_array[i])
out.release()

转换为视频的图像的预期顺序:

'0.jpg', '1.jpg', ...'271.jpg'

实际结果:

'31.jpg', '230.jpg', '12.jpg', ...

有两个问题
files.sort(key = lambda x: x[5:-4])
files.sort()

首先,'0.jpg'[5:-4] 生成一个空字符串。我想你想要像

这样的东西
file.sort(key = lambda x: int(x[:-4]))

其次,您通过再次排序丢弃了结果。放弃第二类。