
1.5 图像边缘检测算法
图像边缘检测是计算机视觉与图像处理中的基本问题,主要目的是提取图像中明暗变化明显的边缘细节信息。图像边缘检测的算法有很多,包括传统的模板算子(Sobel、Roberts、Prewitt、Laplace)、形态学边缘检测、经典的 Canny 边缘检测及基于深度学习的边缘检测算法等。本节主要介绍 Sobel模板算子和经典的 Canny边缘检测算法,在后续章节的人像细节增强、斑点检测等算法中将会应用到该算法。
1.5.1 Sobel边缘检测
Sobel 模板算子是 Irwin Sobel 在 1968 年发表的论文 An Isotropic 3×3 Image Gradient Operator中提出的一种一阶导数模板算子,用来计算图像灰度函数的近似梯度[7]。
Sobel模板算子如下:

其中,Gx表示水平方向的卷积模板,Gy表示垂直方向的卷积模板。
对于图像中任何一点的像素P(i, j),使用水平和垂直卷积模板分别对图像进行卷积操作,得到水平梯度GX和垂直梯度GY,则梯度幅度计算如下:

完整梯度幅度计算公式如下:

Sobel边缘检测结果计算如下:

其中,255白色表示边缘,0黑色表示背景。
Sobel边缘检测的效果如图1.46所示。

图1.46 本节中的Sobel边缘检测效果
PS中的查找边缘功能,就是基于Sobel模板算子实现的,它的公式如下:

查找边缘效果如图1.47所示。

图1.47 PS中查找边缘的效果
编程实现
我们使用C语言实现Sobel边缘检测算法:




本节介绍的算法的DEMO效果如图1.48所示,分别实现了Sobel边缘检测和PS中的查找边缘功能。

图1.48 本节算法DEMO的效果
本节所有代码工程及DEMO见代码包中1.6.1文件夹中的文件。
1.5.2 经典Canny边缘检测
Canny边缘检测是 John Canny在 1986年首次提出的一种改进的边缘检测方法。该方法主要通过图像信号函数的极大值来判断图像的边缘像素点,与基本的 Sobel 模板算子等相比,其具有低错误率、高定位性等优点[8],因而被广泛应用。
Canny边缘检测算法介绍如下。
1.高斯滤波平滑处理
由于图像中经常包含一些高斯噪声,因此,在边缘检测前,要先用高斯滤波器对其进行滤波。为了方便,这里使用如下高斯滤波器模板:

2.梯度计算
使用一阶导数算子(一般用 Sobel 模板算子)计算灰度图像中每个像素点在水平和垂直方向上的导数GX、GY,得出梯度向量(GX,GY),最后得到该像素点的梯度幅度G和相位角D,具体可参考1.5.1节的内容。

3.非极大值抑制
对于上面计算得到的梯度值,其实是一个粗边缘信息,可以通过非极大值抑制去掉一些非边缘信息。这里将当前像素的梯度值与其在梯度方向上的邻域像素的梯度值做对比,如果当前像素的梯度值为最大值,则保留该点的梯度信息,否则将该点删除或将像素值置为0。
4.双阈值边缘检测和边缘连接
由非极大值抑制得到的边缘信息中包含较多伪边缘信息,可通过设置高低双阈值的方法去除它们。首先,设定两个阈值,一个高阈值,一个低阈值,阈值大小根据实际情况设置,一般高阈值为低阈值的2.5倍。
然后判断:梯度值大于高阈值的像素点一定是边缘点,将该点像素值置为 255;梯度值小于低阈值的像素点一定不是边缘点,将该点像素值置为 0;介于高低阈值之间的像素点为准边缘点,对于这些点,如果其像素点周围 8邻域的梯度值都小于高阈值,则认为其不是边缘点,将该点像素值置为0,否则置为255。
上述四个步骤,就是Canny边缘检测算法的计算过程,Canny边缘检测效果如图1.49所示。

图1.49 Canny边缘检测效果(highThreshold=50、lowThreshold=5)
编程实现
我们使用C语言实现Canny边缘检测算法:







本节所有代码工程及DEMO见代码包中1.6.2文件夹中的文件。