向使用matplotlib ArtistAnimation设置动画的图像添加文本

2024-06-01 13:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个图像作为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的文本?

谢谢你的帮助!在


Tags: 图像文本imgforfig动画plt数组
1条回答
网友
1楼 · 发布于 2024-06-01 13:17:01

您可以使用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()

相关问题 更多 >