Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 281
betelgeuse Avatar asked Jun 11 '14 14:06

betelgeuse


People also ask

How do I animate text in Matplotlib?

Initialize a variable "text" to hold a string. Add text to the axes at x=0.20 and y=0.50. Make a list of colors. Make an animation by repeatedly calling a function *animate*, where size of text is increased and color is changed.

What is Blit in Matplotlib animation?

The blit keyword is an important one: this tells the animation to only re-draw the pieces of the plot which have changed. The time saved with blit=True means that the animations display much more quickly. We end with an optional save command, and then a show command to show the result.

How do I show text in Matplotlib?

Basic text commandsAdd an annotation, with an optional arrow, at an arbitrary location of the Axes . Add a label to the Axes 's x-axis. Add a label to the Axes 's y-axis. Add a title to the Axes .


1 Answers

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()
like image 101
Molly Avatar answered Oct 20 '22 01:10

Molly