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

最后都变了- 提交于 2021-02-07 11:46:01

问题


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:

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:

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?


回答1:


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



回答2:


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:



来源:https://stackoverflow.com/questions/50559000/how-do-i-make-2-images-appear-side-by-side-in-jupyter-notebook-ipython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!