原理
- Canny 边缘检测算法 是 John F. Canny 于 1986年开发出来的一个多级边缘检测算法,也被很多人认为是边缘检测的 最优算法, 最优边缘检测的三个主要评价标准是:
- 低错误率: 标识出尽可能多的实际边缘,同时尽可能的减少噪声产生的误报。
- 高定位性: 标识出的边缘要与图像中的实际边缘尽可能接近。
- 最小响应: 图像中的边缘只能标识一次。
步骤
-
消除噪声。 使用高斯平滑滤波器卷积降噪。 下面显示了一个 的高斯内核示例:
-
计算梯度幅值和方向。 此处,按照Sobel滤波器的步骤:
-
运用一对卷积阵列 (分别作用于 和 方向):
-
使用下列公式计算梯度幅值和方向:
梯度方向近似到四个可能角度之一(一般 0, 45, 90, 135)
-
-
非极大值 抑制。 这一步排除非边缘像素, 仅仅保留了一些细线条(候选边缘)。
-
滞后阈值: 最后一步,Canny 使用了滞后阈值,滞后阈值需要两个阈值(高阈值和低阈值):
- 如果某一像素位置的幅值超过 高 阈值, 该像素被保留为边缘像素。
- 如果某一像素位置的幅值小于 低 阈值, 该像素被排除。
- 如果某一像素位置的幅值在两个阈值之间,该像素仅仅在连接到一个高于 高 阈值的像素时被保留。
Canny 推荐的 高:低 阈值比在 2:1 到3:1之间。
-
想要了解更多细节,你可以参考任何你喜欢的计算机视觉书籍。
源码
- 本程序做什么?
- 要求使用者输入一个数字,设置 Canny Edge Detector 的低阈值 (通过trackbar)
- 使用 Canny 边缘检测 产生一个 mask (白线代表边缘,黑色代表背景)。
- 使用 mask 作为掩码显示原图像。
- 本教程的源码如下,你也可以从 这里 下载
解释
-
创建程序中要用到的变量:
-
装载原图像:
-
创建与 src 同类型和大小的矩阵(dst)
-
将输入图像转换到灰度空间 (使用函数 cvtColor):
-
创建显示窗口
-
创建trackbar,来获取用户交互输入的低阈值:
注意:
- 通过trackbar控制的变量为 lowThreshold ,上限为 max_lowThreshold (我们已经设定为100)
- 每次用户通过trackbar产生变动,回调函数 CannyThreshold 被调用.
-
让我们一步一步的来观察 CannyThreshold 函数:
-
首先, 使用 3x3的内核平滑图像:
-
其次,运用 Canny 寻找边缘:
输入参数:
- detected_edges: 原灰度图像
- detected_edges: 输出图像 (支持原地计算,可为输入图像)
- lowThreshold: 用户通过 trackbar设定的值。
- highThreshold: 设定为低阈值的3倍 (根据Canny算法的推荐)
- kernel_size: 设定为 3 (Sobel内核大小,内部使用)
-
-
填充 dst 图像,填充值为0 (图像全黑).
-
最后, 使用函数 copyTo 标识被检测到的边缘部分 (背景为黑色).
copyTo 将 src 图像拷贝到 dst . 但是,仅仅拷贝掩码不为0的像素。既然Canny边缘检测的输出是镶嵌在黑色背景中的边缘像素,因此其结果 dst 图像除了被检测的边缘像素,其余部分都为黑色。
-
显示结果:
结果
-
在编译上面的代码之后, 我们可以运行结果,将图片路径输入,如下图:
-
滑动标尺, 尝试不同的阈值,我们得到如下结果:
-
仔细观察边缘像素是如何叠加在黑色背景之上的。