问题一:图片不显示
您需要将动画对象存储在变量中:
my_anim = animation.ArtistAnimation(fig, myimages, interval=100)
此要求专门针对animation
并且与其他绘图功能不一致matplotlib
,通常可以使用的地方my_plot=plt.plot()
or plt.plot()
漠然地。
这个问题有待进一步讨论here.
问题2:保存不起作用
没有任何animation
例如,也无法保存图形。这是因为save
方法
属于ArtistAnimation
班级。你所做的就是在呼唤save
来自animation
模块,这就是引发错误的原因。
问题 3:两个窗口
最后一个问题是你会弹出两个数字。原因是当你打电话时plt.imshow()
,它在当前图窗上显示图像,但由于尚未创建图窗,pyplot
隐式地为您创建一个。
当 python 稍后解释时fig = plt.figure()
语句,它创建一个新图形(另一个窗口)并将其标记为“图 2”。
将此语句移至代码开头即可解决该问题。
这是修改后的代码:
import matplotlib.pyplot as plt
import matplotlib.image as mgimg
from matplotlib import animation
fig = plt.figure()
# initiate an empty list of "plotted" images
myimages = []
#loops through available png:s
for p in range(1, 4):
## Read in picture
fname = "heatflow%03d.png" %p
img = mgimg.imread(fname)
imgplot = plt.imshow(img)
# append AxesImage object to the list
myimages.append([imgplot])
## create an instance of animation
my_anim = animation.ArtistAnimation(fig, myimages, interval=1000, blit=True, repeat_delay=1000)
## NB: The 'save' method here belongs to the object you created above
#my_anim.save("animation.mp4")
## Showtime!
plt.show()
(要运行上面的代码,只需将 3 个图像添加到您的工作文件夹中,名称为“heatflow001.png”到“heatflow003.png”。)
替代方法使用FuncAnimation
当您第一次尝试使用时,您可能是对的FuncAnimation
,因为在列表中收集图像会占用大量内存。我通过比较以下代码与上面的代码测试了内存使用情况
系统监视器。看来FuncAnimation
方法更加有效。我相信随着您使用更多图像,差异会变得更大。
这是第二个代码:
from matplotlib import pyplot as plt
from matplotlib import animation
import matplotlib.image as mgimg
import numpy as np
#set up the figure
fig = plt.figure()
ax = plt.gca()
#initialization of animation, plot array of zeros
def init():
imobj.set_data(np.zeros((100, 100)))
return imobj,
def animate(i):
## Read in picture
fname = "heatflow%03d.png" % i
## here I use [-1::-1], to invert the array
# IOtherwise it plots up-side down
img = mgimg.imread(fname)[-1::-1]
imobj.set_data(img)
return imobj,
## create an AxesImage object
imobj = ax.imshow( np.zeros((100, 100)), origin='lower', alpha=1.0, zorder=1, aspect=1 )
anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = True,
frames=range(1,4), interval=200, blit=True, repeat_delay=1000)
plt.show()