我需要在网格中显示20个图像,我的代码如下
def plot_matric_demo(img, nrows, ncols):
fig, ax = plt.subplots(nrows=nrows, ncols=ncols)
cur_index = 0
for row in ax:
for col in row:
col.imshow(img)
cur_index = cur_index + 1
col.axis('off')
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
plt.show()
subplot_img = cv2.imread("subplots.png")
plot_matric_demo(subplot_img, 5, 4)
似乎子图中的图像太小,而距离又很大,我想知道如何使子图中的图像更大?
TL; DR使用plt.subplots(nrows=nr, ncols=nc, figsize=(..., ...))
调整图形大小,以使单个子图具有至少近似与要显示图像相同的纵横比。
关键是,imshow
将使用正方形像素,因此,如果您的图像的纵横比为1:2,则绘制的图像的纵横比为1:2,并且每幅图像都位于自己的中间子图-如果子图的纵横比与图像的纵横比不同,您将遇到“大白框综合症”。
让我们先从导入和伪造的图像开始,宽高比为1:2
In [1]: import numpy as np
...: import matplotlib.pyplot as plt
In [2]: img = np.arange(54*108).reshape(108,54)
并复制您的布置,在该布置中,您将4x5(x:y)子图细分为8x6(x:y)图-您的子图水平宽(8/4 = 2)而垂直短(6/5 = 1.2),并且每个图像在其子图中居中时都具有WIDE水平边距。
In [3]: f, axs = plt.subplots(5, 4)
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')
现在恢复行和列的作用,现在您的子图在水平方向上较小(8/5 = 1.6),在水平方向上较高(6/4 = 1.5),由于水平白色边距的减小和增加图像尺寸,因为可用高度更大
In [4]: f, axs = plt.subplots(4, 5)
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')
为了结束故事,关键是要使子图具有(至少近似与您使用的图像相同的宽高比,并且为此目的,我们必须干预figsize
参数,并指定宽度:height等于(ncols×1):( rows×2),在我的示例中为figsize=(5,8)
In [5]: f, axs = plt.subplots(4, 5, figsize=(5,8))
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')