当前位置:   article > 正文

python一个窗口中显示多张图像(matplotlib.pyplot)

python一个窗口中显示多张图像(matplotlib.pyplot)
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
  • 1
  • 2
  • 3
def show_images(images, titles=None, num_cols=None, scale=3, normalize=False):
    """ 一个窗口中绘制多张图像:
    Args: 
        images: 可以为一张图像(不要放在列表中),也可以为一个图像列表
        titles: 图像对应标题、
        num_cols: 每行最多显示多少张图像
        scale: 用于调整图窗大小
        normalize: 显示灰度图时是否进行灰度归一化
    """

    # 加了下面2行后可以显示中文标题
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 单张图片显示
    if not isinstance(images, list):
        if not isinstance(scale, tuple):
            scale = (scale, scale * 1.5)

        plt.figure(figsize=(scale[1], scale[0]))
        img = images
        if len(img.shape) == 3:
            # opencv库中函数生成的图像为BGR通道,需要转换一下
            B, G, R = cv.split(img)
            img = cv.merge([R, G, B])
            plt.imshow(img)
        elif len(img.shape) == 2:
            # pyplot显示灰度需要加一个参数
            if normalize:
                plt.imshow(img, cmap='gray')
            else:
                plt.imshow(img, cmap='gray', vmin=0, vmax=255)
        else:
            raise TypeError("Invalid shape " +
                            str(img.shape) + " of image data")
        if titles is not None:
            plt.title(titles, y=-0.15)
        plt.axis('off')
        plt.show()
        return

    # 多张图片显示
    if not isinstance(scale, tuple):
        scale = (scale, scale)

    num_imgs = len(images)
    if num_cols is None:
        num_cols = int(np.ceil((np.sqrt(num_imgs))))
    num_rows = (num_imgs - 1) // num_cols + 1

    idx = list(range(num_imgs))
    _, figs = plt.subplots(num_rows, num_cols,
                           figsize=(scale[1] * num_cols, scale[0] * num_rows))
    for f, i, img in zip(figs.flat, idx, images):
        if len(img.shape) == 3:
            # opencv库中函数生成的图像为BGR通道,需要转换一下
            B, G, R = cv.split(img)
            img = cv.merge([R, G, B])
            f.imshow(img)
        elif len(img.shape) == 2:
            # pyplot显示灰度需要加一个参数
            if normalize:
                f.imshow(img, cmap='gray')
            else:
                f.imshow(img, cmap='gray', vmin=0, vmax=255)
        else:
            raise TypeError("Invalid shape " +
                            str(img.shape) + " of image data")
        if titles is not None:
            f.set_title(titles[i], y=-0.15)
        f.axes.get_xaxis().set_visible(False)
        f.axes.get_yaxis().set_visible(False)
    # 将不显示图像的fig移除,不然会显示多余的窗口
    if len(figs.shape) == 1:
        figs = figs.reshape(-1, figs.shape[0])
    for i in range(num_rows * num_cols - num_imgs):
        figs[num_rows - 1, num_imgs % num_cols + i].remove()
    plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

测试

单张图片
if __name__ == '__main__':
    src = cv.imread("image\\cat.jpg")
    title = "cat"
    show_images(src, title)
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

多张图片
show_images([src]*4, [title]*4)
  • 1

在这里插入图片描述

多张图片(规定一行最多显示多少张图像)
show_images([src] * 4, [title] * 4, num_cols=3)
  • 1

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/612693
推荐阅读
相关标签
  

闽ICP备14008679号