使用matplotlib的ArtistAnimation添加文本到动态图片

6

我有几个作为2d数组的图片,并希望创建这些图片的动画并添加一个随着图像变化的文本。

到目前为止,我已经成功生成了动画,但我需要你的帮助向每个图像添加文本

我有一个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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接