【问题标题】:matplotlib save animation in gif errormatplotlib 在 gif 中保存动画错误
【发布时间】:2014-09-28 05:47:43
【问题描述】:

我想将 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


    【解决方案1】:

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

    【讨论】:

    • 这很好用。但我可以减少 imagemagick 文件的大小吗?我的程序只有~20kb,但 Imagemagick 大约 60mb...我只需要 imagemagick 中的 gif 更改功能。你有什么想法吗?
    • @user42298 我在制作 3D 绘图时也有类似的经历。轴和背景网格被绘制并占据了大部分空间。删除这些元素会产生一个漂亮而小巧的动画。开箱即用,使用 ImageMagick 生成的 gif 比使用 ffmpeg 生成的 mp4 具有更好的分辨率。我希望这会有所帮助。
    • 我得到 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 在 Windows 7 中运行此脚本
    • 是否可以使用多个核心来做到这一点?我正在保存数百个视频。
    【解决方案2】:

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

    希望对你有帮助。

    【讨论】:

    • 这对我帮助很大!在 Mac OS X 上使用它,除了 convert.exe ;)
    • 您能否详细说明@SandervandenOord。我的 Mac 无法做到这一点。你刚刚删除了convert.exe。因此,animation.convert_path: C:\Program Files\ImageMagick-6.9.2-Q16-HDRI
    • @jonboy 这是 3 多年前的事了,所以我不再确切知道了。但是 .exe 是一个 windows 文件,所以我想是的,应该省略这部分。
    • @jonboy 你也可以试试我在下面给出的答案,有 0 个赞;)
    • 谢谢。我试一试无济于事。我想知道我是否遗漏了其他东西。
    【解决方案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 matplotlibmatplotlib.matplotlib_fname() 您需要调整的设置可以在文件末尾找到。我调整了以下(注释掉)。请注意,这些设置不在“引号”中:

      animation.writer : imagemagick

      动画编解码器:mpeg4

      动画.比特率:-1

      animation.frame_format: png

      animation.convert_path: 转换

    【讨论】:

      【解决方案4】:

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

      将我的 matplotlibrc 编辑为 add 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.
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 2018-12-31
          • 1970-01-01
          • 2018-01-03
          • 2014-09-01
          • 2013-08-03
          • 1970-01-01
          • 1970-01-01
          • 2020-02-27
          • 1970-01-01
          相关资源
          最近更新 更多