我如何动态(循环)在 google colab 中显示图像?

use*_*971 7 python matplotlib google-colaboratory

我一直在尝试使用 pyplot/matplotlib 来显示图像,因为它们在循环中发生变化,但我无法使任何工作正常进行。我基本上无法更新显示的图像。这是复制问题的代码:

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()
Run Code Online (Sandbox Code Playgroud)

Kor*_*ich 11

我测试了这段代码,它可以工作。

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)
Run Code Online (Sandbox Code Playgroud)