Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make 2 images appear side by side in Jupyter notebook (iPython)?

I want to display 2 PNG images in iPython side by side.

My code to do this is:

from IPython.display import Image, HTML, display

img_A = '\path\to\img_A.png'
img_B = '\path\to\img_B.png'

display(HTML("<table><tr><td><img src=img_A></td><td><img src=img_B></td></tr></table>"))

But it doesn't output the images, and instead only displays placeholders for the 2 images:

enter image description here

I tried the following as well:

s = """<table>
<tr>
<th><img src="%s"/></th>
<th><img src="%s"/></th>
</tr></table>"""%(img_A, img_B)
t=HTML(s)
display(t)

But the result is the same:

enter image description here

The images are in the path for sure, because I verified by displaying them in a pop up:

plt.imshow(img_A)
plt.imshow(img_B)

and they do appear in the pop ups.

How do I make the 2 images appear side by side in iPython?

like image 247
Kristada673 Avatar asked May 28 '18 04:05

Kristada673


People also ask

How do I add multiple images to a Jupyter notebook?

Use scipy. misc. imread(name='my_file. png') , this will return a Numpy array that you can then use to create a dataset.

What is %% capture in Jupyter?

What does %% capture do in Jupyter? Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

Which method is used to display image in the Jupyter?

To display the image, the Ipython. display() method necessitates the use of a function. In the notebook, you can also specify the width and height of the image.


2 Answers

You can try using matplotlib. You can read image to numpy array by using mpimg.imread (documentation) from matplotlib, then you can use subplots (documentation) and for creating two columns for figures and finally imshow (documetation) to display images.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib import rcParams

%matplotlib inline

# figure size in inches optional
rcParams['figure.figsize'] = 11 ,8

# read images
img_A = mpimg.imread('\path\to\img_A.png')
img_B = mpimg.imread('\path\to\img_B.png')

# display images
fig, ax = plt.subplots(1,2)
ax[0].imshow(img_A)
ax[1].imshow(img_B)
like image 84
student Avatar answered Sep 22 '22 11:09

student


matplotlib is a very good tool for plotting but I found it very heavy and slow for scenarios where I simply need a fast and easy way to display bigger number of images.
To solve this I'm using IPyPlot package:

import ipyplot

ipyplot.plot_images(images_list, max_images=20, img_width=150)

You would get a plot similar to this:
enter image description here

like image 29
Karol Żak Avatar answered Sep 22 '22 11:09

Karol Żak