標籤:
OpenCV Canny 源碼注釋與分析
1986年,John F.Canny 完善了邊緣檢測理論,Canny演算法以此命名。
Canny 演算法的步驟:
1. 使用濾波器卷積降噪
2. 使用Sobel導數計算梯度幅值和方向
3. 非極大值抑制 + 滯後閾值
在正式處理前,用高斯濾平滑波器對映像做濾波降噪的操作,避免雜訊點的幹擾,但在OpenCV的canny源碼中,沒有進行高斯濾波,需要使用者自行濾波;有些資料將非極大值抑制和滯後閾值視為兩個步驟也是可行的,但是在源碼中非極大值抑制 和滯後閾值是同時進行的。
canny源碼的位置:\opencv\sources\modules\imgproc\src\canny.cpp參考了網上許多資料,有不足之處請指正,謝謝。
/*M/////////////////////////////////////////////////////////////////////////////////////////// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.//// By downloading, copying, installing or using the software you agree to this license.// If you do not agree to this license, do not download, install,// copy or use the software.////// Intel License Agreement// For Open Source Computer Vision Library//// Copyright (C) 2000, Intel Corporation, all rights reserved.// Third party copyrights are property of their respective owners.//// Redistribution and use in source and binary forms, with or without modification,// are permitted provided that the following conditions are met://// * Redistribution's of source code must retain the above copyright notice,// this list of conditions and the following disclaimer.//// * Redistribution's in binary form must reproduce the above copyright notice,// this list of conditions and the following disclaimer in the documentation// and/or other materials provided with the distribution.//// * The name of Intel Corporation may not be used to endorse or promote products// derived from this software without specific prior written permission.//// This software is provided by the copyright holders and contributors "as is" and// any express or implied warranties, including, but not limited to, the implied// warranties of merchantability and fitness for a particular purpose are disclaimed.// In no event shall the Intel Corporation or contributors be liable for any direct,// indirect, incidental, special, exemplary, or consequential damages// (including, but not limited to, procurement of substitute goods or services;// loss of use, data, or profits; or business interruption) however caused// and on any theory of liability, whether in contract, strict liability,// or tort (including negligence or otherwise) arising in any way out of// the use of this software, even if advised of the possibility of such damage.////M*/#include "precomp.hpp"/*#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)#define USE_IPP_CANNY 1#else#undef USE_IPP_CANNY#endif*/#ifdef USE_IPP_CANNYnamespace cv{static bool ippCanny(const Mat& _src, Mat& _dst, float low, float high){ int size = 0, size1 = 0; IppiSize roi = { _src.cols, _src.rows }; ippiFilterSobelNegVertGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size); ippiFilterSobelHorizGetBufferSize_8u16s_C1R(roi, ippMskSize3x3, &size1); size = std::max(size, size1); ippiCannyGetSize(roi, &size1); size = std::max(size, size1); AutoBuffer<uchar> buf(size + 64); uchar* buffer = alignPtr((uchar*)buf, 32); Mat _dx(_src.rows, _src.cols, CV_16S); if( ippiFilterSobelNegVertBorder_8u16s_C1R(_src.data, (int)_src.step, _dx.ptr<short>(), (int)_dx.step, roi, ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 ) return false; Mat _dy(_src.rows, _src.cols, CV_16S); if( ippiFilterSobelHorizBorder_8u16s_C1R(_src.data, (int)_src.step, _dy.ptr<short>(), (int)_dy.step, roi, ippMskSize3x3, ippBorderRepl, 0, buffer) < 0 ) return false; if( ippiCanny_16s8u_C1R(_dx.ptr<short>(), (int)_dx.step, _dy.ptr<short>(), (int)_dy.step, _dst.data, (int)_dst.step, roi, low, high, buffer) < 0 ) return false; return true;}}#endifvoid cv::Canny( InputArray _src, OutputArray _dst, double low_thresh, double high_thresh, int aperture_size, bool L2gradient ){ Mat src = _src.getMat(); //輸入映像,必須為單通道灰階圖 CV_Assert( src.depth() == CV_8U ); // 8位無符號 _dst.create(src.size(), CV_8U); //根據src的大小構造目標矩陣dst Mat dst = _dst.getMat(); //輸出映像,為單通道黑白圖 // low_thresh 表示低閾值, high_thresh表示高閾值 // aperture_size 表示運算元大小,預設為3 // L2gradient計算梯度幅值的標識,預設為false // 如果L2gradient為false 並且 apeture_size的值為-1(-1的二進位標識為:1111 1111) // L2gradient為false 則計算sobel導數時,用G = |Gx|+|Gy| // L2gradient為true 則計算sobel導數時,用G = Math.sqrt((Gx)^2 + (Gy)^2) 根號下 開平方 if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT) {// CV_CANNY_L2_GRADIENT 宏定義其值為: Value = (1<<31) 1左移31位 即2147483648 //backward compatibility // ~標識按位取反 aperture_size &= ~CV_CANNY_L2_GRADIENT;L2gradient = true; } // 判別條件1:aperture_size是奇數 // 判別條件2: aperture_size的範圍應當是[3,7], 預設值3 if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7))) CV_Error(CV_StsBadFlag, ""); // 報錯 if (low_thresh > high_thresh) // 如果低閾值 > 高閾值 std::swap(low_thresh, high_thresh); // 則交換低閾值和高閾值#ifdef HAVE_TEGRA_OPTIMIZATION if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient)) return;#endif#ifdef USE_IPP_CANNY if( aperture_size == 3 && !L2gradient && ippCanny(src, dst, (float)low_thresh, (float)high_thresh) ) return;#endif const int cn = src.channels(); // cn為輸入映像的通道數 Mat dx(src.rows, src.cols, CV_16SC(cn)); // 儲存 x方向 方嚮導數的矩陣,CV_16SC(cn):16位有符號cn通道 Mat dy(src.rows, src.cols, CV_16SC(cn)); // 儲存 y方向 方嚮導數的矩陣 ...... /*Sobel參數說明:(參考cvSobel) cvSobel( const CvArr* src, // 輸入映像 CvArr* dst, // 輸入映像 int xorder, // x方向求導的階數 int yorder, // y方向求導的階數 int aperture_size = 3 // 濾波器的寬和高 必須是奇數); */ // BORDER_REPLICATE 表示當卷積點在映像的邊界時,原始映像邊緣的像素會被複製,並用複製的像素擴充原始圖的尺寸 //計算x方向的sobel方嚮導數,計算結果存在dx中 Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE); //計算y方向的sobel方嚮導數,計算結果存在dy中 Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE); //L2gradient為true時, 表示需要根號下開平方運算,閾值也需要平方 if (L2gradient) { 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); // cvFloor返回不大於參數的最大整數值, 相當於取整 int high = cvFloor(high_thresh); // ptrdiff_t 是C/C++標準庫中定義的一個資料類型,signed類型,通常用於儲存兩個指標的差(距離),可以是負數 // mapstep 用於存放 ptrdiff_t mapstep = src.cols + 2; // +2 表示左右各擴充一條邊 // AutoBuffer<uchar> 會自動分配一定大小的記憶體,並且指定記憶體中的資料類型是uchar // 列數 +2 表示映像左右各自擴充一條邊 (用於複製邊緣像素,擴大原始映像) // 行數 +2 表示映像上下各自擴充一條邊 AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int)); int* mag_buf[3]; //定義一個大小為3的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)); uchar* map = (uchar*)(mag_buf[2] + mapstep*cn); memset(map, 1, mapstep); memset(map + mapstep*(src.rows + 1), 1, mapstep); int maxsize = std::max(1 << 10, src.cols * src.rows / 10); // 2的10次冪 1024 std::vector<uchar*> stack(maxsize); // 定義指標類型向量,用於存地址 uchar **stack_top = &stack[0]; // 棧頂指標(指向指標的指標),指向stack[0], stack[0]也是一個指標 uchar **stack_bottom = &stack[0]; // 棧底指標 ,初始時 棧底指標 == 棧頂指標 // 梯度的方向被近似到四個角度之一 (0, 45, 90, 135 四選一) /* sector numbers (Top-Left Origin) 1 2 3 * * * * * * 0*******0 * * * * * * 3 2 1 */ // define 定義函數塊 // CANNY_PUSH(d) 是入棧函數, 參數d表示地址指標,讓該指標指向的內容為整數2,併入棧,棧頂指標+1 // 2表示 像素屬於某條邊緣 可以看下方的注釋 // CANNY_POP(d) 是出棧函數, d指向棧底指標 #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 suppression. // 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 一定屬於邊緣 // for內進行非極大值抑制 + 滯後閾值處理 for (int i = 0; i <= src.rows; i++) // i 表示第i行 {// i == 0 時,_norm 指向 mag_buf[1]// i > 0 時, _norm 指向 mag_buf[2]// +1 表示跳過每行的第一個元素,因為是後擴充的邊,不可能是邊緣int* _norm = mag_buf[(i > 0) + 1] + 1; if (i < src.rows) { short* _dx = dx.ptr<short>(i); // _dx指向dx矩陣的第i行 short* _dy = dy.ptr<short>(i); // _dy指向dy矩陣的第i行 if (!L2gradient) // 如果 L2gradient為false { for (int j = 0; j < src.cols*cn; j++) // 對第i行裡的每一個值都進行計算 _norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j])); // 用||+||計算 } else { for (int j = 0; j < src.cols*cn; j++)//用平方計算,當 L2gradient為 true時,高低閾值都被平方了,所以此處_norm[j]無需開平方 _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j]; // } if (cn > 1) // 如果不是單通道(由於輸入映像必須是單通道,所以個人覺得這個if不成立) { 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 } // 當i == src.rows (最後一行)時,申請空間並且每個空間的值初始化為0, 儲存在mag_buf[2]中 else memset(_norm-1, 0, /* cn* */mapstep*sizeof(int)); // at the very beginning we do not have a complete ring // buffer of 3 magnitude rows for non-maxima suppression if (i == 0) continue; uchar* _map = map + mapstep*i + 1; // _map 指向第 i+1 行,+1表示跳過該行第一個元素 _map[-1] = _map[src.cols] = 1; // 第一列和最後一列不是邊緣,所以設定為1 int* _mag = mag_buf[1] + 1; // take the central row 中間那一行 ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1]; ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1]; const short* _x = dx.ptr<short>(i-1); const short* _y = dy.ptr<short>(i-1);// 如果棧的大小不夠,則重新為棧分配記憶體(相當於擴大容量) if ((stack_top - stack_bottom) + src.cols > maxsize) { 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; //前一個像素點 0:非邊緣點 ;1:邊緣點 for (int j = 0; j < src.cols; j++) // 第 j 列 { #define CANNY_SHIFT 15 // tan22.5 const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5); int m = _mag[j]; if (m > low) // 如果大於低閾值 { int xs = _x[j]; // dx中 第i-1行 第j列 int ys = _y[j]; // dy中 第i-1行 第j列 int x = std::abs(xs); int y = std::abs(ys) << CANNY_SHIFT; int tg22x = x * TG22; if (y < tg22x) //角度小於22.5 用區間表示:[0, 22.5) { // 與左右兩點的梯度幅值比較,如果比左右都大 //(此時當前點是左右鄰域內的極大值),則 goto __ocv_canny_push 執行入棧操作 if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push; } else //角度大於22.5 { int tg67x = tg22x + (x << (CANNY_SHIFT+1)); if (y > tg67x) //(67.5, 90) { //與上下兩點的梯度幅值比較,如果比上下都大 //(此時當前點是左右鄰域內的極大值),則 goto __ocv_canny_push 執行入棧操作 if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push; } else //[22.5, 67.5] { // ^ 按位異或 如果xs與ys異號 則取-1 否則取1 int s = (xs ^ ys) < 0 ? -1 : 1; //比較對角線鄰域 if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push; } } } //比當前的梯度幅值低閾值還低,直接被確定為非邊緣 prev_flag = 0; _map[j] = uchar(1); // 1 表示不屬於邊緣 continue;__ocv_canny_push: // 前一個點不是邊緣點 並且 當前點的幅值大於高閾值 並且 正上方的點不是邊緣點 if (!prev_flag && m > high && _map[j-mapstep] != 2) { //將當前點的地址入棧,入棧前,會將該點地址指向的值設定為2(查看上面的宏定義函數塊裡) CANNY_PUSH(_map + j); prev_flag = 1; } else _map[j] = 0; } // scroll the ring buffer // 交換指標指向的位置,向上覆蓋,把mag_[1]的內容覆蓋到mag_buf[0]上 // 把mag_[2]的內容覆蓋到mag_buf[1]上// 最後 讓mag_buf[2]指向_mag指向的那一行 _mag = mag_buf[0]; mag_buf[0] = mag_buf[1]; mag_buf[1] = mag_buf[2]; mag_buf[2] = _mag; } // now track the edges (hysteresis thresholding) // 通過上面的for迴圈,確定了各個鄰域內的極大值點為邊緣點(標記為2) // 現在,在這些邊緣點的8鄰域內(上下左右+4個對角),將可能的邊緣點(標記為0)確定為邊緣 while (stack_top > stack_bottom) { uchar* m; if ((stack_top - stack_bottom) + 8 > maxsize) { 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); // 出棧 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); }}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);}/* End of file. */
OpenCV Canny 源碼注釋與分析