leemengtaiwan
10/6/2017 - 6:55 AM

在notebook水平顯示多張以ndarray表示的圖片, 可以輸入labels當作照片標題

Show images in jupyter notebook horizontally w/ labels as title.

def show_images_horizontally(images, labels=[], lookup_label=None,
                             figsize=(15, 7)):
    """
    Show images in jupyter notebook horizontally w/ labels as title.

    Parameters
    ----------
    images: ndarray of shape (#images, height, width, #channels)
    labels: ndarray of shape (#images, label)
    lookup_label: dict
        indicate what text to render for every value in labels
        e.g. {0: 'dog', 1: 'cat'}

    """
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import figure, imshow, axis

    fig = figure(figsize=figsize)
    for i in range(images.shape[0]):
        a = fig.add_subplot(1, images.shape[0], i + 1)
        if lookup_label:
            plt.title(lookup_label[labels[i][0]])
            assert labels.any(), 'labels not available'
        imshow(images[i], cmap='Greys_r')
        axis('off')


show_images_horizontally(train_X[:2], train_y[:2], lookup_label={0: 'Dog', 1: 'Cat'})


# IPython.Display version
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('image_folder', x) for x in image_file_names)));