matplotlib save animation in gif error

2019-01-14 18:55发布

问题:

I want to save matplotlib animation in gif format.

I succeded to save animation to mp4 format, using code

import matplotlib
matplotlib.use("Agg")

~some codes~

ani = animation.FuncAnimation(fig, draw, update, interval=10, blit=False)
mywriter = animation.FFMpegWriter(fps=60)
ani.save('myanimation.mp4',writer=mywriter)

but if I change myanimation.mp4 to gif format, python makes error

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\edison\Edison_v4_backup_1\ver5.py", line 164, in <module>
    ani.save('demoanimation.gif',writer=mywriter);
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 718, in save
    writer.grab_frame(**savefig_kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 204, in grab_frame
    dpi=self.dpi, **savefig_kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1421, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2220, in print_figure
    **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 497, in print_raw
    renderer._renderer.write_rgba(filename_or_obj)
RuntimeError: Error writing to file

Seeing that I succeded to save in mp4 format, I don't know why it makes error when saving gif format.

回答1:

This is because matplotlib does not support GIFs without external programs. If you have imagemagick correctly installed and configured, this should work:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np


def init_animation():
    global line
    line, = ax.plot(x, np.zeros_like(x))
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1,1)

def animate(i):
    line.set_ydata(np.sin(2*np.pi*i / 50)*np.sin(x))
    return line,

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 2*np.pi, 200)

ani = matplotlib.animation.FuncAnimation(fig, animate, init_func=init_animation, frames=50)
ani.save('/tmp/animation.gif', writer='imagemagick', fps=30)



回答2:

Just a reminder, before you use Matplotlib and ImageMagick to convert images or videos to gif, you need to modify Matplotlib's config and add ImageMagick's path.

The following code will show you the config file path of Matplotlib

import matplotlib
matplotlib.matplotlib_fname()

For me the path is

C:\Anaconda\lib\site-packages\matplotlib\mpl-data\matplotlibrc

Then changing animation.convert_path

#animation.convert_path: 'convert' # Path to ImageMagick's convert binary.
                                   # On Windows use the full path since convert
                                   # is also the name of a system tool.

by adding convert.exe path to it

animation.convert_path: C:\Program Files\ImageMagick-6.9.2-Q16-HDRI\convert.exe

Don't forget to remove the # before animation.convert_path.

After the above modification, Matplotlib and ImageMagick will perfectly work and output the gif file you want.

Hope it helps.



回答3:

DrV's script didn't work for me on Windows 7, even though convert and ffmpeg both are in the system path.

  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 513, in print_raw
    renderer._renderer.write_rgba(filename_or_obj)

RuntimeError: Error writing to file

 

C:\Users>ffmpeg
ffmpeg version N-50911-g9efcfbe Copyright (c) 2000-2013 the FFmpeg developers
   ...

 

C:\Users>convert
Version: ImageMagick 6.9.1-1 Q16 x64 2015-03-20 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
   ...

Editing my matplotlibrc to add the full path to the exe fixed it:

###ANIMATION settings
#animation.html : 'none'           # How to display the animation as HTML in
                                   # the IPython notebook. 'html5' uses
                                   # HTML5 video tag.
#animation.writer : ffmpeg         # MovieWriter 'backend' to use
#animation.codec : mpeg4           # Codec to use for writing movie
#animation.bitrate: -1             # Controls size/quality tradeoff for movie.
                                   # -1 implies let utility auto-determine
#animation.frame_format: 'png'     # Controls frame format used by temp files
animation.ffmpeg_path: C:\Program Files\ImageMagick-6.9.1-Q16\ffmpeg.exe   # Path to ffmpeg binary. Without full path
                                   # $PATH is searched
#animation.ffmpeg_args: ''         # Additional arguments to pass to ffmpeg
#animation.avconv_path: 'avconv'   # Path to avconv binary. Without full path
                                   # $PATH is searched
#animation.avconv_args: ''         # Additional arguments to pass to avconv
#animation.mencoder_path: 'mencoder'
                                   # Path to mencoder binary. Without full path
                                   # $PATH is searched
#animation.mencoder_args: ''       # Additional arguments to pass to mencoder
animation.convert_path: C:\Program Files\ImageMagick-6.9.1-Q16\convert.exe # Path to ImageMagick's convert binary.
                                   # On Windows use the full path since convert
                                   # is also the name of a system tool.



回答4:

Still had some trouble on Mac OS X, but the answers above pointed me in the right direction.

What I did came down to:

  1. brew install imagemagick
  2. edit the path file on location /etc/path (sudo vim path) and added the location of bin folder of imagemagick, in my case: /usr/local/Cellar/imagemagick/6.9.6-4/bin
  3. changed the settings of matplotlibrc as described above. You can find the location of matplotlibrc by doing in Python: import matplotlib matplotlib.matplotlib_fname() The settings you need to adjust can be found at the end of the file. I adjusted the following ones (commented out). Please note that those settings are not in 'quotes':

    animation.writer : imagemagick

    animation.codec : mpeg4

    animation.bitrate: -1

    animation.frame_format: png

    animation.convert_path: convert



回答5:

I have just tried to install ffmpeg, didn't help. Then I tried to install imagemagick - failed. So I resorted to looping animation and recording it with screen scrapper. I use ScreenToGif.