
本文介绍使用 NumPy 的 np.pad 实现图像居中填充(padding)的方法,适用于预处理中需统一尺寸但保留原始比例的场景,避免缩放导致的形变。
本文介绍使用 numpy 的 `np.pad` 实现图像居中填充(padding)的方法,适用于预处理中需统一尺寸但保留原始比例的场景,避免缩放导致的形变。
在图像处理任务中,常需将不同尺寸的输入图像统一为固定分辨率(如 700×700),但直接缩放(如 cv2.resize)会扭曲目标结构。更合理的做法是:保持图像原始像素内容不变,仅在四周补零(黑色背景),并将原图精确居中放置于目标画布中。这要求计算上下、左右各需填充的像素数,并利用 numpy.pad 高效实现。
核心思路是:对高度方向计算总填充量 dh = target_h - original_h,取其一半分别加在顶部和底部(若为奇数,则向下取整分配,np.pad 自动兼容);宽度同理。注意通道维度(如 RGB 的第 3 维)无需填充,对应 padding 元组中设为 (0, 0)。
以下为完整可复用的实现代码:
import numpy as np
def pad_to_size(image: np.ndarray, target_height: int, target_width: int,
pad_value: int = 0) -> np.ndarray:
"""
将图像居中填充至指定尺寸,不缩放、不裁剪。
Args:
image: 输入图像,形状为 (H, W) 或 (H, W, C)
target_height: 目标高度
target_width: 目标宽度
pad_value: 填充值(默认黑/0)
Returns:
填充后的图像,形状为 (target_height, target_width, C) 或 (target_height, target_width)
"""
h, w = image.shape[:2]
# 计算各方向填充量:(top, bottom), (left, right), (channel_start, channel_end)
pad_h = max(0, target_height - h)
pad_w = max(0, target_width - w)
top, bottom = pad_h // 2, pad_h - pad_h // 2
left, right = pad_w // 2, pad_w - pad_w // 2
# 构建 padding 元组:二维图像为 ((top,bottom), (left,right));三维则追加通道维度
if image.ndim == 3:
padding = ((top, bottom), (left, right), (0, 0))
else: # 灰度图
padding = ((top, bottom), (left, right))
return np.pad(image, padding, mode='constant', constant_values=pad_value)
# 示例用法
H, W = 600, 650
img = np.random.randint(0, 255, (H, W, 3), dtype=np.uint8) # 模拟原始图像
padded = pad_to_size(img, target_height=700, target_width=700)
print(f"Original shape: {img.shape} → Padded shape: {padded.shape}") # (600,650,3) → (700,700,3)
⚠️ 注意事项:
- 若原图已大于目标尺寸(如
H > 700),该函数不做裁剪,返回原图——你可根据需求在调用前添加判断逻辑(例如先 crop 再 pad); -
pad_value=0对应黑色背景,若需白色则设为255,灰度图同理; -
np.pad默认mode='constant'安全可靠,避免使用'reflect'或'wrap'等模式导致边缘异常; - 与 OpenCV 的
cv2.copyMakeBorder功能等价,但np.pad更轻量、无需额外依赖。
综上,np.pad 是实现无损、居中填充的理想工具——简洁、高效、语义清晰,特别适合深度学习数据预处理流水线中的标准化步骤。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











