如何阻止Matplotlib在子图中自动缩放图像至相同尺寸?
解决Matplotlib并排显示不同尺寸图像时保留原始尺寸的问题
你遇到的问题核心是:默认的subplots会给每个子图分配同等大小的网格空间,即便设置了aspect='equal',图像也会被拉伸/挤压来适配子图的固定轴区域,导致无法保留原始尺寸。以下是两种可行的解决方案:
方案一:基于图像宽度比例分配子图空间(推荐)
使用GridSpec的width_ratios参数,根据图像的实际宽度比例来分配子图的宽度空间,确保每个子图的宽度能匹配图像原始宽度,再结合aspect='equal'就能让图像按真实尺寸显示。
代码示例:
from matplotlib.gridspec import GridSpec # 假设你的图像变量已定义:img, img_512, img_512_upsample fig = plt.figure(figsize=(15, 10)) # 按图像宽度比例设置子图宽度:原始图1024,下采样512,上采样1024 → 比例2:1:2 gs = GridSpec(1, 3, width_ratios=[img.shape[1], img_512.shape[1], img_512_upsample.shape[1]]) # 添加第一个子图 ax0 = fig.add_subplot(gs[0]) ax0.imshow(img, cmap='gray', aspect='equal') ax0.set_title("Original Image") ax0.axis('on') # 添加第二个子图 ax1 = fig.add_subplot(gs[1]) ax1.imshow(img_512, cmap='gray', aspect='equal') ax1.set_title("Down Sample to 512x512") ax1.axis('on') # 添加第三个子图 ax2 = fig.add_subplot(gs[2]) ax2.imshow(img_512_upsample, cmap='gray', aspect='equal') ax2.set_title("Up Sample to 1024x1024") ax2.axis('on') plt.tight_layout() plt.show()
方案二:设置子图的宽高比匹配图像
通过set_box_aspect方法,给每个子图设置与图像一致的宽高比(图像高度/图像宽度),强制子图轴区域的比例适配图像,从而让图像按原始尺寸显示。
代码示例:
fig, ax = plt.subplots(1,3, figsize=(15,10)) # 原始图像子图 ax[0].imshow(img, cmap='gray', aspect='equal') ax[0].set_title("Original Image") ax[0].axis('on') ax[0].set_box_aspect(img.shape[0]/img.shape[1]) # 图像高宽比 # 下采样图像子图 ax[1].imshow(img_512, cmap='gray', aspect='equal') ax[1].set_title("Down Sample to 512x512") ax[1].axis('on') ax[1].set_box_aspect(img_512.shape[0]/img_512.shape[1]) # 上采样图像子图 ax[2].imshow(img_512_upsample, cmap='gray', aspect='equal') ax[2].set_title("Up Sample to 1024x1024") ax[2].axis('on') ax[2].set_box_aspect(img_512_upsample.shape[0]/img_512_upsample.shape[1]) plt.tight_layout() plt.show()
为什么之前的方法无效?
aspect='equal'仅保证图像的像素宽高比不变,但子图的轴区域大小是固定的,图像仍会被缩放适配轴区域;extent只是设置图像的坐标显示范围,不会改变子图的物理空间大小;plt.autoscale(False)仅关闭坐标自动缩放,对子图的空间分配没有影响。
内容的提问来源于stack exchange,提问作者Max H
相关产品推荐
相关产品推荐

