jdbrody
jdbrody

Reputation: 513

Update matplotlib image in a function

I've got a loop that's processing images and I want, on every 100th iteration (say) to display the image in a single output window using matplotlib. So I'm trying to write a function which will take a numpy tensor as input and display the corresponding image.

Here's what I have which isn't working:

def display(image):
  global im

  # If  im has been initialized, update it with the current image; otherwise initialize im and update with current image.   
  try:
    im
    im.set_array(image)
    plt.draw()
  except NameError:
    im = plt.imshow(image, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)
    plt.show(block=False)
    plt.draw()

I was trying to pass it through FuncAnimation at first, but that seems designed to have the animation call a function to do the update, rather than having a function call on matplotlib to display the result.

The code above opens a window but it doesn't seem to update. Can anyone point me in the right direction here?

Many thanks,

Justin

Upvotes: 2

Views: 8036

Answers (1)

toti08
toti08

Reputation: 2454

Maybe you can use a combination of:

The first one will re-draw your figure, while the second one will call the GUI event loop to update the figure.

Also you don't need to call imshow all the times, it's sufficient to call the "set_data" method on your "im" object. Something like that should work:

import matplotlib.pyplot as plt
import numpy

fig,ax = plt.subplots(1,1)
image = numpy.array([[1,1,1], [2,2,2], [3,3,3]])
im = ax.imshow(image)

while True:       
    image = numpy.multiply(1.1, image)
    im.set_data(image)
    fig.canvas.draw_idle()
    plt.pause(1)

This was adapted from this answer. Hope it helps.

Upvotes: 7

Related Questions