如何使用IPython显示连续显示图像?

Suz*_*ioc 10 python ipython

如果我执行以下命令:

for file in files:
    display(Image(filename=os.path.join(folder,file)))
Run Code Online (Sandbox Code Playgroud)

我在列中获得了一个图像列表:

在此输入图像描述

如何将它们排成一排(水平)?

小智 12

这对我有用:

from matplotlib.pyplot import figure, imshow, axis
from matplotlib.image import imread

def showImagesHorizontally(list_of_files):
    fig = figure()
    number_of_files = len(list_of_files)
    for i in range(number_of_files):
        a=fig.add_subplot(1,number_of_files,i+1)
        image = imread(list_of_files[i])
        imshow(image,cmap='Greys_r')
        axis('off')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Aki*_*oss 10

您还可以使用HTML:

from IPython.display import display, HTML
def make_html(folder, image):
     return '<img src="{}" style="display:inline;margin:1px"/>'
            .format(os.path.join(folder, image))

display(HTML(''.join(make_html(f, x)) for x in files))
Run Code Online (Sandbox Code Playgroud)

在我的情况下,通过设置边距将修复未对齐(和恕我直言产生更好的结果).


小智 6

使用 Jupyter 内置工具的替代解决方案(IPython.display和ipywidgets):

from IPython.display import display
from ipywidgets import widgets, HBox

imageA = widgets.Image(value=open('path/to/image/a.jpg', 'rb').read())
imageB = widgets.Image(value=open('path/to/image/b.jpg', 'rb').read())

hbox = HBox([imageA, imageB])
display(hbox)

# optional: you can show more hboxes, boxes will be arranged vertically
display(anotherHbox) # 2nd
display(yetAnotherHbox) # 3rd
display(andAnotherHbox) # 4th
Run Code Online (Sandbox Code Playgroud)

参考:

请注意,IPythondisplay模块也有Image类,该类widgets.Image与HBox.