我们经常会有对图像边缘做扩展的需求.比如
希望卷积后得到的矩阵大小不变
希望改变图像大小,但是不改变宽高比
opencv实现
opencv中使用copyMakeBorder()来完成这一功能
api
src是原图像矩阵
dst是新图像矩阵
top/bottom/left/right是边界扩展的大小(比如5就代表5个像素)
borderType
value是扩充的像素填什么值
borderType分两种:
BORDER_CONSTANT
边缘填充用固定像素值,比如填充黑边,就用0,白边255
BORDER_REPLICATE
用原始图像相应的边缘的像素去做填充,看起来有一种把图像边缘"拉糊了"的效果
opencv示例
import sys
import cv2 as cv
def test():
src = cv.imread("/home/sc/disk/keepgoing/opencv_test/lights.jpeg")
top = int(0.05 * src.shape[0]) # shape[0] = rows
bottom = top
left = int(0.04 * src.shape[1]) # shape[1] = cols
right = left
value = [0,0,0]
borderType = cv.BORDER_CONSTANT
dst1 = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
borderType = cv.BORDER_REPLICATE
dst2 = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
cv.imshow("blackborder",dst1)
cv.imshow("BORDER_REPLICATE",dst2)
if 27 == cv.waitKey():
cv.destroyAllWindows()
test()
效果如下: