图像边缘检测
1.sobel理论
G
=
G
X
2
+
G
y
2
G = \sqrt{G_X^2+G_y^2}
G=GX2?+Gy2?
?
分别计算X轴方向上的梯度差,y轴方向上的梯度差,然后再权重相加。
Sobel(src, ddepth, dx, dy, dst=None, ksize=None, scale=None, delta=None, borderType=None)
import cv2
import numpy as np
o =cv2.imread("image/sobel.bmp",cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(o,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(o,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
sobelxy11= cv2.Sobel(o,cv2.CV_64F,1,1,ksize=3)
cv2.imshow("original",o)
cv2.imshow("x",sobelx)
cv2.imshow("y",sobely)
cv2.imshow("xy",sobelxy)
cv2.imshow("xy11",sobelxy11)
cv2.waitKey()
cv2.destroyAllWindows()
2.scharr理论
Scharr(src, ddepth, dx, dy, dst=None, scale=None, delta=None, borderType=None)
与sobel不同的是,不能同时计算X轴方向和y轴方向的梯度,否则会报错
import cv2
import numpy as np
o = cv2.imread('image\\scharr.bmp',cv2.IMREAD_GRAYSCALE)
scharrxy11=cv2.Scharr(o,cv2.CV_64F,1,1)
cv2.imshow("original",o)
cv2.imshow("xy11",scharrxy11)
cv2.waitKey()
cv2.destroyAllWindows()
3.sobel算子和scharr算子对比
import cv2
import numpy as np
o = cv2.imread('image\\lena.bmp',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(o,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(o,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
scharrx = cv2.Scharr(o,cv2.CV_64F,1,0)
scharry = cv2.Scharr(o,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0)
cv2.imshow("original",o)
cv2.imshow("sobelxy",sobelxy)
cv2.imshow("scharrxy",scharrxy)
cv2.waitKey()
cv2.destroyAllWindows()
4. 拉普拉斯Laplacian算子
Laplacian(src, ddepth, dst=None, ksize=None, scale=None, delta=None, borderType=None)
import cv2
import numpy as np
o = cv2.imread('image\\lena.bmp',cv2.IMREAD_GRAYSCALE)
laplacian = cv2.Laplacian(o,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
cv2.imshow("original",o)
cv2.imshow("laplacian",laplacian)
cv2.waitKey()
cv2.destroyAllWindows()
5.Canny边缘检测
Canny(image, threshold1, threshold2, edges=None, apertureSize=None, L2gradient=None)
import cv2
import numpy as np
o=cv2.imread("image\\lena.bmp",cv2.IMREAD_GRAYSCALE)
r1=cv2.Canny(o,100,200)
r2=cv2.Canny(o,64,128)
cv2.imshow("original",o)
cv2.imshow("result1",r1)
cv2.imshow("result2",r2)
cv2.waitKey()
cv2.destroyAllWindows()
比较不同的阈值选取对检测结果的影响
|