how to display multiple pngs in a grid using jupyter notebook

Question:

I have a list of file names, located in the same folder as the jupyter notebook.

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

I’d like to display these images in a grid inside a notebook output cell, specifying:

  • number of rows
  • number of columns
  • image dims, in pixels, to display (same dims for each image)
Asked By: 3z33etm

||

Answers:

Try this:

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()

A deeper dive, you can view in Tabs using ipywidgets as an alternative:

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)

For more extensive details, visit the documentation.

Answered By: Yaakov Bressler
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.