我是python的新手,我尝试制作动画并使用matplotlibs FuncAnimation将其保存为某种视频格式。如果我运行以下代码:
import numpy as np
import matplotlib.animation as ani
import matplotlib.pyplot as plt
azimuths = np.radians(np.linspace(0, 360, 360))
zeniths = np.arange(0, 8, 0.2)
rho, psi = np.meshgrid(zeniths, azimuths)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, polar=True)
ax.set_yticks([])
plt.grid()
def frame(i):
values_i = prob_density(rho ** 2, psi, i)
ax.contourf(psi, rho, values_i)
animation = ani.FuncAnimation(fig, frame, np.linspace(0, 1000, 10))
animation.save('video.mp4', writer='ffmpeg')
有一个错误说:
ValueError: outfile must be *.htm or *.html
因为这似乎与ffmpeg文件有关 - 这些文件位于
中/anaconda3/bin/ffmpeg
我已经有一段时间了,但似乎无法找到解决方案,尽管这似乎是常见的问题。感谢任何建议。
答案 0 :(得分:2)
我从未使用FuncAnimation bevore,但是matplotlib-example状态,你必须首先初始化ffmpeg。像这样:
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
fig1 = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)
也许,你可以尝试一下。