在一个IPython Notebook单元格中显示多个图像?

问题描述:

如果我有多个图像(加载为NumPy数组),如何在一个IPython Notebook单元格中显示?

If I have multiple images (loaded as NumPy arrays) how can I display the in one IPython Notebook cell?

我知道我可以使用 plt.imshow(ima)显示一个图像...但我希望一次显示多个。

I know that I can use plt.imshow(ima) to display one image… but I want to show more than one at a time.

我试过:

 for ima in images:
     display(Image(ima))

但我的图片链接已损坏:

But I just get a broken image link:

简答:

调用 plt.figure()如果你想要创建新的数字单元格中不止一个:

call plt.figure() to create new figures if you want more than one in a cell:

for ima in images:
    plt.figure()
    plt.imshow(ima)

但要澄清与图像:

IPython.display.Image 用于显示图像文件,而不是数组数据。如果你想用Image显示numpy数组,你必须先将它们转换为文件格式(最简单的用PIL):

IPython.display.Image is for displaying Image files, not array data. If you want to display numpy arrays with Image, you have to convert them to a file-format first (easiest with PIL):

from io import BytesIO
import PIL
from IPython.display import display, Image

def display_img_array(ima):
    im = PIL.Image.fromarray(ima)
    bio = BytesIO()
    im.save(bio, format='png')
    display(Image(bio.getvalue(), format='png'))

for ima in images:
    display_img_array(ima)

笔记本,说明了这两种方法。

A notebook illustrating both approaches.