img = cv2.imread(“pie.png”,cv2.IMREAD_GRAYSCALE)
cv2.imshow(“img”,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
dst = cv2.Sobell(src,ddepth,dx,dy,ksize)
- ddepth : 图像的深度
- dx,dy :分别表示水平和竖直方向
- ksize :Sobel算子的大小
#计算x
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)#ksize只能是奇数
cv_show("sobelx",sobelx)
白到黑是整数,黑到白就是负数了,所有的负数会被截断成0。所以要取绝对值
#计算x---加上绝对值
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)#取绝对值
cv_show("sobelx",sobelx)
#计算y
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)#取绝对值
cv_show("sobely",sobely)
#分别计算x,y后,求和
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
cv_show("sobelxy",sobelxy)
注意:不建议x、y一起计算
#x、y一起 直接计算 ---不建议 sobel = cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3) sobel = cv2.convertScaleAbs(sobel)#取绝对值 cv_show("sobel",sobel)
换个例子:
img = cv2.imread(“girl.jpg”,cv2.IMREAD_GRAYSCALE)
cv2.imshow(“img”,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
x、y分开计算:
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)#取绝对值
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)#取绝对值
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
cv_show("sobelxy",sobelxy)
x、y一起计算
#整体计算
sobel = cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
sobel = cv2.convertScaleAbs(sobel)#取绝对值
cv_show("sobel",sobel)
# 不同算子的差异
img = cv2.imread("girll.png",cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)#取绝对值
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)#取绝对值
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)#更敏感,描绘的更加细致(换个图片跟明显)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
res = np.hstack((sobelxy,scharrxy,laplacian))
cv_show("res",res)