图像的Canny 边缘检测算法

版权声明:本文为博主原创文章,请转载时注明出处,欢迎浏览! https://blog.csdn.net/leemboy/article/details/84258914

使用OpenCV函数 Canny 检测边缘

Canny 边缘检测算法 是 John F. Canny 于 1986年开发出来的一个多级边缘检测算法,也被很多人认为是边缘检测的 最优算法, 最优边缘检测的三个主要评价标准是:

  • 低错误率: 标识出尽可能多的实际边缘,同时尽可能的减少噪声产生的误报。
  • 高定位性: 标识出的边缘要与图像中的实际边缘尽可能接近。
  • 最小响应: 图像中的边缘只能标识一次。

步骤

1、消除噪声。 使用高斯平滑滤波器卷积降噪。 下面显示了一个 size = 5 的高斯内核示例:

K = \dfrac{1}{159}\begin{bmatrix}           2 & 4 & 5 & 4 & 2 \\           4 & 9 & 12 & 9 & 4 \\           5 & 12 & 15 & 12 & 5 \\           4 & 9 & 12 & 9 & 4 \\           2 & 4 & 5 & 4 & 2                   \end{bmatrix}

2、计算梯度幅值和方向。 此处,按照Sobel滤波器的步骤:

  • 运用一对卷积阵列 (分别作用于 xy 方向):

G_{x} = \begin{bmatrix} -1 & 0 & +1  \\ -2 & 0 & +2  \\ -1 & 0 & +1 \end{bmatrix}  G_{y} = \begin{bmatrix} -1 & -2 & -1  \\ 0 & 0 & 0  \\ +1 & +2 & +1 \end{bmatrix}

  • 使用下列公式计算梯度幅值和方向:

    \begin{array}{l} G = \sqrt{ G_{x}^{2} + G_{y}^{2} } \\ \theta = \arctan(\dfrac{ G_{y} }{ G_{x} }) \end{array}

    梯度方向近似到四个可能角度之一(一般 0, 45, 90, 135)

3、非极大值 抑制。 这一步排除非边缘像素, 仅仅保留了一些细线条(候选边缘)。

4、滞后阈值: 最后一步,Canny 使用了滞后阈值,滞后阈值需要两个阈值(高阈值和低阈值):

  • 如果某一像素位置的幅值超过 阈值, 该像素被保留为边缘像素。
  • 如果某一像素位置的幅值小于 阈值, 该像素被排除。
  • 如果某一像素位置的幅值在两个阈值之间,该像素仅仅在连接到一个高于 阈值的像素时被保留。

Canny 推荐的 : 阈值比在 2:1 到3:1之间。

5、想要了解更多细节,你可以参考任何你喜欢的计算机视觉书籍。

代码如下:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

/// 全局变量

Mat src, src_gray;
Mat dst, detected_edges;

int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";

/**
* @函数 CannyThreshold
* @简介: trackbar 交互回调 - Canny阈值输入比例1:3
*/
void CannyThreshold(int, void*)
{
  /// 使用 3x3内核降噪
  blur( src_gray, detected_edges, Size(3,3) );

  /// 运行Canny算子
  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );

  /// 使用 Canny算子输出边缘作为掩码显示原图像
  dst = Scalar::all(0);

  src.copyTo( dst, detected_edges);
  imshow( window_name, dst );
}


/** @函数 main */
int main( int argc, char** argv )
{
  /// 装载图像
  src = imread( argv[1] );

  if( !src.data )
  { return -1; }

  /// 创建与src同类型和大小的矩阵(dst)
  dst.create( src.size(), src.type() );

  /// 原图像转换为灰度图像
  cvtColor( src, src_gray, CV_BGR2GRAY );

  /// 创建显示窗口
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );

  /// 创建trackbar
  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );

  /// 显示图像
  CannyThreshold(0, 0);

  /// 等待用户反应
  waitKey(0);

  return 0;
  }
 

猜你喜欢

转载自blog.csdn.net/leemboy/article/details/84258914