简体   繁体   中英

How do I display multiple images from one cell in a Jupyter notebook

I'm trying to display a series of images in a cell in a Jupyter notebook. The code looks like this:

from matplotlib import pyplot
file_names = ['a', 'b', 'c']
for name in file_names:
  image = cv2.imread(name)
  pyplot.imshow(image)

But what I get in this notebook cell is only the last image displayed, not each of the three. If I remove the loop and display each image in a separate cell I see all the images. Is there a use of imshow I'm missing?

The function pyplot.imshow only writes the image to the buffer that will be shown/stored/etc in subsequent actions (this is how you can use pyplot.title , pyplot.xlim , and other commands in a sequence and then only have one plot at the end of all of them).

The reason it seems to display an image in Jupyter is because it's the last line of code executed in the cell, and Jupyter always tries to render the last item it sees unless that behavior is disabled (note that pyplot.imshow actually returns an image object which could be rendered -- Jupyter has logic in place which attempts to do so).

If you really just want to display those items in a loop (as opposed to using subplots or some other way to construct a composite image) then you need to add an additional pyplot.show() command:

from matplotlib import pyplot
file_names = ['a', 'b', 'c']
for name in file_names:
  image = cv2.imread(name)
  pyplot.imshow(image)
  pyplot.show()

You can also use subplots to plot the images, which allows, for example, aligning them horizontally:

from matplotlib import pyplot

file_names = ['a', 'b', 'c']

# create subplots instances
fig, axes = pyplot.subplots(1,3, figsize=(12,4))

for name, ax in zip(file_names, axes.ravel()):
  image = cv2.imread(name)

  # plot image into the subplot
  ax.imshow(image[:,:,::-1])

Note that cv2 will read images in BGR while pyplot assumes RGB , therefore the ::-1 .

Just use pyplot.show() in a loop.

If you want to save each plot separately, just add plt.clf() right after the loop starts and add smth like _%d in the image name to run over all images in loop and save them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM