Canny是常用的边缘检测方法,其特点是试图将独立边的候选像素拼装成轮廓。
John Canny于1986年提出Canny算子,它与Marr(LoG)边缘检测方法类似,也属于是先平滑后求导数的方法。
John Canny研究了最优边缘检测方法所需的特性,给出了评价边缘检测性能优劣的三个指标:
1.好的信噪比,即将非边缘点判定为边缘点的概率要低,将边缘点判为非边缘点的概率要低;
2.高的定位性能,即检测出的边缘点要尽可能在实际边缘的中心;
3. 对单一边缘仅有唯一响应,即单个边缘产生多个响应的概率要低,并且虚假响应边缘应该得到最大抑制。
用一句话说,就是希望在提高对景物边缘的敏感性的同时,可以抑制噪声的方法才是好的边缘提取方法。
Canny算子求边缘点具体算法步骤如下:
1. 用高斯滤波器平滑图像.
2. 用一阶偏导有限差分计算梯度幅值和方向.
3. 对梯度幅值进行非极大值抑制 .
4. 用双阈值算法检测和连接边缘
Canny edge detector and produces the edge map.
Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false );
image
单通道输入图像.
edges
单通道存储边缘的输出图像
threshold1
第一个阈值
threshold2
第二个阈值
aperture_size
Sobel 算子内核大小 (见 Sobel).
L2gradient=false
CV_CANNY_L2_GRADIENT 宏定义其值为 Value = (1<<31).
默认不使用 L2gradient
函数 Canny 采用 CANNY 算法发现输入图像的边缘而且在输出图像中标识这些边缘。threshold1和threshold2 当中的小阈值用来控制边缘连接,大的阈值用来控制强边缘的初始分割。
- 注意事项:cvCanny只接受单通道图像作为输入。
/*******************************************************
测试程序【寻找轮廓】
时间:2016年9月3日
//【1、canny检测边缘】
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
//【2、参数canny——>contours】
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
********************************************************/
Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);
// Function header
void thresh_callback(int, void* );
int main(void)
{
src = imread("lab.jpg", 1 );
//【预处理】
cvtColor( src, src_gray, COLOR_BGR2GRAY );
blur( src_gray, src_gray, Size(3,3) );
const char* source_window = "Source";
namedWindow( source_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
thresh_callback( 0, 0 );
waitKey(0);
return(0);
}
void thresh_callback(int, void* )
{
Mat canny_output; //Canny输出
vector<vector<Point> > contours; //二维为数组
vector<Vec4i> hierarchy;
//【1、canny检测边缘】
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
// Find contours
//【2、参数canny——>contours】:
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
//【3、绘制轮廓】
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
for( size_t i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() );
}
namedWindow( "Contours", WINDOW_AUTOSIZE );
imshow( "Contours", drawing );
}