如何保存动画而不显示视频中的前一帧?

时间:2014-03-29 15:01:11

标签: python animation matplotlib

我想用Python保存动画,但我得到了叠加的帧!我想单独显示帧。 请在这里使用我:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from numpy import pi, cos, sin

fig = plt.figure()
plt.axis([-1.5, 1.5,-1.5, 1.5])
ax = plt.gca()
ax.set_aspect(1)

N=100

xp = [None] * N
yp = [None] * N

def init():
    # initialize an empty list of cirlces
    return []

def animate(i):

    xp[i]=sin(i*pi/10)
    yp[i]=cos(i*pi/10)

    patches = []

    patches.append(ax.add_patch( plt.Circle((xp[i],yp[i]),0.02,color='b') ))
    return patches 

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=N-1, interval=20, blit=True)

anim.save("example.avi")
plt.show()

1 个答案:

答案 0 :(得分:1)

有些事情我不确定,而且看起来似乎是axis.plot()行为和FuncAnimate()行为不同。但是,下面的代码适用于两者。

仅使用一个补丁(在您的情况下)

您的代码的关键点是,除了旧圈子之外,您每次迭代都会添加一个新圈子:

patches = []
patches.append(ax.add_patch( plt.Circle((xp[i],yp[i]),0.02,color='b') ))

即使您清除了修补程序列表,它们仍然存储在轴中。

相反,只需创建一个圆圈并改变其位置。

使用init()

清除第一帧

此外,init()需要从基础框架中清除补丁。

独立示例

from matplotlib import pyplot as plt
from matplotlib import animation
from numpy import pi, cos, sin

fig = plt.figure()
plt.axis([-1.5, 1.5, -1.5, 1.5])
ax = plt.gca()
ax.set_aspect(1)
N = 100
xp = []
yp = []


# add one patch at the beginning and then change the position
patch = plt.Circle((0, 0), 0.02, color='b')
ax.add_patch(patch)
def init():
    patch.set_visible(False)
    # return what you want to be cleared when axes are reset
    # this actually clears even if patch not returned it so I'm not sure
    # what it really does
    return tuple()


def animate(i):
    patch.set_visible(True)  # there is probably a more efficient way to do this
    # just change the position of the patch
    x, y = sin(i*pi/10), cos(i*pi/10)
    patch.center = x, y
    # I left this. I guess you need a history of positions.
    xp.append(x)
    yp.append(y)
    # again return what you want to be cleared after each frame
    # this actually clears even if patch not returned it so I'm not sure
    # what it really does
    return tuple()


anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=N-1, interval=20, blit=True)
# for anyone else, if you get strange errors, make sure you have ffmpeg
# on your system and its bin folder in your path or use whatever
# writer you have as: writer=animation.MencoderWriter etc...
# and then passing it to save(.., writer=writer)
anim.save('example.mp4')
plt.show()

返回值???

关于init()animate()的返回值,看起来并不重要。单个补丁仍然会被移动并正确绘制而不会清除之前的补丁。