在使用matplotlib ArtistAnimation时向图像添加文本
我有几张图片,它们是以二维数组的形式存在的,我想把这些图片做成动画,并且在每张图片上添加一段会变化的文字。
到目前为止,我已经成功制作了动画,但我需要你的帮助来给每张图片添加文字。
我有一个for
循环,用来打开每张图片并把它们添加到动画中。假设我想在每张图片上添加图片编号(imgNum
)。
这是我目前的代码,它可以生成没有文字的图片动画。
ims = []
fig = plt.figure("Animation")
ax = fig.add_subplot(111)
for imgNum in range(numFiles):
fileName= files[imgNum]
img = read_image(fileName)
frame = ax.imshow(img)
ims.append([frame])
anim = animation.ArtistAnimation(fig, ims, interval=350, blit=True, repeat_delay=350)
anim.save('dynamic_images.mp4',fps = 2)
plt.show()
那么,我该如何在每张图片上添加带有imgNum
的文字呢?
谢谢你的帮助!
1 个回答
11
你可以使用 annotate 来添加文本,并把 Annotation
这个艺术家加入到你传给 ArtistAnimation 的艺术家列表中。下面是一个基于你代码的例子。
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
ims = []
fig = plt.figure("Animation")
ax = fig.add_subplot(111)
for imgNum in range(10):
img = np.random.rand(10,10) #random image for an example
frame = ax.imshow(img)
t = ax.annotate(imgNum,(1,1)) # add text
ims.append([frame,t]) # add both the image and the text to the list of artists
anim = animation.ArtistAnimation(fig, ims, interval=350, blit=True, repeat_delay=350)
plt.show()