matplotlib在gif错误中保存动画

时间:2014-08-05 14:12:04

标签: animation matplotlib gif

我想以gif格式保存matplotlib动画。

我成功地使用代码

将动画保存为mp4格式
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)

但如果我将myanimation.mp4更改为gif格式,则python会出错

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

看到我成功保存为mp4格式,我不知道为什么在保存gif格式时出错。

5 个答案:

答案 0 :(得分:16)

这是因为matplotlib不支持没有外部程序的GIF。如果您已正确安装和配置imagemagick,则应该可以:

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)

enter image description here

答案 1 :(得分:3)

提醒您,在使用MatplotlibImageMagick将图片或视频转换为gif之前,您需要修改Matplotlib的配置并添加ImageMagick的路径

以下代码将显示Matplotlib的配置文件路径

import matplotlib
matplotlib.matplotlib_fname()

对我而言,路径是

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

然后更改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.

添加 convert.exe 路径

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

不要忘记在#之前移除animation.convert_path

经过上述修改后,Matplotlib和ImageMagick将完美地工作并输出您想要的gif文件。

example gif

希望它有所帮助。

答案 2 :(得分:2)

DrV的脚本在Windows 7上对我不起作用,即使convertffmpeg都在系统路径中。

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

修改我的matplotlibrcadd the full path to the exe修复了它:

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

animated GIF output

答案 3 :(得分:0)

在Mac OS X上仍有一些问题,但上面的答案指出了我正确的方向。

我做了什么归结为:

  1. brew install imagemagick
  2. 编辑位置/ etc / path(sudo vim路径)上的路径文件,并添加了imagemagick的bin文件夹的位置,在我的例子中:/usr/local/Cellar/imagemagick/6.9.6-4/bin
  3. 如上所述更改了matplotlibrc的设置。你可以在Python中找到matplotlibrc的位置:import matplotlib matplotlib.matplotlib_fname() 您需要调整的设置可以在文件末尾找到。我调整了以下(注释掉)。请注意,这些设置不在&#39;引用&#39;:

    animation.writer:imagemagick

    animation.codec:mpeg4

    animation.bitrate:-1

    animation.frame_format:png

    animation.convert_path:convert

答案 4 :(得分:0)

我刚刚尝试安装ffmpeg,没有帮助。然后,我尝试安装imagemagick-失败。因此,我求助于循环动画并使用屏幕抓取器对其进行记录。我使用ScreenToGif