Behnam
Behnam

Reputation: 511

images order while making gif using imageio

I am making a gif by imageio module using generated .png files. Although the .png files are sorted and in an order of numbers, the generated .gif animation does not follow this order. What is the reason? Here is my code so far:

png_dir='png'
images=[]
for file_name in os.listdir(png_dir):
    if file_name.endswith('.png'):
        file_path = os.path.join(png_dir, file_name)
        images.append(imageio.imread(file_path))
imageio.mimsave('movie.gif', images, duration=1)

and the .png files are like file_01.png, file_02.png ... file_099.png

Why the gif is not generated with the same order of the .png files?

Thanks in advance for any help!

Upvotes: 0

Views: 2097

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

You are assuming that the files are ordered, but the docs of os.listdir state (emphasis mine):

os.listdir(path='.')

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.

You can sort the returned list yourself:

for file_name in sorted(os.listdir(png_dir)):

Note: Python has no built-in natural sorting. if that's what you're looking for you should check the answers in this question: Does Python have a built in function for string natural sort?

Upvotes: 3

Related Questions