如何使pyplot.subplot内的图像变大

2024-09-28 03:19:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 图像imgforindexplotdemopltcol
1条回答
网友
1楼 · 发布于 2024-09-28 03:19:01

TL;DR使用plt.subplots(nrows=nr, ncols=nc, figsize=(..., ...))调整图形大小,使单个子图至少具有与要显示的图像大致相同的纵横比


关键点是,^ {CD2>}将使用正方形像素,所以如果你的图像具有1:2长宽比,绘制的图像将具有1:2长宽比,并且每一个都将位于其自身的子图的中间-如果子图的纵横比不同于图像的纵横比,那么你将经历“大白边界综合症”。p>

让我们从导入和假图像开始,宽高比为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

相关问题 更多 >

    热门问题