Ram*_*nez 5 python animation matplotlib
下面的代码连续显示并保存随机矩阵的动画.我的问题是如何调整我保存的动画的持续时间.这里我唯一的参数是fps,dpi控制帧剩余的秒数,第二个控制图像的质量.我想要的是实际控制将根据矩阵实际存储的数量保存的帧数.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
N = 5
A = np.random.rand(N,N)
im = plt.imshow(A)
def updatefig(*args):
im.set_array(np.random.rand(N,N))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=200, blit=True)
ani.save('try_animation.mp4', fps=10, dpi=80) #Frame per second controls speed, dpi controls the quality
plt.show()
Run Code Online (Sandbox Code Playgroud)
我很想知道是否应该添加更多参数.我试图在matplotlib的类文档中寻找合适的一个但是我没有成功:
http://matplotlib.org/api/animation_api.html#module-matplotlib.animation
文档显示FuncAnimation接受一个参数frames,该参数控制播放的帧总数.因此您的代码可以读取
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
N = 5
A = np.random.rand(N,N)
im = plt.imshow(A)
def updatefig(*args):
im.set_array(np.random.rand(N,N))
return im,
ani = animation.FuncAnimation(fig, updatefig, frames=10, interval=200, blit=True)
ani.save('try_animation.mp4', fps=10, dpi=80) #Frame per second controls speed, dpi controls the quality
plt.show()
Run Code Online (Sandbox Code Playgroud)
打10帧.
多年以后我建立了这个例子,每次我都需要看看动画的参数如何相互关联.我决定在这里分享它,无论谁发现它有用.
TL/DR:
frames * (1 / fps)(以秒为单位)frames * interval / 1000(以秒为单位)下面的代码允许您在提供即时视觉反馈的环境中使用此设置.
此代码构建一个根据参数滴答的时钟:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure(figsize=(16, 12))
ax = fig.add_subplot(111)
# You can initialize this with whatever
im = ax.imshow(np.random.rand(6, 10), cmap='bone_r', interpolation='nearest')
def animate(i):
aux = np.zeros(60)
aux[i] = 1
image_clock = np.reshape(aux, (6, 10))
im.set_array(image_clock)
ani = animation.FuncAnimation(fig, animate, frames=60, interval=1000)
ani.save('clock.mp4', fps=1.0, dpi=200)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这将生成并保存一个如下所示的动画:
所以关键是随着时间的推移,黑色方块将沿着大的白色方块移动.有60个白色的盒子,所以你可以在一分钟内建立一个时钟.
现在,需要注意的重要一点是,有两个参数可以确定黑匣子的移动速度:函数interval中的animation.FuncAnimation函数和'fps' ani.save.第一个控制将显示的动画中的速度,第二个控制将保存的动画中的速度.
如上面的代码所示,您将生成60帧,并以每秒1帧的速度显示.这意味着时钟每秒钟都会滴答作响.如果您希望保存的动画时钟每两秒钟打一次,那么您应该设置fps=0.5.如果您希望显示的动画时钟每两秒钟点击一次,您应该设置interval=2000.
[我会尽快编辑更长的解释]
| 归档时间: |
|
| 查看次数: |
8575 次 |
| 最近记录: |