matplotlib在jupyter笔记本中并排显示图像

时间:2019-08-19 11:41:43

标签: python matplotlib

我想在jupyter笔记本中并排显示matplotlib相册中的一些图像。

我写了一个函数,但是没有用。

import cv2
import numpy as np
import matplotlib.pyplot as plt

def show(path):
    for iter in list.get(path):
        img = cv2.imread(images)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.axis('off')
        plt.imshow(img)
        plt.show()
        fig, ax = plt.subplots(nrows=2, ncols=2)

2 个答案:

答案 0 :(得分:1)

您只需要对每个图像使用子图功能:

plt.subplot(2, 2, n) # n is the position of your subplot (1 to 4)
plt.imshow(img)

加载完所有子图后,只需调用:

plt.show()

下面我举了一个可能对您有所帮助的简单示例,您可以在github repo中找到此文件的Jupyter笔记本:

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("a"+".jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.axis('off')

plt.subplot(2, 2, 1)
plt.imshow(img)

plt.subplot(2, 2, 2)
plt.imshow(img)

plt.subplot(2, 2, 3)
plt.imshow(img)

plt.subplot(2, 2, 4)
plt.imshow(img)

plt.show()

结果是:

sideside

答案 1 :(得分:0)

有些错误。首先,您要覆盖listiter,它们是内置的两个可调用对象。最佳做法是不这样做。我不确定变量list是什么,但是由于它实现了.get方法,因此它看起来像是字典。

您遇到的主要问题是,每次循环迭代时都要创建一组新的图像/轴。

您应该在for循环之外定义图像和轴,并在轴上与要绘制的图像一起迭代。

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

def plot_album(album_name):
    fig, axes = plt.subplots(nrows=2, ncols=2)
    # this assumes the images are in images_dir/album_name/<name>.jpg
    image_paths = glob(images_dir + album_name + '/*.jpg')
    for imp, ax in zip(image_paths, axes.ravel()):
        img = mpimg.imread(imp)
        ax.imshow(img)
        ax.axis('off')
    fig.tight_layout()

enter image description here