Plot a sequence of images with matplotlib Python

10,340

Solution 1

I tried the ion() method and it works fine for small amount of data, but if you have large images or images streaming in relatively quickly, this method is horrendously slow. From what I understand, ion() will redraw everything each time you make a change to your figure, including axes and labels, etc. Which might not be what you want.

This thread shows a much nicer way of doing things

Here's a simple example that I made showing how to do this:

import time
import numpy
import matplotlib.pyplot as plt


fig = plt.figure( 1 )
ax = fig.add_subplot( 111 )
ax.set_title("My Title")

im = ax.imshow( numpy.zeros( ( 256, 256, 3 ) ) ) # Blank starting image
fig.show()
im.axes.figure.canvas.draw()

tstart = time.time()
for a in xrange( 100 ):
  data = numpy.random.random( ( 256, 256, 3 ) ) # Random image to display
  ax.set_title( str( a ) )
  im.set_data( data )
  im.axes.figure.canvas.draw()

print ( 'FPS:', 100 / ( time.time() - tstart ) )

I get about 30 FPS on my machine with the above code. When I run the same thing with plt.ion() and ax.imshow( data ) instead of im.axes.figure.canvas.draw() and im.set_data( data ), I get around 1 FPS

Solution 2

Use pause(). For a set of images stored in video[t, x, y], this makes a simple animation:

import matplotlib.pyplot as plt
for i in range(video.shape[0]):
    plt.imshow(video[i,:,:])
    plt.pause(0.5)
Share:
10,340
blueSurfer
Author by

blueSurfer

Just another guy studying computer science.

Updated on June 04, 2022

Comments

  • blueSurfer
    blueSurfer almost 2 years

    I'm implementing the kmeans clustering algorithm in Python. I would like to plot at each iteration the status (image) of the clusters quality. So, basically I have a cycle which plot at each iteration an image and I want to animate this. I don't know if I made that clear. At the moment I just use the show() command which plot the image but then I have to close it in order to continue the iteration.

    So, is there some way to animate the sequence of images computed at each step?