如何在Matplotlib子图网格中保留图像原始分辨率?
保留原始分辨率的Matplotlib图像网格展示方案
要实现保留单张图像原始分辨率的网格展示,核心是让画布的像素尺寸匹配所有图像拼接后的像素规模,同时预留足够空间放置标签与边距。Matplotlib的画布尺寸(英寸)和DPI共同决定最终输出像素数,因此需要基于单张图像的原始像素尺寸计算画布参数。
关键调整要点
- 基于单张图像的宽高(示例为195x240)和网格行列数,计算画布基础尺寸
- 额外预留标签空间,避免遮挡图像
- 修正原代码中未定义的
betas、alphas变量 - 调整子图间距,确保图像无拉伸变形
修改后的完整可运行代码
import cv2 import urllib import numpy as np import matplotlib.pyplot as plt # 读取示例图像(195x240像素) req = urllib.request.urlopen('https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/OpenCV_Logo_with_text.png/195px-OpenCV_Logo_with_text.png') arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img = cv2.imdecode(arr, -1) # OpenCV读入为BGR格式,转换为RGB适配Matplotlib显示 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 网格参数 n_rows = 5 # 行数 n_cols = 5 # 列数 # 单张图像的原始像素尺寸 img_h, img_w = img.shape[:2] # DPI设置(匹配Matplotlib默认值,便于像素计算) dpi = 100 # 计算画布基础尺寸(英寸):像素数 / DPI = 英寸数 base_width = (img_w * n_cols) / dpi base_height = (img_h * n_rows) / dpi # 预留标签空间:左右各加1英寸,上下各加1.5英寸(可根据标签长度调整) fig_width = base_width + 2 fig_height = base_height + 3 # 创建画布,指定尺寸与DPI fig, ax = plt.subplots(n_rows, n_cols, figsize=(fig_width, fig_height), dpi=dpi) # 生成带增益和偏置的图像并展示 alphas = [1 + a*0.2 for a in range(n_rows)] betas = [b*20 for b in range(n_cols)] for a in range(n_rows): for b in range(n_cols): axis = ax[a, b] # 计算调整后的图像并限制像素范围 adjusted_img = np.clip(alphas[a] * img + betas[b], 0, 255).astype(np.uint8) axis.imshow(adjusted_img) # 隐藏刻度,避免干扰图像展示 axis.set_xticks([]) axis.set_yticks([]) # 添加行标签(增益值) for a in range(n_rows): ax[a, 0].set_ylabel(f'{alphas[a]:.1f}', fontsize=10) # 添加列标签(偏置值) for b in range(n_cols): ax[-1, b].set_xlabel(f'{betas[b]}', fontsize=10) # 添加全局标题 fig.supylabel('增益 (alpha)', fontsize=12, y=0.92) fig.supxlabel('偏置 (beta)', fontsize=12, x=0.5) # 调整子图间距:图像紧密排列,同时给标签留足空间 fig.subplots_adjust(wspace=0, hspace=0.1, left=0.1, right=0.9, bottom=0.1, top=0.9) # 保存图像时指定DPI,确保输出像素精度 plt.savefig('image_grid.png', dpi=dpi, bbox_inches='tight') plt.show()
效果说明
- 输出网格图的像素尺寸约为
(195*5 + 200) × (240*5 + 300)(预留空间像素数=预留英寸数×DPI) - 每张子图严格保留195x240的原始分辨率,无拉伸变形
- 标签与边距空间充足,不会遮挡图像内容
内容的提问来源于stack exchange,提问作者Him
相关产品推荐
相关产品推荐

