使用 matplotlib 导出动画 gif [英] Exporting animated gif using matplotlib

查看:33
本文介绍了使用 matplotlib 导出动画 gif的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天来,我一直在尝试在我的 Windows 计算机上导出动画 gif.

基本代码如下:

将 numpy 导入为 np导入 matplotlib.pyplot 作为 plt从 matplotlib.animation 导入 FuncAnimation图, ax = plt.subplots()xdata, ydata = [], []ln, = plt.plot([], [], 'ro', 动画=真)定义初始化():ax.set_xlim(0, 2*np.pi)ax.set_ylim(-1, 1)返回 ln,定义更新(帧):xdata.append(frame)ydata.append(np.sin(frame))ln.set_data(xdata, ydata)返回 ln,ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),init_func=init, blit=True)ani.save("test.gif")plt.show()

和错误:

<预><代码>>>>蟒蛇.\anim_test.py回溯(最近一次调用最后一次):文件.\anim_test.py",第 22 行,在 <module> 中ani.save("test.gif")文件C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py",第 1063 行,保存writer.grab_frame(**savefig_kwargs)文件C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py",第 336 行,grab_frame'with --verbose-debug.'.format(e, out, err))IOError:将动画保存到文件时出错(原因:[Errno 22] 无效参数)标准输出:标准错误:.重新运行可能会有所帮助使用 --verbose-debug.PS C:\Users\ishma\Dropbox (SteinLab)\spectra\MassSpecPlot>python .\anim_test.py --verbose-debug$HOME=C:\Users\ishmamatplotlib 数据路径 C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\mpl-data*********************************************************************您有以下不受支持的 LaTeX 前导自定义:请不要在这些自定义激活的情况下寻求支持.*********************************************************************加载的 rc 文件 C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\mpl-data\matplotlibrcmatplotlib 版本 2.0.2详细级别调试互动是假的平台是win32加载的模块:<dictionary-keyiterator object at 0x0000000003EA0048>CACHEDIR=C:\Users\ishma\.matplotlib使用来自 C:\Users\ishma\.matplotlib\fontList.cache 的 fontManager 实例后端 Qt5Agg 版本 5.6Animation.save 使用 <class 'matplotlib.animation.FFMpegWriter'>以像素为单位的帧大小为 640 x 480MovieWriter.run: 运行命令: ffmpeg -f rawvideo -vcodec rawvideo -s 640x480 -pix_fmt rgba -r 5.0 -i pipe: -vcodec h264 -pix_fmt yuv420p -y test.gifMovieWriter.grab_frame:抓取帧.findfont: 匹配 :family=sans-serif:style=normal:variant=normal:weight=400:stretch=normal:size=10.0 到 DejaVu Sans (u'C:\\Users\\ishma\\Anaconda2\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSans.ttf') 得分为 0.000000MovieWriter.grab_frame:抓取帧.MovieWriter -- 运行过程出错:没有任何没有任何MovieWriter -- 命令标准输出:没有任何MovieWriter -- 命令标准错误:没有任何回溯(最近一次调用最后一次):文件.\anim_test.py",第 22 行,在 <module> 中ani.save("test.gif")文件C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py",第 1063 行,保存writer.grab_frame(**savefig_kwargs)文件C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py",第 336 行,grab_frame'with --verbose-debug.'.format(e, out, err))IOError:将动画保存到文件时出错(原因:[Errno 22] 无效参数)标准输出:无标准错误:无.它可能有助于使用 --verbose-debug 重新运行.

如果我将输出文件类型切换为 mp4,代码就可以工作.在阅读了许多制作视频文件时出错的人的帖子后,我觉得我已经尝试了不同作家的各种组合(包括 FFMpegWriter、ImageMagickWriter、AVConvWriter 和 FileWriters),确保相关程序在我的 PATH 中,更改了设置在 matplotlibrc 中,并尝试了多台计算机.我被难住了.

我发现只有一个线程引用了这个确切的错误:https://stackoverflow.com/questions/46562938/oserror-errno-22-invalid-argument-error- Saving-animation到文件

但是按照评论中的建议并没有解决我的问题.

有什么想法吗?感谢您的帮助.

解决方案

通过问题中的代码,您基本上要求使用 MPEG 编写器生成动画 gif.然而,MPEG 编写器只能制作视频.

通过 matplotlib 动画模块生成动画 gif 的标准方法是使用 ImageMagick.

所以首先将您的行更改为

ani.save("test.gif",writer="imagemagick")

现在要让它起作用,rcParam animation.convert_path 必须指向 ImageMagick 的 convert 程序.
似乎您在此处使用 Windows,因此最好包含它的完整路径.因此,在保存之前,设置

plt.rcParams["animation.convert_path"] = "C:\ProgramFiles\ImageMagick\convert.exe"

或任何您的 convert.exe 路径.

