0

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!

Behnam
  • 501
  • 1
  • 5
  • 21
  • 1
    You need to have the same number of digits when zero-padding for it to work. You should use `file_001.png`, `file_002.png` ... `file_010.png`, `file_011.png` ... `file_099.png` – Mark Setchell Nov 30 '18 at 10:40
  • I was expecting such a comment. Actually these .png files are created automatically with a loop, so I don't have control on their number of digits. The next comment by @Mike Scotty shows a better solution – Behnam Nov 30 '18 at 10:56
  • 1
    That's not correct - you do have control over the format of numbers when you formulate a filename - you can use `%04d` for the format, for example. – Mark Setchell Nov 30 '18 at 10:57
  • Thanks for the point! Actually as the number of my png files increased, I changed the numbering from serial numbers to dates. – Behnam Nov 30 '18 at 11:25

1 Answers1

3

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?

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50