import cv2
# big_pad=True:当目标图像高和宽均大于原图时,进行边缘填充
# big_pad=False:按照目标尺寸的最小缩放比例,先缩放,再进行边缘填充
# borderType=cv2.BORDER_CONSTANT:表示常量填充,borderValue为填充常量0~255(黑~白)
# borderType=cv2.BORDER_REPLICATE:边界复制填充
# borderType=cv2.BORDER_REFLECT:边界反射填充
# borderType=cv2.BORDER_WRAP:边框包装填充
def image_padding(image, target_shape, big_pad=True,
borderType=cv2.BORDER_REFLECT, borderValue=(0, 0, 0)):
# 目标尺寸大小
ph, pw = target_shape
# 原始图片尺寸
h, w, _ = image.shape
if big_pad and ph > h and pw > w: # 以原图为中心进行边缘填充
top = bottom = (ph - h) // 2 # 获取上、下填充尺寸
top += (ph - h) % 2 # 为保证目标大小,无法整除则上+1
left = right = (pw - w) // 2
left += (pw - w) % 2 # 为保证目标大小,同理左上+1
image_padded = cv2.copyMakeBorder(image, top, bottom, left, right,
borderType=borderType, value=borderValue)
else: # 最小比例缩放填充(大尺寸:高/宽比例变化较大的将被填充,小尺寸反之)
# 计算缩放后图片尺寸
scale = min(pw/w, ph/h) # 获取高/宽变化最小比例
nw, nh = int(scale * w), int(scale * h)
# 对原图按照目标尺寸的最小比例进行缩放
img_resized = cv2.resize(image, (nw, nh))
top = bottom = (ph - nh) // 2 # 获取上、下填充尺寸
top += (ph - nh) % 2 # 为保证目标大小,无法整除则上+1
left = right = (pw - nw) // 2
left += (pw - nw) % 2 # 为保证目标大小,同理左上+1
image_padded = cv2.copyMakeBorder(img_resized, top, bottom, left, right,
borderType=borderType, value=borderValue)
return image_padded
if __name__ == "__main__":
path = './2_2.png'
img = cv2.imread(path)
img_pad = image_padding(img, (640,640))
cv2.imwrite('./1_BORDER_WRAP.png',img_pad)
# cv2.imwrite('./1_.png',img_pad[64:576,64:576])
原图
BORDER_WRAP
REFLECT
REPLICATE