Home > Software design >  How to sort imageio glob frames numerically
How to sort imageio glob frames numerically

Time:03-14

I want to sort the frames so that it first is 0.png, 1.png, 2.png, 3.png etc

My code:

# Getting all the frames and saving them in array
image_path = Path('frames')
images = sorted(list(image_path.glob('*.png')))
image_list = []
for file_name in images:
    print(f"Got {file_name}")
    image_list.append(imageio.imread(file_name))


# Main Code
imageio.mimwrite('test.gif', image_list, format='GIF', fps=100, duration=0.2)

I have a folder in my directory called frames where multiple frames are stored like 0.png 1.png, 2.png etc

I want to sort them so that I can have a valid gif

CodePudding user response:

You can just count how many png files you have and then add them to the list

list = []
frameCount = len(glob.glob1(frames_path,"*.png"))
for i in range(0, frameCount):
    list.append(imageio.imread(frames_path   "/"   str(i)   ".png"))
    print("added "   str(i)   ".png")

CodePudding user response:

So if you use pathlib:

image_path = Path('frames')
images = sorted(
    list(image_path.glob('*.png')),
    key=lambda f: int(f.stem)
)

There is also a nice library called natsort to do natural sorting: natsort

  • Related