GIF animation in Python in 3 Steps

Gif Animation in PythonGIF animation in Matlab in 3 steps is a popular post here on this blog. Learnt the technique while trying to plot the results from the Karhunen-Loeve Expansion in September 2012.

Since then, I have moved from matlab to python.

But I wanted to recreate that same thing in Python. This is where I have to say, Matlab is like iOS and Python is Android. For doing this in Matlab, all ingredients were in place, but in python, this isn’t the case.

So here are the 3 long steps in Python to get a GIF animation.

Step 1:
Download Figtodat and images2gif

Step 2:
Import Figtodat and writeGif

import Figtodat
from images2gif import writeGif

Step 3:
Collect the figures into an array and call writeGif to get the animation


figure = plt.figure()
plot   = figure.add_subplot (111)
plot.hold(False)
images=[]
y = numpy.random.randn(100,5)
for i in range(y.shape[1]):
    plot.plot (numpy.sin(y[:,i]))  
    im = Figtodat.fig2img(figure)
    images.append(im)

writeGif("images.gif",images,duration=0.3,dither=0)

Don’t want to spend time finding the listed modules, download them directly from the link at the end of the post.

Here’s the complete code.

# -*- coding: utf-8 -*-
"""
@author: Sukhbinder Singh
"""
import Figtodat
from images2gif import writeGif
import matplotlib.pyplot as plt
import numpy
    
figure = plt.figure()
plot   = figure.add_subplot (111)
    
plot.hold(False)
    # draw a cardinal sine plot
images=[]
y = numpy.random.randn(100,5)
for i in range(y.shape[1]):
    plot.plot (numpy.sin(y[:,i]))  
    plot.set_ylim(-3.0,3)
    plot.text(90,-2.5,str(i))
    im = Figtodat.fig2img(figure)
    images.append(im)

writeGif("images.gif",images,duration=0.3,dither=0)

Download all files

Advertisements

27 thoughts on “GIF animation in Python in 3 Steps

  1. your code doesnot work:

    File “…./Figtodat.py”, line 27, in fig2data
    buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
    AttributeError: ‘FigureCanvasMac’ object has no attribute ‘tostring_argb’

    Like

  2. Hi, i faced a problem when i try to run your testing_GIF.py.
    The problem is

    File “images2gif.py”, line 223, in _writeGifToFile
    fp.write(globalPalette)

    TypeError: must be string or buffer, not None

    I checked the function _writeGifToFile, the getheader(im)[1] always return ‘None’, thats the reason globalPalette is ‘None’.

    PIL is installed, my python version is 2.7.10, and numpy version is 1.9.2

    What would be the possible problem and solution?

    Like

  3. Hi, i face a problem when i try to run your testing_GIF.py.
    The problem is

    File “images2gif.py”, line 223, in _writeGifToFile
    fp.write(globalPalette)

    TypeError: must be string or buffer, not None

    I checked the function _writeGifToFile, the getheader(im)[1] always returns ‘None’. Thats the reason that globalPalette is ‘None’.

    My python version is 2.7.10, numpy version is 1.9.2, and PIL is installed.
    So what would be the possible problem and solutions?

    Regards,
    Lee

    Like

    • Hi there

      Thanks for the comment. I am aware that now the code is not working. Because of some changes in matplotlib, something is broken.

      I will try to find some time to dig into this issue this weekend.

      Thanks

      Like

  4. Thanks a lot for this post, however, I downloaded your zip file and run the code with the following error message. I tried update PIL and replaced `PIL.Image.fromString` to `PIL.Image.frombytes` but still the same error message as follows:

    I am using Mac OsX and python 2.7 and other libraries are quite recent.
    Could you help me to find out why? Thanks a lot
    “`
    TypeError Traceback (most recent call last)
    in ()
    18 images.append(im)
    19
    —> 20 writeGif(“images.gif”,images,duration=0.3,dither=0)

    /Users/Natsume/Downloads/python_gif/images2gif.pyc in writeGif(filename, images, duration, repeat, dither, nq)
    350 # Write
    351 try:
    –> 352 n = _writeGifToFile(fp, images2, duration, loops)
    353 finally:
    354 fp.close()

    /Users/Natsume/Downloads/python_gif/images2gif.pyc in _writeGifToFile(fp, images, durations, loops)
    221 # Write
    222 fp.write(header)
    –> 223 fp.write(globalPalette)
    224 fp.write(appext)
    225

    TypeError: argument 1 must be string or buffer, not None
    “`

    Like

    • Yes Tom. Thanks for the info. I haven’t tried imageio hope to give it a spin during weekend. Also try to make images2gif running again as not many will want to have a new library just for creating gif.

      Thanks

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s