Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i dynamically (in a loop) show images in google colab?

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()
like image 360
user3246971 Avatar asked Oct 17 '18 13:10

user3246971


People also ask

How do I display image output in Google Colab?

First, open google drive & upload the image on the drive. Select the uploaded image, right-click on it, get a sharable link & copy it. Open Google Colab Notebook & add text block where you want to include the image. The general code to include an image is given below.

Can colab notebooks contain images?

The first method, insert an image from the local machine: Click on the “Insert image”, and choose the image from your local machine. The second method, insert an image from Google drive: upload your image to the same folder where your colab notebook is residing.

How do I upload multiple images to Google Colab?

You need to click on Mount Drive Option to the pane on the left side of the notebook and you'll get access to all the files stored in your drive. For importing multiple files in one go, you may need to write a function. Save this answer.

What is colab %% capture?

What does %% capture do in Colab? Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.


1 Answers

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)
like image 135
korakot Avatar answered Nov 15 '22 06:11

korakot