现在很明显 convert.exe 不再是新版本 imageMagick 的一部分了.文档

<块引用>

如果这些工具不可用,您可以简单地将它们附加到magick工具中,如下所示:
魔法转换.

对于 matplotlib 动画,这意味着您需要设置一个额外的参数.设置路径为

plt.rcParams["animation.convert_path"] = "C:\ProgramFiles\ImageMagick\magick.exe"

然后调用

ani.save("test.gif",writer="imagemagick", extra_args="convert")

I've been trying to export an animated gif on my windows computer for several days.

Here is the basic code:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro', animated=True)

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
ani.save("test.gif")
plt.show()

And the error:

>>> python .\anim_test.py
Traceback (most recent call last):
  File ".\anim_test.py", line 22, in <module>
    ani.save("test.gif")
  File "C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py", line 1063, in save
    writer.grab_frame(**savefig_kwargs)
  File "C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py", line 336, in grab_frame
    'with --verbose-debug.'.format(e, out, err))
IOError: Error saving animation to file (cause: [Errno 22] Invalid argument) Stdout:  StdError: . It may help to re-run
with --verbose-debug.
PS C:\Users\ishma\Dropbox (SteinLab)\spectra\MassSpecPlot> python .\anim_test.py --verbose-debug
$HOME=C:\Users\ishma
matplotlib data path C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\mpl-data

*****************************************************************
You have the following UNSUPPORTED LaTeX preamble customizations:

Please do not ask for support with these customizations active.
*****************************************************************

loaded rc file C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\mpl-data\matplotlibrc
matplotlib version 2.0.2
verbose.level debug
interactive is False
platform is win32
loaded modules: <dictionary-keyiterator object at 0x0000000003EA0048>
CACHEDIR=C:\Users\ishma\.matplotlib
Using fontManager instance from C:\Users\ishma\.matplotlib\fontList.cache
backend Qt5Agg version 5.6
Animation.save using <class 'matplotlib.animation.FFMpegWriter'>
frame size in pixels is 640 x 480
MovieWriter.run: running command: ffmpeg -f rawvideo -vcodec rawvideo -s 640x480 -pix_fmt rgba -r 5.0 -i pipe: -vcodec h
264 -pix_fmt yuv420p -y test.gif
MovieWriter.grab_frame: Grabbing frame.
findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=400:stretch=normal:size=10.0 to DejaVu Sans (u'
C:\\Users\\ishma\\Anaconda2\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSans.ttf') with score of 0.0000
00
MovieWriter.grab_frame: Grabbing frame.
MovieWriter -- Error running proc:
None
None
MovieWriter -- Command stdout:
None
MovieWriter -- Command stderr:
None
Traceback (most recent call last):
  File ".\anim_test.py", line 22, in <module>
    ani.save("test.gif")
  File "C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py", line 1063, in save
    writer.grab_frame(**savefig_kwargs)
  File "C:\Users\ishma\Anaconda2\lib\site-packages\matplotlib\animation.py", line 336, in grab_frame
    'with --verbose-debug.'.format(e, out, err))
IOError: Error saving animation to file (cause: [Errno 22] Invalid argument) Stdout: None StdError: None. It may help to
 re-run with --verbose-debug.

If I switch the output file type to mp4, the code works. After reading many threads from people with errors producing video files, I feel like I have tried every combination of different writers (including FFMpegWriter, ImageMagickWriter, AVConvWriter, and the FileWriters as well), made sure the relevant programs are in my PATH, changed settings in matplotlibrc, and tried multiple computers. I'm stumped.

I've found only one thread referencing this exact error: https://stackoverflow.com/questions/46562938/oserror-errno-22-invalid-argument-error-saving-animation-to-file

But following the advice in the comments there haven't solved my problem.

Any ideas? Thanks for any help.

解决方案

With the code from the question you are basically asking to produce an animated gif using the MPEG writer. The MPEG writer however is only able to produce videos.

The standard way to produce an animated gif through the matplotlib animation module is to use ImageMagick.

So first change your line to

ani.save("test.gif",writer="imagemagick")

Now for this to work the rcParam animation.convert_path must point to the ImageMagick's convert program.
It seems you are on windows here, so it's best to include the complete path to it. Hence, before the saving, set

plt.rcParams["animation.convert_path"] = "C:\ProgramFiles\ImageMagick\convert.exe" 

or whatever your path to the convert.exe may be.

Now it may apparently happen that convert.exe is not part of newer versions of imageMagick anymore. The documentation says

If these tools are not available, you can simply append them to the magick tool like this:
magick convert.

For the matplotlib animation this means that you would need to set an extra argument. Set the path to

plt.rcParams["animation.convert_path"] = "C:\ProgramFiles\ImageMagick\magick.exe"

then call

ani.save("test.gif",writer="imagemagick", extra_args="convert")

这篇关于使用 matplotlib 导出动画 gif的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