Matplotlib保存动画为gif格式时出现错误

17

我想将matplotlib动画保存为gif格式。

我成功地使用以下代码将动画保存为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个回答

30

这是因为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)

这里输入图片描述


1
这个程序运行得很好。但是我能否减小Imagemagick文件的大小呢?我的程序只有约20kb,但Imagemagick大约有60mb...我只需要Imagemagick中的gif更改功能。你有什么想法吗? - user42298
@user42298 我在制作3D图形动画时也有类似的经历。坐标轴和背景网格占据了大部分空间。删除这些元素可以得到一个漂亮而小巧的动画。使用ImageMagick生成的gif比使用ffmpeg生成的mp4具有更好的分辨率。希望这能帮到你。 - user989762
当我在Windows 7上运行此脚本时,我会收到以下错误:`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` - endolith
使用多个核心可以实现这个吗?我正在保存数百个视频。 - crypdick

7

提醒一下,在使用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

希望它有所帮助。

1
这对我帮助很大!我在Mac OS X上使用它,除了convert.exe之外 ;) - Sander van den Oord
能否详细说明一下,@SandervandenOord。我在我的Mac上无法运行这个程序。你是不是刚刚删除了convert.exe文件?因此,animation.convert_path: C:\Program Files\ImageMagick-6.9.2-Q16-HDRI - jonboy
@jonboy 这是三年前的事了,所以我已经不太记得了。但是 .exe 是Windows文件,所以我想是的,这部分应该被省略掉。 - Sander van den Oord
@jonboy,你也可以尝试下面我给出的答案,它还没有得到赞哦;) - Sander van den Oord
谢谢。我尝试了一下,但没有成功。我在想是否还有其他遗漏的东西。 - jonboy

3

我在Mac OS X上遇到了一些问题,但是上面的答案指导我朝正确的方向前进。

我的做法如下:

  1. 安装imagemagick:brew install imagemagick
  2. 编辑路径文件/etc/path(sudo vim path),添加imagemagick的bin文件夹的位置,例如:/usr/local/Cellar/imagemagick/6.9.6-4/bin
  3. 按照上述所述更改matplotlibrc的设置。您可以通过在Python中执行以下操作找到matplotlibrc的位置:import matplotlib matplotlib.matplotlib_fname()。您需要调整的设置可以在文件末尾找到。我调整了以下设置(注释掉)。请注意,这些设置不在引号中:

    animation.writer:imagemagick

    animation.codec:mpeg4

    animation.bitrate:- 1

    animation.frame_format:png

    animation.convert_path:convert


2

在Windows 7上,DrV的脚本对我无效,尽管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
   ...

编辑我的matplotlibrc文件,添加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


1
我刚试图安装FFmpeg,但没有成功。然后我尝试安装ImageMagick,也失败了。所以我采用了循环动画并使用屏幕抓取工具进行录制。我使用ScreenToGif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接