gpt4 book ai didi

python - 如何使 pyplot.subplots 内的图像更大

转载 作者:行者123 更新时间:2023-11-30 21:52:44 27 4
gpt4 key购买 nike

我需要在网格中显示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)

似乎子图中的图像太小,同时距离又很大,我想知道如何才能使子图中的图像变大?

enter image description here

最佳答案

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)

并复制您的安排,其中您将 8x6 (x:y) 图形分割为 4x5 (x:y) 子图 - 您的子图水平宽 (8/4=2) 且垂直短 (6/5 =1.2)并且每个图像在其子图居中时具有较宽的水平边距。

In [3]: f, axs = plt.subplots(5, 4) 
...: for x in axs.flatten():
...: x.imshow(img) ; x.axis('off')

enter image description here

现在恢复行和列的角色,现在您的子图在水平方向上更小(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')

enter image description here

要结束故事,关键是让子图与您使用的图像具有(至少大约)相同的纵横比,为此,我们必须对 figsize 进行干预> 参数,指定宽度:高度等于 (ncols×1):(nrows×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')

enter image description here

关于python - 如何使 pyplot.subplots 内的图像更大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59838360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com