几天来,我一直在尝试在我的 Windows 计算机上导出动画 gif。
基本代码如下:
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()
错误:
>>> 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.
如果我将输出文件类型切换为 mp4,代码就可以工作。在阅读了很多制作视频文件时出错的人的帖子后,我觉得我已经尝试了不同编写器的各种组合(包括 FFMpegWriter、ImageMagickWriter、AVConvWriter 和 FileWriters),确保相关程序在我的路径中,更改设置在 matplotlibrc 中,并尝试了多台计算机。我很难过。
我发现只有一个线程引用了这个确切的错误: https://stackoverflow.com/questions/46562938/oserror-errno-22-invalid-argument-error-saving-animation-to-file
但是按照评论中的建议并没有解决我的问题。
有什么想法吗?感谢您的帮助。
最佳答案
使用问题中的代码,您基本上是在要求使用 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 的一部分。 The documentation说
If these tools are not available, you can simply append them to the magick tool like this:
magick convert
.
对于 matplotlib 动画,这意味着您需要设置一个额外的参数。设置路径为
plt.rcParams["animation.convert_path"] = "C:\ProgramFiles\ImageMagick\magick.exe"
然后调用
ani.save("test.gif",writer="imagemagick", extra_args="convert")
关于python - 使用 matplotlib 导出动画 gif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46712669/