I'm trying to write a series of numpy array as an animated gif. I need to control strictly the colormap or palette (which color is associated with each integer value in the array), so that it matches the indices in the arrays
I found the imageio.mimwrite
. It has the ability to set the frame rate, and use compression, which seem great.
imageio.mimwrite('test.gif', ims, duration=0.2, subrectangles=True)
but I haven't found a way of setting a custom palette, only the number of colors seem to be settable... I know I can write image to disk and then imageio, but I would prefer not having to.
Using pillow, I can save the gif with custom palette:
im = Image.fromarray(...)
im.putpalette(...)
for i in im_list: i.putpalette(...)
im.save(filename, save_all=True, append_images=[image_list])
But I haven't found a way of setting both palette and framerate...
Any idea ?
Thanks!
In case it can help someone, here a piece of code that use PIL to save a palette animated gif with custom duration:
from PIL import Image
# image_list: list of numpy 2d uint8 array
# duration is a list of duration for each individual frame
# loop, 0 for infinite
# colormap_np : n by 3 uint8 array
pil_ims = [Image.fromarray(i, mode='P') for i in image_list]
pil_ims[0].save(
filename='test.gif',
save_all=True,
append_images=pil_ims[1:],
duration=duration,
loop=0,
palette=colormap.tobytes()
)