Creating Animated Gif with Imageio

making gif from images using imageio in python

This works for me:

import os
import imageio

png_dir = '../animation/png'
images = []
for file_name in sorted(os.listdir(png_dir)):
if file_name.endswith('.png'):
file_path = os.path.join(png_dir, file_name)
images.append(imageio.imread(file_path))

# Make it pause at the end so that the viewers can ponder
for _ in range(10):
images.append(imageio.imread(file_path))

imageio.mimsave('../animation/gif/movie.gif', images)

images order while making gif using imageio

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?

Programmatically generate video or animated GIF in Python?

Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They have a Python wrapper but it looks pretty crappy and unsupported. Still open to other suggestions.

Custom Frame Duration for Animated Gif in Python ImageIO

mimsave does not accept 4 positional arguments. Anything beyond the 3rd argument must be provided as a keyword argument. In other words, you have to unpack kargs like so:

imageio.mimsave(exportname, frames, 'GIF', **kargs)

gif generating using imageio.mimwrite

I found I can save it as bytes with the following code

gif_encoded = iio.mimsave("<bytes>", images, format='gif')

it will save the GIF as bytes then you can encode it.

encoded_string = base64.b64encode(gif_encoded)
encoded_string = b'data:image/gif;base64,'+encoded_string
decoded_string = encoded_string.decode()

for more examples check this out
https://imageio.readthedocs.io/en/stable/examples.html#read-from-fancy-sources



Related Topics



Leave a reply



Submit