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()
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.
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.
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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With