matplotlib 在 gif 中保存动画错误

问题描述 投票:0回答:6

我想将 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格式时出错。

animation matplotlib gif
6个回答
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)

enter image description here


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

希望有帮助。


3
投票

在 Mac OS X 上仍然遇到一些问题,但上面的答案为我指明了正确的方向。

我所做的归结为:

  1. brew 安装 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()
    您需要调整的设置可以在文件末尾找到。我调整了以下内容(已注释掉)。请注意,这些设置不在“引号”中:

    动画作者:imagemagick

    动画编解码器:mpeg4

    动画比特率:-1

    动画.frame_format: png

    animation.convert_path:转换


2
投票

DrV 的脚本在 Windows 7 上对我不起作用,尽管

convert
ffmpeg
都在系统路径中。

  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.


1
投票

我刚刚尝试安装 ffmpeg,但没有帮助。然后我尝试安装 imagemagick - 失败。所以我求助于循环动画并用屏幕scraper录制它。我使用ScreenToGif


0
投票

在 Windows 上执行此操作的一种简单方法是使用 Pillowwriter,无需使用 Imagemagic 或任何其他花哨的库,如下所示:

writer = animation.PillowWriter(fps=60)
ani.save('rotation.gif',writer=writer)
© www.soinside.com 2019 - 2024. All rights reserved.