【问题标题】:How to display ndarray images inline during loop in IPython?如何在 IPython 循环期间内联显示 ndarray 图像?
【发布时间】:2024-01-17 14:38:01
【问题描述】:

以下代码

%matplotlib inline

for i in range(0, 5):
    index = np.random.choice(len(dataset))
    print('index:', index)
    image = dataset[index, :, :]
    print('image shape:', np.shape(image))
    plt.imshow(image)

jupyter notebook的末尾显示五张打印输出和一张图片。

是否可以在每次循环迭代时显示图像?

我可以用

处理图像文件
for fullname in fullnames:
  print('fullname:', fullname)
  display(Image(filename=fullname))

是否可以对 ndarrays 做同样的事情?

更新

写作

for i in range(0, 5):
   ...
   plt.figure()
   plt.imshow(image)

做得更好,但并不完美。多张图片显示,但都在文字之后。

应该交错。

【问题讨论】:

    标签: python matplotlib jupyter-notebook


    【解决方案1】:

    试试:

    for i in range(0, 5):
       ...
       plt.figure()
       plt.imshow(image)
       plt.show()
    

    如果没有plt.show(),则仅在单元格完成执行后才呈现和显示图形(即退出for 循环)。使用plt.show(),您可以在每次迭代后强制渲染。

    【讨论】: