How to display images in a row with IPython display?
This worked for me:
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')
You can also use 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))
In my case, by setting a margin will fix the un-alignment (and IMHO produce nicer results).
An alternative solution using Jupyter built-in facilities (IPython.display
and 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
References:
- Usage of
widgets.Image
: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#Image HBox
and layout: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html- IPython
display
: https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.display
Be careful that IPython display
module also has Image
class, which is different from widgets.Image
and not compatible with HBox
.