简体   繁体   中英

Python: wrong iteration through images

I have a folder that has 196 .jpg images. With the following code i can create a mp4 video out of those images.

The code is working and i can watch the video:

import cv2
import os

image_folder = 'im/img_jpg/'
video_name = 'video.mp4'

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

fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter(video_name, fourcc, 20.0, (width,height))

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

cv2.destroyAllWindows()
video.release()

But now I run in a problem. The video is not correct, because the images are not in correct order. Printing "images" looks like this:

print(images)
['00000158.jpg', '00000164.jpg', '00000170.jpg', '00000038.jpg', '00000010.jpg', ...

It should be:

['00000001.jpg', '00000002.jpg', '00000003.jpg', '00000004.jpg', '00000005.jpg', ...

What am I doing wrong?

os.listdir以任意顺序返回文件名,您可以调用images.sort()进行排序。

Just sort items in list with sorted() function. As I remember, when you list items with os module they're sorted in the same way as you see them in explorer.

Try:

images = sorted([img for img in os.listdir(image_folder) if img.endswith(".jpg")])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM