目标: 将一张长方形图片扩展成一张正方形图片,例如: 200x300x3的一张图片扩展成一张300x300x3的图片,填充部分使用白色.
代码:
import cv2
import os
imglist = os.listdir('.')
os.mkdir('./img')
for item in imglist:
if item.endswith('.jpg'):
src = os.path.join(os.path.abspath('.'), item)
img = cv2.imread(src)
shape = max(img.shape)
high = img.shape[0]
length = img.shape[1]
top = int((shape - high) / 2)
bottom = shape - high - top
left = int((shape - length) / 2)
right = shape - length - left
newimg = cv2.copyMakeBorder(
img,
top,
bottom,
left,
right,
cv2.BORDER_CONSTANT,
value=[
255,
255,
255])
cv2.imwrite("./img/" + item, newimg)
范例:
原图尺寸: (350, 277, 3)
扩展后图片尺寸: (350, 350, 3)
讨论:
cv2.copyMakeBorder(src,top, bottom, left, right ,borderType,value)
src:源图像
top,bottem,left,right: 分别表示四个方向上边界的长度
borderType: 边界的类型有以下几种:
BORDER_REFLICATE # 直接用边界的颜色填充, aaaaaa | abcdefg | gggg
BORDER_REFLECT # 倒映,abcdefg | gfedcbamn | nmabcd
BORDER_REFLECT_101 # 倒映,和上面类似,但在倒映时,会把边界空开,abcdefg | egfedcbamne | nmabcd
BORDER_WRAP # 类似于这种方式abcdf | mmabcdf | mmabcd
BORDER_CONSTANT # 常量,增加的变量通通为value色 [value][value] | abcdef | [value][value][value]