8

I have been trying to use pyplot/matplotlib to show images as they change in a loop, but i haven't been able to get anything working. I am basically unable to update the image being shown. here is the code to replicate the problem:

f = plt.figure(1)
ax = plt.gca()
show_obj= ax.imshow(np.random.randn(28,28))
for i in range(10):
  print(i)
  # None of these 3 options work
  if True:
    # the image does not update
    show_obj.set_data(np.random.randn(28,28))
    f.canvas.draw()
  if False:
    # image does not update
    ax.clear()
    ax.imshow(np.random.rand(28,28))
    pass
  if False:
    # starts drawing new axes
    f = plt.figure(1)
    ax = plt.gca()
    ax.imshow(np.random.rand(28,28))
  plt.show()
user3246971
  • 233
  • 2
  • 6

4 Answers4

13

I test this code and it works.

from IPython.display import clear_output
import matplotlib.pyplot as plt
from numpy.random import randn
from time import sleep

for i in range(5):
  clear_output()
  plt.imshow(randn(28, 28))
  plt.show()
  sleep(1)
korakot
  • 37,818
  • 16
  • 123
  • 144
3

Inspired by korsakov’s post; this modification makes it more “smooth”, and somewhat more logical :-)

from IPython.display import clear_output
import matplotlib.pyplot as plt
from numpy.random import randn
from time import sleep

for i in range(5):
  plt.imshow(randn(28, 28))
  plt.show()
  sleep(1)
  clear_output(wait=True)
Ron
  • 31
  • 1
0

If you'd like to show all of the images in your output, you can run:

import matplotlib.pyplot as plt

for filename in filenames:
    img = plt.imread(filename)
    plt.imshow(img)
    plt.show()
yndolok
  • 5,197
  • 2
  • 42
  • 46
0

my contribution:

import time #optional, just for demo
from matplotlib import pyplot as plt
from IPython.display import clear_output
from cv2 import imread #Hack
from google.colab.patches import cv2_imshow #Hack

#Initializations
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
fig = ax1.get_figure()
path = 'file.png' #your drive temporal file path
line1, = ax1.plot([],[])
line2, = ax2.plot([],[])

#update as many times you wish
line1.set_data([1,2,3,4],[0,8,2,4])
line2.set_data([1,2,3,4],[0,-8,-2,-4])

#Animation purposes
clear_output()
fig.savefig(path, format='png') #Hack
img = imread(path) 
cv2_imshow(img)    
time.sleep(20)     #demo: it show the img even when halted

Explanation:

  • The reason that you can't update your images is because google.colab writes a fixed temporal file.
  • Sol. write your own image and upload it by your own.
Daniel Exxxe
  • 59
  • 1
  • 7