【问题标题】:How can i dynamically (in a loop) show images in google colab?如何在 google colab 中动态(循环)显示图像?
【发布时间】:2019-03-22 04:52:19
【问题描述】:

我一直在尝试使用 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()

【问题讨论】:

标签: python matplotlib google-colaboratory


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    灵感来自 korsakov 的帖子;这种修改使它更“流畅”,也更合乎逻辑:-)

    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)
    

    【讨论】:

      【解决方案3】:

      如果您想在输出中显示所有图像,可以运行:

      import matplotlib.pyplot as plt
      
      for filename in filenames:
          img = plt.imread(filename)
          plt.imshow(img)
          plt.show()
      

      【讨论】:

        【解决方案4】:

        我的贡献:

        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
        

        解释:

        • 无法更新图片的原因是 google.colab 写入了固定的临时文件。
        • 溶胶。自己写图片,自己上传。

        【讨论】:

          猜你喜欢
          • 2020-03-06
          • 2019-01-22
          • 1970-01-01
          • 2020-10-10
          • 2022-01-14
          • 2020-12-09
          • 2019-08-12
          • 2022-11-03
          • 2021-06-19
          相关资源
          最近更新 更多