Skip to content

Instantly share code, notes, and snippets.

@nirum
Last active April 7, 2019 07:19
Show Gist options
  • Save nirum/d4224ad3cd0d71bfef6eba8f3d6ffd59 to your computer and use it in GitHub Desktop.
Save nirum/d4224ad3cd0d71bfef6eba8f3d6ffd59 to your computer and use it in GitHub Desktop.
Save a numpy array (a stack of images) as a gif using moviepy
import os
from moviepy.editor import ImageSequenceClip
def gif(filename, array, fps=10, scale=1.0):
"""Creates a gif given a stack of images using moviepy
Notes
-----
works with current Github version of moviepy (not the pip version)
https://github.com/Zulko/moviepy/commit/d4c9c37bc88261d8ed8b5d9b7c317d13b2cdf62e
Usage
-----
>>> X = randn(100, 64, 64)
>>> gif('test.gif', X)
Parameters
----------
filename : string
The filename of the gif to write to
array : array_like
A numpy array that contains a sequence of images
fps : int
frames per second (default: 10)
scale : float
how much to rescale each image by (default: 1.0)
"""
# ensure that the file has the .gif extension
fname, _ = os.path.splitext(filename)
filename = fname + '.gif'
# copy into the color dimension if the images are black and white
if array.ndim == 3:
array = array[..., np.newaxis] * np.ones(3)
# make the moviepy clip
clip = ImageSequenceClip(list(array), fps=fps).resize(scale)
clip.write_gif(filename, fps=fps)
return clip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment