0

Im trying to make a gif but the order in which the images are displayed are not right. The images are save with the next format: 'IMG_1', and this is the code

def make_gif(frame_folder):
frames = glob.glob(f"{frame_folder}/*.png")
fps = 5
clip = mpy.ImageSequenceClip(frames, fps=fps)
clip.write_gif('movie.gif')

I sorted my list but displayed the same thingframes = sorted(glob.glob(f"{frame_folder}/*.png"))

And when I print the glob.glob it shows that the first image in the array it's the 'IMG_1' but then the second one it's the 'IMG_11'. And Im trying to put it in order, first the 'IMG_1' and then the 'IMG_2'

jeffoam
  • 11
  • 1
  • what is the output of your glob.glob when you print it? – Daraan Oct 18 '22 at 18:00
  • Have you tried sorting the `frames` list? – G. Anderson Oct 18 '22 at 18:01
  • I sorted my list but displayed the same thing. When I print the glob.glob it shows that the first image in the array it's the 'IMG_1' but then the second one it's the 'IMG_11'. And Im trying to put it in order, first the 'IMG_1' and then the 'IMG_2' – jeffoam Oct 18 '22 at 18:05
  • `I sorted my list but displayed the same thing` add that with the code into the question, the entire comment with the associated code, people don't have to read the comments to know what you want to ask. – Ahmed AEK Oct 18 '22 at 18:06
  • Does this answer your question? [Is there a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sort) – mkrieger1 Oct 18 '22 at 18:08
  • Thx guys it work with 'natsorted' – jeffoam Oct 18 '22 at 18:18
  • Your question isn't defined carefully. Please remove the unnecessary details and mention the important ones. – Dorrin Samadian Oct 18 '22 at 19:23

1 Answers1

0

You are sorting strings, which sort differently than numbers. Specifically, the order for strings will compare the first letter/element, then the second, then the third, whereas numbers sort based on place-value (not first/second, but tens/ones).

Using built-in sorted(iterable,key=func), you can use a function to define how you want to sort. In your case, it looks like you want to use the numbers that come after the '_' character in the name.

So you could do this:

frames = sorted(glob.glob(f"{frame_folder}/*.png"), key=lambda x: int(x.split('_')[-1]))

This defines a lambda function that will take the string from the list, separate it on the _ and just use the last element, and then turn that to an integer. After all that, it'll sort those integers and return the original strings/filenames based on that sort.

scotscotmcc
  • 2,719
  • 1
  • 6
  • 29