cvCanny函数源码解析
2016-05-16 22:10
477 查看
这段时间要做图像识别,首先肯定逃不过图像的边缘检测,这是基础。
边缘检测算法有很多,但是综合比较来看,canny算子的效果最好,所以这边就写一下opencv中cvcanny函数怎么使用,以及它的源码分析。
详细的步骤以及参数含义见这个博客 http://blog.csdn.net/poem_qianmo/article/details/25560901
这边我简单地写一下:
1、用高斯滤波器平滑图像(注意:cvCanny函数里面并没有这一步,所以使用之前要加上blur)。
2、用sobel算子来计算两个方向的梯度幅值。
3、对梯度幅值进行非极大值抑制 。
4、用双阈值算法检测和连接边缘。
下面是源代码:
真正的函数是Canny:(建议看之前,把原理搞明白了,有些原理性的东西,我都没有加注释,或者写得不是太具体)
这边先放一张程序中ring buffer的结构图,帮助更好地理解
有任何不准确的地方,欢迎讨论。
边缘检测算法有很多,但是综合比较来看,canny算子的效果最好,所以这边就写一下opencv中cvcanny函数怎么使用,以及它的源码分析。
详细的步骤以及参数含义见这个博客 http://blog.csdn.net/poem_qianmo/article/details/25560901
这边我简单地写一下:
1、用高斯滤波器平滑图像(注意:cvCanny函数里面并没有这一步,所以使用之前要加上blur)。
2、用sobel算子来计算两个方向的梯度幅值。
3、对梯度幅值进行非极大值抑制 。
4、用双阈值算法检测和连接边缘。
下面是源代码:
void cvCanny( const CvArr* image, CvArr* edges, double threshold1, double threshold2, int aperture_size ) { cv::Mat src = cv::cvarrToMat(image), dst = cv::cvarrToMat(edges); CV_Assert( src.size == dst.size && src.depth() == CV_8U && dst.type() == CV_8U ); cv::Canny(src, dst, threshold1, threshold2, aperture_size & 255, (aperture_size & CV_CANNY_L2_GRADIENT) != 0); }
真正的函数是Canny:(建议看之前,把原理搞明白了,有些原理性的东西,我都没有加注释,或者写得不是太具体)
这边先放一张程序中ring buffer的结构图,帮助更好地理解
#include "precomp.hpp" void cv::Canny( InputArray _src, OutputArray _dst,//InputArray是引用类型 double low_thresh, double high_thresh, int aperture_size, bool L2gradient ) { Mat src = _src.getMat();//转换成mat形式处理 CV_Assert( src.depth() == CV_8U ); _dst.create(src.size(), CV_8U); Mat dst = _dst.getMat(); //L2gradient默认为false,false时表示计算时用简便的||+||,ture时用根号下开方 if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)//aperture_size为-1时成立 { //backward compatibility aperture_size &= ~CV_CANNY_L2_GRADIENT; L2gradient = true; } //aperture_size非-1,1,3,5,7退出,一般3为默认 if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7))) CV_Error(CV_StsBadFlag, ""); #ifdef HAVE_TEGRA_OPTIMIZATION if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient)) return; #endif const int cn = src.channels();//就当做单通道,这样思考起来比较方便 cv::Mat dx(src.rows, src.cols, CV_16SC(cn));//用于存储方向导数的矩阵 cv::Mat dy(src.rows, src.cols, CV_16SC(cn)); //aperture_size是窗口的大小 cv::Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE);//对x方向求方向导数 cv::Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE);//对y方向求方向导数 if (low_thresh > high_thresh) std::swap(low_thresh, high_thresh); if (L2gradient)//true时为平方运算,所以相应的阈值也要进行平方运算 { low_thresh = std::min(32767.0, low_thresh); high_thresh = std::min(32767.0, high_thresh); if (low_thresh > 0) low_thresh *= low_thresh; if (high_thresh > 0) high_thresh *= high_thresh; } int low = cvFloor(low_thresh); int high = cvFloor(high_thresh); //64位兼容方式编译 typedef _W64 int ptrdiff_t ptrdiff_t mapstep = src.cols + 2;//跨度,+2是在左右各加一条边 //这个分配空间是 图像的大小(存放边缘信息) + 3个跨度大小的容量组成一个ringbuffer(用于重复存放三排梯度值) //ring buffer 我的理解 优点:重复使用内存 , 速度很快 具体的情况还是最好查一下 cv::AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int)); int* mag_buf[3];//定义指针数组 //uchar* 是操作符重载,返回了buffer的指针,int* 是强制转换为int类型进行处理 mag_buf[0] = (int*)(uchar*)buffer; mag_buf[1] = mag_buf[0] + mapstep*cn; mag_buf[2] = mag_buf[1] + mapstep*cn; memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));//ringbuffer第一排赋值为0 uchar* map = (uchar*)(mag_buf[2] + mapstep*cn);//map用来存储是否为边缘的信息 //分别给图像中最上面和最下面一行都赋值为1 memset(map, 1, mapstep); memset(map + mapstep*(src.rows + 1), 1, mapstep); int maxsize = std::max(1 << 10, src.cols * src.rows / 10); std::vector<uchar*> stack(maxsize);//指针类型的向量 uchar **stack_top = &stack[0]; uchar **stack_bottom = &stack[0]; /* sector numbers (Top-Left Origin) 1 2 3 * * * * * * 0*******0 * * * * * * 3 2 1 */ //将图像中心点梯度方向近似为4个方向 0, 45, 90 及135,直接可以利用8邻域进行比较计算 //CANNY_PUSH(d) d表示的是一个地址 stack中存的是地址 将改地址的指向的内容赋值为2,表明是边缘,并将该地址压入栈中 #define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d) #define CANNY_POP(d) (d) = *--stack_top//弹出地址 // calculate magnitude and angle of gradient, perform non-maxima supression. // fill the map with one of the following values: // 0 - the pixel might belong to an edge // 1 - the pixel can not belong to an edge // 2 - the pixel does belong to an edge //边缘信息只有3中,0,1,2 for (int i = 0; i <= src.rows; i++) { //i=0时,就第一次刚进来时,存在mag_buf[1]和 i>0时存在mag_buf[2]中,后面新的梯度幅度值都放到mag_buf[2] //循环结束前,最后一步会使ring buffer顺序循环一次,使原来mag_buf[1]中的内容放到mag_buf[0] //mag_buf[2]放到mag_buf[1]中,原来mag_buf[0]中的内容就被覆盖掉 int* _norm = mag_buf[(i > 0) + 1] + 1;//跳过第一列,指向原始图像每一行的第一个点 if (i < src.rows) { short* _dx = dx.ptr<short>(i);//指向第i行 short* _dy = dy.ptr<short>(i); if (!L2gradient) { for (int j = 0; j < src.cols*cn; j++) _norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));//计算第i行的梯度的幅度值 } else { for (int j = 0; j < src.cols*cn; j++) _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j]; } if (cn > 1)//不管 { for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn) { int maxIdx = jn; for(int k = 1; k < cn; ++k) if(_norm[jn + k] > _norm[maxIdx]) maxIdx = jn + k; _norm[j] = _norm[maxIdx]; _dx[j] = _dx[maxIdx]; _dy[j] = _dy[maxIdx]; } } _norm[-1] = _norm[src.cols] = 0;//第一列和最后一列不可能是边缘,梯度设为0 } else memset(_norm-1, 0, /* cn* */mapstep*sizeof(int));//i等于src.rows,也就是最后一行,都赋值为0,存在mag_buf[2]中 // at the very beginning we do not have a complete ring // buffer of 3 magnitude rows for non-maxima suppression //满足非极大值限制,只能推出该点可能为边缘点 //这里要满足两个条件,如果是梯度在邻域中是最大值,且大于high阈值,确定是边缘点,然后以此为中心需找邻域中满足低阈值的点 if (i == 0) continue; uchar* _map = map + mapstep*i + 1;//边缘信息指针指向当前行 _map是暂时值 存放当前行的边缘信息 _map[-1] = _map[src.cols] = 1;//第一列和最后一列不可能是边缘 int* _mag = mag_buf[1] + 1; // take the central row 存放当前行的梯度值 ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];//因为使用int为基本类型进行处理,所以magstep1为一行的跨度 ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];//负数 用于向上跳转一行 const short* _x = dx.ptr<short>(i-1);//x方向梯度值指针指向上一行(这边算角度为什么要指向上一行,不太明白。。。) const short* _y = dy.ptr<short>(i-1); if ((stack_top - stack_bottom) + src.cols > maxsize)//当存不下时,给stack扩容 { int sz = (int)(stack_top - stack_bottom); maxsize = maxsize * 3/2; stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } int prev_flag = 0; for (int j = 0; j < src.cols; j++) { #define CANNY_SHIFT 15 const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5);//tan22.5 位作平移提高计算精度 int m = _mag[j];//_mag = mag_buf[1] + 1 当前点读出前面算的梯度值 if (m > low)//大于低阈值 { int xs = _x[j]; int ys = _y[j]; int x = std::abs(xs);//当前点的 int y = std::abs(ys) << CANNY_SHIFT; int tg22x = x * TG22; if (y < tg22x)//当角度小于22.5度时,比较左右两个点的值 { if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push; } else { int tg67x = tg22x + (x << (CANNY_SHIFT+1)); if (y > tg67x)//当角度大于67.5度时,比较上下两个点的值 { if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push; } else { int s = (xs ^ ys) < 0 ? -1 : 1;//按位异或,用于判断符号是否相同,不同就为-1,比较对角线上两个点的值 if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push; } } } prev_flag = 0;//为1代表前一个像素点为边缘点,为0代表前一个点为非边缘点 _map[j] = uchar(1);//不满足上面任何一种梯度情况,表明不可能为边缘点 continue; __ocv_canny_push: //前一个点不是边缘点,并且当前点的值大于high阈值,并且正对上一行那个点也不是边缘点,那么该点为边缘点 //说白了就是领域最大值才有资格先成为边缘点 if (!prev_flag && m > high && _map[j-mapstep] != 2) { CANNY_PUSH(_map + j);//将该地址对应的值改为2,并且把地址压入栈中 prev_flag = 1; } else _map[j] = 0;//只要不满足上面三个条件中的一个,只能说明可能是边缘点 ,所谓的非极大值抑制 } // scroll the ring buffer _mag = mag_buf[0]; mag_buf[0] = mag_buf[1]; mag_buf[1] = mag_buf[2]; mag_buf[2] = _mag; } //------------------------最大的for循环到这-------------------------- // now track the edges (hysteresis thresholding) while (stack_top > stack_bottom) { uchar* m; if ((stack_top - stack_bottom) + 8 > maxsize)//边缘点超过整幅图像的1/10 { int sz = (int)(stack_top - stack_bottom); maxsize = maxsize * 3/2; stack.resize(maxsize); stack_bottom = &stack[0]; stack_top = stack_bottom + sz; } CANNY_POP(m);//pop出边缘地址 //m周围8领域内的原来是0的点(可能是边缘点的点)改为边缘点 if (!m[-1]) CANNY_PUSH(m - 1); if (!m[1]) CANNY_PUSH(m + 1); if (!m[-mapstep-1]) CANNY_PUSH(m - mapstep - 1); if (!m[-mapstep]) CANNY_PUSH(m - mapstep); if (!m[-mapstep+1]) CANNY_PUSH(m - mapstep + 1); if (!m[mapstep-1]) CANNY_PUSH(m + mapstep - 1); if (!m[mapstep]) CANNY_PUSH(m + mapstep); if (!m[mapstep+1]) CANNY_PUSH(m + mapstep + 1); } // the final pass, form the final image const uchar* pmap = map + mapstep + 1;//从图像第二行开始 uchar* pdst = dst.ptr(); for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step) { for (int j = 0; j < src.cols; j++) pdst[j] = (uchar)-(pmap[j] >> 1);//pmap中为2的,才赋值为1,0或1都变成0 (uchar)- 跟一个数字,这时(uchar)表示256 总体上说是一种二值化 } }
有任何不准确的地方,欢迎讨论。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性