betelgeuse
betelgeuse

Reputation: 469

Add text to image animated with matplotlib ArtistAnimation

I have several images as 2d arrays and I want to create an animation of these images and add a text that changes with the image.

So far I managed to get the animation but I need your help to add a text to each of the images.

I have a for loop to open each of the images and add them to the animation, and let say that I want to add the image number (imgNum) to each of the images.

Here is my code that is working to generate a movie of the images, without text.

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()

So, how can I add to each of the images a text with imgNum ?

Thanks for your help!

Upvotes: 6

Views: 7271

Answers (1)

Molly
Molly

Reputation: 13610

You can add text with annotate and add the Annotation artist to the list artists that you pass to ArtistAnimation. Here's an example based on your code.

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()

Upvotes: 11

Related Questions