Canny算法检测分为5个步骤:
1:使用高斯滤波平滑图像,减少图像噪声
2:计算图像种每个像素值灰度值的梯度方向和幅值
3:应用非极大值抑制算法消除边缘检测带来的杂散响应
4:应用双阈值法划分强边缘和弱边缘
5:消除孤立边缘
import cv2
import sys
if __name__ == '__main__':
image=cv2.imread('lbxx.jpg',cv2.IMREAD_ANYDEPTH)
if image is None:
print('这个图像已经损坏')
sys.exit()
#通过高阈值检测图像边缘,apertureSize=3是sobel算子的大小,100和200是界定高阈值的范围
result_high=cv2.Canny(image,100,200,apertureSize=3)
#通过低阈值检测图像边缘
result_low=cv2.Canny(image,20,40,apertureSize=3)
#高斯模糊后检测图像的边缘
result_gauss=cv2.GaussianBlur(image,(3,3),5)
result_gauss=cv2.Canny(result_gauss,100,200,apertureSize=3)
#创建并设置窗口,来显示三种结果
cv2.namedWindow('result_high',cv2.WINDOW_NORMAL)
cv2.resizeWindow('result_high',800,800)
cv2.imshow('result_high',result_high)
cv2.namedWindow('result_low', cv2.WINDOW_NORMAL)
cv2.resizeWindow('result_low', 800, 800)
cv2.imshow('result_low',result_low)
cv2.namedWindow('result_gauss', cv2.WINDOW_NORMAL)
cv2.resizeWindow('result_gauss', 800, 800)
cv2.imshow('result_gauss',result_gauss)
cv2.waitKey(0)
cv2.destroyAllWindows()
展现出的结果:
通过上面的运行结果,我们知道,较高的阈值会降低噪声对图像提取边缘结果的以影响,同时会减少一些边缘信息,而且我们发现先利用高斯模糊在进行边缘检测,能对那些边缘纹理多的大幅度的降低边缘检测的结果,对纹理少的显示出的边缘结果却不是很明显。