Python:在一个图中显示多个图像,没有缩放

时间:2018-03-18 13:50:45

标签: python matplotlib

我正在使用Python进行一些图像处理,我想在一个图中绘制4个图像(它们都是224x224x3 np数组),添加一些标题并将整个图形保存为png。

显然,我可以使用plt和subplot来做到这一点:

        f, axs = plt.subplots(2, 2)
        ax = axs[0, 0]
        ax.imshow(img1)
        ax.axis('off')
        ax.set_title('original')

        ax = axs[1, 0]
        ax.imshow(img2)
        ax.axis('off')
        ax.set_title('blur + noise')

        ax = axs[0, 1]
        ax.imshow(img3)
        ax.axis('off')
        ax.set_title('restored a')

        ax = axs[1, 1]
        ax.imshow(img4)
        ax.axis('off')
        ax.set_title('restored b')

然而,这将适用于不同图像的缩放,我希望以原始分辨率显示图像,而不应用任何插值。有没有办法在plt中实现这种行为?我发现其他一些thread提出了类似的问题,但它只回答了如何在不缩放的情况下显示单个图像。

感谢您的帮助, 最大

1 个答案:

答案 0 :(得分:1)

该程序与链接问题基本相同, Show image without scaling

除了边距和图像尺寸之外,您还需要考虑子图之间的间距。

那么数字的大小就是

size_image_A + size_image_B + 2* margin + spacing

这需要通过除以数字dpi转换为小英寸的大小。 subplots_adjust参数需要通过相对轴单位的间距进行扩展。

import matplotlib.pyplot as plt
import numpy as np

images = [np.random.rayleigh((i+1)/8., size=(180, 200, 3)) for i in range(4)]


margin=50 # pixels
spacing =35 # pixels
dpi=100. # dots per inch

width = (200+200+2*margin+spacing)/dpi # inches
height= (180+180+2*margin+spacing)/dpi

left = margin/dpi/width #axes ratio
bottom = margin/dpi/height
wspace = spacing/float(200)

fig, axes  = plt.subplots(2,2, figsize=(width,height), dpi=dpi)
fig.subplots_adjust(left=left, bottom=bottom, right=1.-left, top=1.-bottom, 
                    wspace=wspace, hspace=wspace)

for ax, im, name in zip(axes.flatten(),images, list("ABCD")):
    ax.axis('off')
    ax.set_title('restored {}'.format(name))
    ax.imshow(im)

plt.show()

enter image description here