3

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

3
  • Your code looks pretty weird, could you please edit it? Commented Jul 25, 2018 at 14:19
  • Done; hopefully it's a little more clear now. Commented Jul 25, 2018 at 15:32
  • 1
    I would guess you forgot to call plt.ion() to activate interactive mode. Commented Jul 25, 2018 at 22:44

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This did it -- thanks so much! For my purposes, I changed the imshow line to im = ax.imshow(image, cmap=plt.get_cmap('gray'), vmin=0, vmax=255), but it works perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.