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

27 responses to “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

    1. Thanks luyi for bringing this to my notice….but It works on my system office and home.. Can you please let me the version of python, numpy… will investigate when i get some time….

      Like

  2. Is it necessary the PIL liblary?

    Like

    1. Yes PIL or pillow library are necessary thanks

      Like

      1. Thank you! Now it works 🙂

        Like

      2. Cheers!! Thanks for reading. 🙂

        Like

  3. Camille Girabawe Avatar
    Camille Girabawe

    Having same troubles as Elena. Would love to know how it was solved

    Like

    1. Hi Do you have PIL installed?

      Like

      1. Camille Girabawe Avatar
        Camille Girabawe

        Hi,
        Yes I have PIL installed. As a check, when I run –> python -c “import PIL.Image” <– I don't get any error

        Like

      2. Ok. Then PIL is not the problem… Can you please give the specific error you are getting. I will check and see . Also what is the OS you are working on? Thanks

        Like

      3. Camille Girabawe Avatar
        Camille Girabawe

        I am using OSX and here is the error lines:

        buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )

        AttributeError: ‘FigureCanvasMac’ object has no attribute ‘tostring_argb’

        Like

      4. Ok.. Thats explains it. I have tested it in windows. Let me check on Mac. Will do so during weekend.

        Like

  4. How to install Figtodat

    Like

    1. Hi Raula, you can download the file and keep it in python path

      Like

  5. 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

  6. 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

    1. Sorry for the delayed response… I will try this and post a reply.. Thanks for reading..

      Like

  7. none of your scripts run; stop posting!

    Like

    1. Perry,

      I have seen this problem with this script. I would like to investigate it when I have some free time.

      It used to work. Is there any other script that you are mentioning?

      Thanks

      Like

  8. I have the same problem as Lee can you explain why it does not work please ? Thank you for your work.

    Like

    1. 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

  9. 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

    1. Hi Daniel

      Yes currently the code is not working. I have to sit and look into it.

      It’s related to the PIL version..

      I will try to find the solution and post back.

      Thanks for reading

      Like

  10. Have the same problem as Lee.

    Like

    1. Hi

      Thanks for this. I am working on it. It’s related to new PIL version.

      Thanks

      Like

  11. The images2gif author has given up maintaining that script, and now recommends a simpler approach using the newer imageio package:
    https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python

    Like

    1. 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 comment

Trending