如何用Matplotlib动画png?

时间:2018-03-14 12:13:18

标签: python-3.x matplotlib

我试图通过改变它的x位置移动它来设置png的动画,但是循环不会覆盖上一步,而是只留下它并在它旁边显示一个新版本:

first step

Final step

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.image as mgimg

fig, ax = plt.subplots()
plt.axis([0, 400, 0, 300])


def animate(i):
    imobj = ax.imshow(np.zeros((0,0)),extent=[0+i, 67+i, 136, 100], aspect='auto',zorder=1)
    fname='catapult0.png'
    img = mgimg.imread(fname)[-1::-1]
    imobj.set_data(img)
    return imobj,
anim = animation.FuncAnimation(fig, animate,
                               frames=100,
                               interval=5,
                               repeat=False)
ax.set_aspect('equal')
plt.show()

1 个答案:

答案 0 :(得分:0)

您应该在动画功能之外创建一次图像。然后,对于动画,您只需要更改图像的位置,即

image.set_extent(...)

完整代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.image as mgimg

fig, ax = plt.subplots( figsize=(4,4))
plt.axis([0, 200, 0, 300])

fname='https://i.stack.imgur.com/UuTST.png'
img = mgimg.imread(fname)[230:230+55,51:51+86]
imobj = ax.imshow(img,extent=[0, img.shape[1], 136, 136+img.shape[0]], zorder=1)

def animate(i):
    imobj.set_extent([0+i, img.shape[1]+i, 136, 136+img.shape[0]])
    return imobj,
anim = animation.FuncAnimation(fig, animate, frames=100,  interval=40, repeat=False)
ax.set_aspect('equal')
plt.show()

enter image description here