本节课主要介绍了几种图像梯度计算的算子以及梯度的计算
先上代码:
def sobel(img):
dstx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize = 3)#cv2,CV_64F可以表示负数 1,0选择x或者y,ksize是算子矩阵大小
dsty = cv2.Sobel(img,cv2.CV_64F,0,1,ksize = 3)#cv2,CV_64F可以表示负数 1,0选择x或者y
#同时计算x梯度与y梯度,即在上面两个函数中dx,dy参数都为1
dstx = cv2.convertScaleAbs(dstx)#取绝对值,不经过处理直接show会导致有小于0的数值存在,在opencv中会被置为0
dsty = cv2.convertScaleAbs(dsty)
return cv2.addWeighted(dstx,1,dsty,1,0)
def scharr(img):
dstx = cv2.Scharr(img,cv2.CV_64F,1,0)#cv2,CV_64F可以表示负数 1,0选择x或者y
dsty = cv2.Scharr(img,cv2.CV_64F,0,1)#cv2,CV_64F可以表示负数 1,0选择x或者y
dstx = cv2.convertScaleAbs(dstx)#取绝对值
dsty = cv2.convertScaleAbs(dsty)
return cv2.addWeighted(dstx,1,dsty,1,0)
def laplacian(img):
lap = cv2.Laplacian(img,cv2.CV_64F)
return cv2.convertScaleAbs(lap)
下面介绍几种梯度计算算子:
计算方式如下:
G x = [ − 1 0 + 1 − 2 0 + 2 − 1 0 + 1 ] ∗ A G~x~ = \begin{bmatrix} -1&0&+1\\ -2&0&+2\\ -1&0&+1\\ \end{bmatrix}*A G x =⎣⎡−1−2−1000+1+2+1