如何使用jupyter笔记本在网格中显示多个png

时间:2019-07-05 16:59:42

标签: python jupyter-notebook

我有一个文件名列表,位于jupyter笔记本所在的文件夹中。

fnames = ['foo.png', 'my_img.png', 'img1.png', ..... 'last_img.png']

我想在笔记本输出单元格内的网格中显示这些图像,并指定:

  • 行数
  • 列数
  • 要显示的图像暗淡(以像素为单位)(每个图像相同的暗淡)

2 个答案:

答案 0 :(得分:2)

尝试

import os
import numpy as np
import matplotlib.pyplot as plt

directory = "./Images/"
images = os.listdir(directory)

fig = plt.figure(figsize=(10, 10))
columns = 2
rows = np.ceil(len(images))

for x, i in enumerate(images):
    path =  os.path.join("./Images/",i)
    img = plt.imread(path)
    fig.add_subplot(rows, columns, x+1)
    plt.imshow(img)
plt.show()

答案 1 :(得分:1)

更深入的了解,您可以使用Tabs作为替代方法在ipywidgets中查看

import os
import ipywidgets as widgets
from IPython.display import display

# Define a useful function
def get_image(f_path):
    '''
    Returns the image from a path
    '''
    img_labs = ['jpg','png']
    if any(x in img_labs for x in f_path.split('.')):
        file = os.path.join(folder,f_path)
        image = open(file,'rb').read()
        return image

# Do the actual work here
folder = 'Some Path to a Folder of Images'
files  = os.listdir(folder)
images = [get_image(x) for x in files]
children = [widgets.Image(value = img) for img in images if str(type(img)) != '<class \'NoneType\'>']
labels = ['{}'.format(i) for i in range(len(children))]

# Customize your layout here:
box_layout = widgets.Layout(
    display='flex',
    flex_flow='column',
    align_items='stretch',
    border='solid',
    width='50%')

# Create the widget
tab = widgets.Tab()
tab.children = children

# Label em'!
for i in range(len(children)):
    tab.set_title(i,labels[i])

display(tab)

有关更多详细信息,请访问documentation