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!
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.
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.
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 .
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With