OpenCV】SIFT原理与源码分析:方向赋值 四 【OpenCV】SIFT原理与源码分析:关键点描述 五 【OpenCV】特征检测器 FeatureDetector 六 计算机视觉】SIFT中LoG和DoG比较

SIFT简介

整理一下方便阅读,作者写的东西摘自论文,在此感谢xiaowei等的贡献

  1. DoG尺度空间构造(Scale-space extrema detectionhttp://blog.csdn.net/xiaowei_cqu/article/details/8067881
  2. 关键点搜索与定位(Keypoint localization)http://blog.csdn.net/xiaowei_cqu/article/details/8087239
  3. 方向赋值(Orientation assignment)http://blog.csdn.net/xiaowei_cqu/article/details/8096072
  4. 关键点描述(Keypoint descriptor)http://blog.csdn.net/xiaowei_cqu/article/details/8113565
  5. OpenCV实现:特征检测器FeatureDetectorhttp://blog.csdn.net/xiaowei_cqu/article/details/8652096
  6. SIFT中LoG和DoG的比较http://blog.csdn.net/xiaowei_cqu/article/details/27692123

    DoG尺度空间构造



    为什么要讨论尺度空间?

    图像的尺度空间表达就是图像在所有尺度下的描述。


    尺度空间表达与金字塔多分辨率表达


    高斯模糊

    高斯核是唯一可以产生多尺度空间的核(《Scale-space theory: A basic tool for analysing structures at different scales》)。一个图像的尺度空间L(x,y,σ) ,定义为原始图像I(x,y)与一个可变尺度的2维高斯函数G(x,y,σ)卷积运算。 

    二维空间高斯函数:


    尺度空间:


    尺度是自然客观存在的,不是主观创造的。高斯卷积只是表现尺度空间的一种形式。

    二维空间高斯函数是等高线从中心成正太分布的同心圆:


    分布不为零的点组成卷积阵与原始图像做变换,即每个像素值是周围相邻像素值的高斯平均。一个5*5的高斯模版如下所示:


    高斯模版是圆对称的,且卷积的结果使原始像素值有最大的权重,距离中心越远的相邻像素值权重也越小。
    在实际应用中,在计算高斯函数的离散近似时,在大概距离之外的像素都可以看作不起作用,这些像素的计算也就可以忽略。所以,通常程序只计算(6σ+1)*(6σ+1)就可以保证相关像素影响。

    高斯模糊另一个很厉害的性质就是线性可分:使用二维矩阵变换的高斯模糊可以通过在水平和竖直方向各进行一维高斯矩阵变换相加得到。


    O(N^2*m*n)次乘法就缩减成了O(N*m*n)+O(N*m*n)次乘法。(N为高斯核大小,m,n为二维图像高和宽)

    其实高斯这一部分只需要简单了解就可以了,在OpenCV也只需要一句代码:

    我这里详写了一下是因为这块儿对分析算法效率比较有用,而且高斯模糊的算法真的很漂亮~

    金字塔多分辨率

    金字塔是早期图像多尺度的表示形式。图像金字塔化一般包括两个步骤:使用低通滤波器平滑图像;对平滑图像进行降采样(通常是水平,竖直方向1/2),从而得到一系列尺寸缩小的图像。


    上图中(a)是对原始信号进行低通滤波,(b)是降采样得到的信号。

    而对于二维图像,一个传统的金字塔中,每一层图像由上一层分辨率的长、宽各一半,也就是四分之一的像素组成:


    多尺度和多分辨率

    尺度空间表达和金字塔多分辨率表达之间最大的不同是:


    DoG(Difference of Gaussian)


    高斯拉普拉斯LoG金字塔



    高斯差分DoG金字塔






    1. // 构建nOctaves组(每组nOctaves+3层)高斯金字塔  
    2. void SIFT::buildGaussianPyramid( const Mat& base, vector<Mat>& pyr, int nOctaves ) const  
    3. {  
    4.     vector<double> sig(nOctaveLayers + 3);  
    5.     pyr.resize(nOctaves*(nOctaveLayers + 3));  
    6.   
    7.     // precompute Gaussian sigmas using the following formula:  
    8.     //  \sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2、  
    9.     // 计算对图像做不同尺度高斯模糊的尺度因子  
    10.     sig[0] = sigma;  
    11.     double k = pow( 2., 1. / nOctaveLayers );  
    12.     forint i = 1; i < nOctaveLayers + 3; i++ )  
    13.     {  
    14.         double sig_prev = pow(k, (double)(i-1))*sigma;  
    15.         double sig_total = sig_prev*k;  
    16.         sig[i] = std::sqrt(sig_total*sig_total - sig_prev*sig_prev);  
    17.     }  
    18.   
    19.     forint o = 0; o < nOctaves; o++ )  
    20.     {  
    21.         // DoG金子塔需要nOctaveLayers+2层图像来检测nOctaves层尺度  
    22.         // 所以高斯金字塔需要nOctaveLayers+3层图像得到nOctaveLayers+2层DoG金字塔  
    23.         forint i = 0; i < nOctaveLayers + 3; i++ )  
    24.         {  
    25.             // dst为第o组(Octave)金字塔  
    26.             Mat& dst = pyr[o*(nOctaveLayers + 3) + i];  
    27.             // 第0组第0层为原始图像  
    28.             if( o == 0  &&  i == 0 )  
    29.                 dst = base;  
    30.               
    31.             // base of new octave is halved image from end of previous octave  
    32.             // 每一组第0副图像时上一组倒数第三幅图像隔点采样得到  
    33.             else if( i == 0 )  
    34.             {  
    35.                 const Mat& src = pyr[(o-1)*(nOctaveLayers + 3) + nOctaveLayers];  
    36.                 resize(src, dst, Size(src.cols/2, src.rows/2),  
    37.                        0, 0, INTER_NEAREST);  
    38.             }  
    39.             // 每一组第i副图像是由第i-1副图像进行sig[i]的高斯模糊得到  
    40.             // 也就是本组图像在sig[i]的尺度空间下的图像  
    41.             else  
    42.             {  
    43.                 const Mat& src = pyr[o*(nOctaveLayers + 3) + i-1];  
    44.                 GaussianBlur(src, dst, Size(), sig[i], sig[i]);  
    45.             }  
    46.         }  
    47.     }  
    48. }  







    这个比较简单,就是一个subtract()函数。
  7. 尺度空间理论

  8. 由前一步《DoG尺度空间构造》,我们得到了DoG高斯差分金字塔:


    如上图的金字塔,高斯尺度空间金字塔中每组有五层不同尺度图像,相邻两层相减得到四层DoG结果。关键点搜索就在这四层DoG图像上寻找局部极值点。

    DoG局部极值点

    寻找DoG极值点时,每一个像素点和它所有的相邻点比较,当其大于(或小于)它的图像域和尺度域的所有相邻点时,即为极值点。如下图所示,比较的范围是个3×3的立方体:中间的检测点和它同尺度的8个相邻点,以及和上下相邻尺度对应的9×2个点——共26个点比较,以确保在尺度空间和二维图像空间都检测到极值点。 


    在一组中,搜索从每组的第二层开始,以第二层为当前层,第一层和第三层分别作为立方体的的上下层;搜索完成后再以第三层为当前层做同样的搜索。所以每层的点搜索两次。通常我们将组Octaves索引以-1开始,则在比较时牺牲了-1组的第0层和第N组的最高层


    高斯金字塔,DoG图像及极值计算的相互关系如上图所示。


    二   关键点精确定位

    以上极值点的搜索是在离散空间进行搜索的,由下图可以看到,在离散空间找到的极值点不一定是真正意义上的极值点。可以通过对尺度空间DoG函数进行曲线拟合寻找极值点来减小这种误差。

    利用DoG函数在尺度空间的Taylor展开式:

    则极值点为:

    程序中还除去了极值小于0.04的点。如下所示:
    [cpp]  view plain  copy
    1. // Detects features at extrema in DoG scale space.  Bad features are discarded  
    2. // based on contrast and ratio of principal curvatures.  
    3. // 在DoG尺度空间寻特征点(极值点)  
    4. void SIFT::findScaleSpaceExtrema( const vector<Mat>& gauss_pyr, const vector<Mat>& dog_pyr,  
    5.                                   vector<KeyPoint>& keypoints ) const  
    6. {  
    7.     int nOctaves = (int)gauss_pyr.size()/(nOctaveLayers + 3);  
    8.       
    9.     // The contrast threshold used to filter out weak features in semi-uniform  
    10.     // (low-contrast) regions. The larger the threshold, the less features are produced by the detector.  
    11.     // 过滤掉弱特征的阈值 contrastThreshold默认为0.04  
    12.     int threshold = cvFloor(0.5 * contrastThreshold / nOctaveLayers * 255 * SIFT_FIXPT_SCALE);  
    13.     const int n = SIFT_ORI_HIST_BINS; //36  
    14.     float hist[n];  
    15.     KeyPoint kpt;  
    16.   
    17.     keypoints.clear();  
    18.   
    19.     forint o = 0; o < nOctaves; o++ )  
    20.         forint i = 1; i <= nOctaveLayers; i++ )  
    21.         {  
    22.             int idx = o*(nOctaveLayers+2)+i;  
    23.             const Mat& img = dog_pyr[idx];  
    24.             const Mat& prev = dog_pyr[idx-1];  
    25.             const Mat& next = dog_pyr[idx+1];  
    26.             int step = (int)img.step1();  
    27.             int rows = img.rows, cols = img.cols;  
    28.   
    29.             forint r = SIFT_IMG_BORDER; r < rows-SIFT_IMG_BORDER; r++)  
    30.             {  
    31.                 const short* currptr = img.ptr<short>(r);  
    32.                 const short* prevptr = prev.ptr<short>(r);  
    33.                 const short* nextptr = next.ptr<short>(r);  
    34.   
    35.                 forint c = SIFT_IMG_BORDER; c < cols-SIFT_IMG_BORDER; c++)  
    36.                 {  
    37.                     int val = currptr[c];  
    38.   
    39.                     // find local extrema with pixel accuracy  
    40.                     // 寻找局部极值点,DoG中每个点与其所在的立方体周围的26个点比较  
    41.                     // if (val比所有都大 或者 val比所有都小)  
    42.                     if( std::abs(val) > threshold &&  
    43.                        ((val > 0 && val >= currptr[c-1] && val >= currptr[c+1] &&  
    44.                          val >= currptr[c-step-1] && val >= currptr[c-step] &&   
    45.                          val >= currptr[c-step+1] && val >= currptr[c+step-1] &&   
    46.                          val >= currptr[c+step] && val >= currptr[c+step+1] &&  
    47.                          val >= nextptr[c] && val >= nextptr[c-1] &&   
    48.                          val >= nextptr[c+1] && val >= nextptr[c-step-1] &&   
    49.                          val >= nextptr[c-step] && val >= nextptr[c-step+1] &&   
    50.                          val >= nextptr[c+step-1] && val >= nextptr[c+step] &&   
    51.                          val >= nextptr[c+step+1] && val >= prevptr[c] &&   
    52.                          val >= prevptr[c-1] && val >= prevptr[c+1] &&  
    53.                          val >= prevptr[c-step-1] && val >= prevptr[c-step] &&   
    54.                          val >= prevptr[c-step+1] && val >= prevptr[c+step-1] &&   
    55.                          val >= prevptr[c+step] && val >= prevptr[c+step+1]) ||  
    56.                         (val < 0 && val <= currptr[c-1] && val <= currptr[c+1] &&  
    57.                          val <= currptr[c-step-1] && val <= currptr[c-step] &&   
    58.                          val <= currptr[c-step+1] && val <= currptr[c+step-1] &&   
    59.                          val <= currptr[c+step] && val <= currptr[c+step+1] &&  
    60.                          val <= nextptr[c] && val <= nextptr[c-1] &&   
    61.                          val <= nextptr[c+1] && val <= nextptr[c-step-1] &&   
    62.                          val <= nextptr[c-step] && val <= nextptr[c-step+1] &&   
    63.                          val <= nextptr[c+step-1] && val <= nextptr[c+step] &&   
    64.                          val <= nextptr[c+step+1] && val <= prevptr[c] &&   
    65.                          val <= prevptr[c-1] && val <= prevptr[c+1] &&  
    66.                          val <= prevptr[c-step-1] && val <= prevptr[c-step] &&   
    67.                          val <= prevptr[c-step+1] && val <= prevptr[c+step-1] &&   
    68.                          val <= prevptr[c+step] && val <= prevptr[c+step+1])))  
    69.                     {  
    70.                         int r1 = r, c1 = c, layer = i;  
    71.                           
    72.                         // 关键点精确定位  
    73.                         if( !adjustLocalExtrema(dog_pyr, kpt, o, layer, r1, c1,  
    74.                                                 nOctaveLayers, (float)contrastThreshold,  
    75.                                                 (float)edgeThreshold, (float)sigma) )  
    76.                             continue;  
    77.                           
    78.                         float scl_octv = kpt.size*0.5f/(1 << o);  
    79.                         // 计算梯度直方图  
    80.                         float omax = calcOrientationHist(  
    81.                             gauss_pyr[o*(nOctaveLayers+3) + layer],  
    82.                             Point(c1, r1),  
    83.                             cvRound(SIFT_ORI_RADIUS * scl_octv),  
    84.                             SIFT_ORI_SIG_FCTR * scl_octv,  
    85.                             hist, n);  
    86.                         float mag_thr = (float)(omax * SIFT_ORI_PEAK_RATIO);  
    87.                         forint j = 0; j < n; j++ )  
    88.                         {  
    89.                             int l = j > 0 ? j - 1 : n - 1;  
    90.                             int r2 = j < n-1 ? j + 1 : 0;  
    91.   
    92.                             if( hist[j] > hist[l]  &&  hist[j] > hist[r2]  &&  hist[j] >= mag_thr )  
    93.                             {  
    94.                                 float bin = j + 0.5f * (hist[l]-hist[r2]) /   
    95.                                 (hist[l] - 2*hist[j] + hist[r2]);  
    96.                                 bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;  
    97.                                 kpt.angle = (float)((360.f/n) * bin);  
    98.                                 keypoints.push_back(kpt);  
    99.                             }  
    100.                         }  
    101.                     }  
    102.                 }  
    103.             }  
    104.         }  
    105. }  


    删除边缘效应

    除了DoG响应较低的点,还有一些响应较强的点也不是稳定的特征点。DoG对图像中的边缘有较强的响应值,所以落在图像边缘的点也不是稳定的特征点。
    一个平坦的DoG响应峰值在横跨边缘的地方有较大的主曲率,而在垂直边缘的地方有较小的主曲率。主曲率可以通过2×2的Hessian矩阵H求出:

    D值可以通过求临近点差分得到。H的特征值与D的主曲率成正比,具体可参见Harris角点检测算法。
    为了避免求具体的值,我们可以通过H将特征值的比例表示出来。令 为最大特征值, 为最小特征值,那么:


    Tr(H)表示矩阵H的迹,Det(H)表示H的行列式。
    表示最大特征值与最小特征值的比值,则有:

    上式与两个特征值的比例有关。随着主曲率比值的增加, 也会增加。我们只需要去掉比率大于一定值的特征点。Lowe论文中去掉r=10的点。
    [cpp]  view plain  copy
    1. // Interpolates a scale-space extremum's location and scale to subpixel  
    2. // accuracy to form an image feature.  Rejects features with low contrast.  
    3. // Based on Section 4 of Lowe's paper.  
    4. // 特征点精确定位  
    5. static bool adjustLocalExtrema( const vector<Mat>& dog_pyr, KeyPoint& kpt, int octv,  
    6.                                 int& layer, int& r, int& c, int nOctaveLayers,  
    7.                                 float contrastThreshold, float edgeThreshold, float sigma )  
    8. {  
    9.     const float img_scale = 1.f/(255*SIFT_FIXPT_SCALE);  
    10.     const float deriv_scale = img_scale*0.5f;  
    11.     const float second_deriv_scale = img_scale;  
    12.     const float cross_deriv_scale = img_scale*0.25f;  
    13.   
    14.     float xi=0, xr=0, xc=0, contr;  
    15.     int i = 0;  
    16.   
    17.     //三维子像元插值  
    18.     for( ; i < SIFT_MAX_INTERP_STEPS; i++ )  
    19.     {  
    20.         int idx = octv*(nOctaveLayers+2) + layer;  
    21.         const Mat& img = dog_pyr[idx];  
    22.         const Mat& prev = dog_pyr[idx-1];  
    23.         const Mat& next = dog_pyr[idx+1];  
    24.   
    25.         Vec3f dD((img.at<short>(r, c+1) - img.at<short>(r, c-1))*deriv_scale,  
    26.                  (img.at<short>(r+1, c) - img.at<short>(r-1, c))*deriv_scale,  
    27.                  (next.at<short>(r, c) - prev.at<short>(r, c))*deriv_scale);  
    28.   
    29.         float v2 = (float)img.at<short>(r, c)*2;  
    30.         float dxx = (img.at<short>(r, c+1) +   
    31.                 img.at<short>(r, c-1) - v2)*second_deriv_scale;  
    32.         float dyy = (img.at<short>(r+1, c) +   
    33.                 img.at<short>(r-1, c) - v2)*second_deriv_scale;  
    34.         float dss = (next.at<short>(r, c) +   
    35.                 prev.at<short>(r, c) - v2)*second_deriv_scale;  
    36.         float dxy = (img.at<short>(r+1, c+1) -   
    37.                 img.at<short>(r+1, c-1) - img.at<short>(r-1, c+1) +   
    38.                 img.at<short>(r-1, c-1))*cross_deriv_scale;  
    39.         float dxs = (next.at<short>(r, c+1) -   
    40.                 next.at<short>(r, c-1) - prev.at<short>(r, c+1) +   
    41.                 prev.at<short>(r, c-1))*cross_deriv_scale;  
    42.         float dys = (next.at<short>(r+1, c) -   
    43.                 next.at<short>(r-1, c) - prev.at<short>(r+1, c) +   
    44.                 prev.at<short>(r-1, c))*cross_deriv_scale;  
    45.   
    46.         Matx33f H(dxx, dxy, dxs,  
    47.                   dxy, dyy, dys,  
    48.                   dxs, dys, dss);  
    49.   
    50.         Vec3f X = H.solve(dD, DECOMP_LU);  
    51.   
    52.         xi = -X[2];  
    53.         xr = -X[1];  
    54.         xc = -X[0];  
    55.   
    56.         if( std::abs( xi ) < 0.5f  &&  std::abs( xr ) < 0.5f  &&  std::abs( xc ) < 0.5f )  
    57.             break;  
    58.   
    59.         //将找到的极值点对应成像素(整数)  
    60.         c += cvRound( xc );  
    61.         r += cvRound( xr );  
    62.         layer += cvRound( xi );  
    63.   
    64.         if( layer < 1 || layer > nOctaveLayers ||  
    65.            c < SIFT_IMG_BORDER || c >= img.cols - SIFT_IMG_BORDER  ||  
    66.            r < SIFT_IMG_BORDER || r >= img.rows - SIFT_IMG_BORDER )  
    67.             return false;  
    68.     }  
    69.   
    70.     /* ensure convergence of interpolation */  
    71.     // SIFT_MAX_INTERP_STEPS:插值最大步数,避免插值不收敛,程序中默认为5  
    72.     if( i >= SIFT_MAX_INTERP_STEPS )  
    73.         return false;  
    74.   
    75.     {  
    76.         int idx = octv*(nOctaveLayers+2) + layer;  
    77.         const Mat& img = dog_pyr[idx];  
    78.         const Mat& prev = dog_pyr[idx-1];  
    79.         const Mat& next = dog_pyr[idx+1];  
    80.         Matx31f dD((img.at<short>(r, c+1) - img.at<short>(r, c-1))*deriv_scale,  
    81.                    (img.at<short>(r+1, c) - img.at<short>(r-1, c))*deriv_scale,  
    82.                    (next.at<short>(r, c) - prev.at<short>(r, c))*deriv_scale);  
    83.         float t = dD.dot(Matx31f(xc, xr, xi));  
    84.   
    85.         contr = img.at<short>(r, c)*img_scale + t * 0.5f;  
    86.         if( std::abs( contr ) * nOctaveLayers < contrastThreshold )  
    87.             return false;  
    88.   
    89.         /* principal curvatures are computed using the trace and det of Hessian */  
    90.        //利用Hessian矩阵的迹和行列式计算主曲率的比值  
    91.        float v2 = img.at<short>(r, c)*2.f;  
    92.         float dxx = (img.at<short>(r, c+1) +   
    93.                 img.at<short>(r, c-1) - v2)*second_deriv_scale;  
    94.         float dyy = (img.at<short>(r+1, c) +   
    95.                 img.at<short>(r-1, c) - v2)*second_deriv_scale;  
    96.         float dxy = (img.at<short>(r+1, c+1) -   
    97.                 img.at<short>(r+1, c-1) - img.at<short>(r-1, c+1) +   
    98.                 img.at<short>(r-1, c-1)) * cross_deriv_scale;  
    99.         float tr = dxx + dyy;  
    100.         float det = dxx * dyy - dxy * dxy;  
    101.   
    102.         //这里edgeThreshold可以在调用SIFT()时输入;  
    103.         //其实代码中定义了 static const float SIFT_CURV_THR = 10.f 可以直接使用  
    104.         if( det <= 0 || tr*tr*edgeThreshold >= (edgeThreshold + 1)*(edgeThreshold + 1)*det )  
    105.             return false;  
    106.     }  
    107.   
    108.     kpt.pt.x = (c + xc) * (1 << octv);  
    109.     kpt.pt.y = (r + xr) * (1 << octv);  
    110.     kpt.octave = octv + (layer << 8) + (cvRound((xi + 0.5)*255) << 16);  
    111.     kpt.size = sigma*powf(2.f, (layer + xi) / nOctaveLayers)*(1 << octv)*2;  
    112.   
    113.     return true;  
    114. }  

    三  方向赋值

    OpenCV】SIFT原理与源码分析:方向赋值


    由前一篇《 关键点搜索与定位》,我们已经找到了关键点。为了实现图像旋转不变性,需要根据检测到的关键点局部图像结构为特征点方向赋值。也就是在 findScaleSpaceExtrema()函数里看到的alcOrientationHist()语句:
    [cpp]  view plain  copy
    1. // 计算梯度直方图  
    2. float omax = calcOrientationHist(gauss_pyr[o*(nOctaveLayers+3) + layer],  
    3.                                                 Point(c1, r1),  
    4.                                                 cvRound(SIFT_ORI_RADIUS * scl_octv),  
    5.                                                 SIFT_ORI_SIG_FCTR * scl_octv,  
    6.                                                 hist, n);  

    我们使用图像的梯度直方图法求关键点局部结构的稳定方向。

    梯度方向和幅值

    在前文中,精确定位关键点后也找到改特征点的尺度值σ,根据这一尺度值,得到最接近这一尺度值的高斯图像:


    使用有限差分,计算以关键点为中心,以3×1.5σ为半径的区域内图像梯度的幅角和幅值,公式如下:

    梯度直方图

    在完成关键点邻域内高斯图像梯度计算后,使用直方图统计邻域内像素对应的梯度方向和幅值。

    有关直方图的基础知识可以参考《数字图像直方图》,可以看做是离散点的概率表示形式。此处方向直方图的核心是统计以关键点为原点,一定区域内的图像像素点对关键点方向生成所作的贡献

    梯度方向直方图的横轴是梯度方向角,纵轴是剃度方向角对应的梯度幅值累加值。梯度方向直方图将0°~360°的范围分为36个柱,每10°为一个柱。下图是从高斯图像上求取梯度,再由梯度得到梯度方向直方图的例图。

    在计算直方图时,每个加入直方图的采样点都使用圆形高斯函数函数进行了加权处理,也就是进行高斯平滑。这主要是因为SIFT算法只考虑了尺度和旋转不变形,没有考虑仿射不变性。通过高斯平滑,可以使关键点附近的梯度幅值有较大权重,从而部分弥补没考虑仿射不变形产生的特征点不稳定。

    通常离散的梯度直方图要进行插值拟合处理,以求取更精确的方向角度值。(这和《关键点搜索与定位》中插值的思路是一样的)。

    关键点方向

    直方图峰值代表该关键点处邻域内图像梯度的主方向,也就是该关键点的主方向。在梯度方向直方图中,当存在另一个相当于主峰值    80%能量的峰值时,则将这个方向认为是该关键点的辅方向。所以一个关键点可能检测得到多个方向,这可以增强匹配的鲁棒性。Lowe的论文指出大概有15%关键点具有多方向,但这些点对匹配的稳定性至为关键。

    获得图像关键点主方向后,每个关键点有三个信息(x,y,σ,θ):位置、尺度、方向。由此我们可以确定一个SIFT特征区域。通常使用一个带箭头的圆或直接使用箭头表示SIFT区域的三个值:中心表示特征点位置,半径表示关键点尺度(r=2.5σ),箭头表示主方向。具有多个方向的关键点可以复制成多份,然后将方向值分别赋给复制后的关键点。如下图:


    源码

    [cpp]  view plain  copy
    1. // Computes a gradient orientation histogram at a specified pixel  
    2. // 计算特定点的梯度方向直方图  
    3. static float calcOrientationHist( const Mat& img, Point pt, int radius,  
    4.                                   float sigma, float* hist, int n )  
    5. {  
    6.     //len:2r+1也就是以r为半径的圆(正方形)像素个数  
    7.     int i, j, k, len = (radius*2+1)*(radius*2+1);  
    8.   
    9.     float expf_scale = -1.f/(2.f * sigma * sigma);  
    10.     AutoBuffer<float> buf(len*4 + n+4);  
    11.     float *X = buf, *Y = X + len, *Mag = X, *Ori = Y + len, *W = Ori + len;  
    12.     float* temphist = W + len + 2;  
    13.   
    14.     for( i = 0; i < n; i++ )  
    15.         temphist[i] = 0.f;  
    16.   
    17.     // 图像梯度直方图统计的像素范围  
    18.     for( i = -radius, k = 0; i <= radius; i++ )  
    19.     {  
    20.         int y = pt.y + i;  
    21.         if( y <= 0 || y >= img.rows - 1 )  
    22.             continue;  
    23.         for( j = -radius; j <= radius; j++ )  
    24.         {  
    25.             int x = pt.x + j;  
    26.             if( x <= 0 || x >= img.cols - 1 )  
    27.                 continue;  
    28.   
    29.             float dx = (float)(img.at<short>(y, x+1) - img.at<short>(y, x-1));  
    30.             float dy = (float)(img.at<short>(y-1, x) - img.at<short>(y+1, x));  
    31.   
    32.             X[k] = dx; Y[k] = dy; W[k] = (i*i + j*j)*expf_scale;  
    33.             k++;  
    34.         }  
    35.     }  
    36.   
    37.     len = k;  
    38.   
    39.     // compute gradient values, orientations and the weights over the pixel neighborhood  
    40.     exp(W, W, len);   
    41.     fastAtan2(Y, X, Ori, len, true);   
    42.     magnitude(X, Y, Mag, len);   
    43.       
    44.     // 计算直方图的每个bin  
    45.     for( k = 0; k < len; k++ )  
    46.     {  
    47.         int bin = cvRound((n/360.f)*Ori[k]);  
    48.         if( bin >= n )  
    49.             bin -= n;  
    50.         if( bin < 0 )  
    51.             bin += n;  
    52.         temphist[bin] += W[k]*Mag[k];  
    53.     }  
    54.   
    55.     // smooth the histogram  
    56.     // 高斯平滑  
    57.     temphist[-1] = temphist[n-1];  
    58.     temphist[-2] = temphist[n-2];  
    59.     temphist[n] = temphist[0];  
    60.     temphist[n+1] = temphist[1];  
    61.     for( i = 0; i < n; i++ )  
    62.     {  
    63.         hist[i] = (temphist[i-2] + temphist[i+2])*(1.f/16.f) +  
    64.             (temphist[i-1] + temphist[i+1])*(4.f/16.f) +  
    65.             temphist[i]*(6.f/16.f);  
    66.     }  
    67.       
    68.     // 得到主方向  
    69.     float maxval = hist[0];  
    70.     for( i = 1; i < n; i++ )  
    71.         maxval = std::max(maxval, hist[i]);  
    72.   
    73.     return maxval;  
    74. }  

    四 【OpenCV】SIFT原理与源码分析:关键点描述

    原创  2012年10月26日 10:35:12
    • 22996

    《SIFT原理与源码分析》系列文章索引:http://blog.csdn.net/xiaowei_cqu/article/details/8069548


    由前一篇《 方向赋值》,为找到的关键点即SIFT特征点赋了值,包含位置、尺度和方向的信息。接下来的步骤是关键点描述,即用用一组向量将这个关键点描述出来,这个描述子不但包括关键点,也包括关键点周围对其有贡献的像素点。用来作为 目标匹配的依据(所以描述子应该有较高的独特性,以保证匹配率),也可使关键点具有更多的不变特性,如光照变化、3D视点变化等。

    SIFT描述子h(x,y,θ)是对关键点附近邻域内高斯图像梯度统计的结果,是一个三维矩阵,但通常用一个矢量来表示。矢量通过对三维矩阵按一定规律排列得到。

    描述子采样区域

    特征描述子与关键点所在尺度有关,因此对梯度的求取应在特征点对应的高斯图像上进行。将关键点附近划分成d×d个子区域,每个子区域尺寸为mσ个像元(d=4,m=3,σ为尺特征点的尺度值)。考虑到实际计算时需要双线性插值,故计算的图像区域为mσ(d+1),再考虑旋转,则实际计算的图像区域为 ,如下图所示:

    源码

    [cpp]  view plain  copy
    1.    Point pt(cvRound(ptf.x), cvRound(ptf.y));  
    2. //计算余弦,正弦,CV_PI/180:将角度值转化为幅度值  
    3.    float cos_t = cosf(ori*(float)(CV_PI/180));  
    4.    float sin_t = sinf(ori*(float)(CV_PI/180));  
    5.    float bins_per_rad = n / 360.f;  
    6.    float exp_scale = -1.f/(d * d * 0.5f); //d:SIFT_DESCR_WIDTH 4      
    7.    float hist_width = SIFT_DESCR_SCL_FCTR * scl;  // SIFT_DESCR_SCL_FCTR: 3   
    8.                                                // scl: size*0.5f  
    9. // 计算图像区域半径mσ(d+1)/2*sqrt(2)  
    10. // 1.4142135623730951f 为根号2  
    11.    int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);  
    12.    cos_t /= hist_width;  
    13.    sin_t /= hist_width;  



    区域坐标轴旋转

    为了保证特征矢量具有旋转不变性,要以特征点为中心,在附近邻域内旋转θ角,即旋转为特征点的方向。

    旋转后区域内采样点新的坐标为:

    源码

    [cpp]  view plain  copy
    1. //计算采样区域点坐标旋转  
    2.     for( i = -radius, k = 0; i <= radius; i++ )  
    3.         for( j = -radius; j <= radius; j++ )  
    4.         {  
    5.             /* 
    6.              Calculate sample's histogram array coords rotated relative to ori. 
    7.              Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e. 
    8.              r_rot = 1.5) have full weight placed in row 1 after interpolation. 
    9.              */  
    10.             float c_rot = j * cos_t - i * sin_t;  
    11.             float r_rot = j * sin_t + i * cos_t;  
    12.             float rbin = r_rot + d/2 - 0.5f;  
    13.             float cbin = c_rot + d/2 - 0.5f;  
    14.             int r = pt.y + i, c = pt.x + j;  
    15.   
    16.             if( rbin > -1 && rbin < d && cbin > -1 && cbin < d &&  
    17.                r > 0 && r < rows - 1 && c > 0 && c < cols - 1 )  
    18.             {  
    19.                 float dx = (float)(img.at<short>(r, c+1) - img.at<short>(r, c-1));  
    20.                 float dy = (float)(img.at<short>(r-1, c) - img.at<short>(r+1, c));  
    21.                 X[k] = dx; Y[k] = dy; RBin[k] = rbin; CBin[k] = cbin;  
    22.                 W[k] = (c_rot * c_rot + r_rot * r_rot)*exp_scale;  
    23.                 k++;  
    24.             }  
    25.         }  


    计算采样区域梯度直方图

    将旋转后区域划分为d×d个子区域(每个区域间隔为mσ像元),在子区域内计算8个方向的梯度直方图,绘制每个方向梯度方向的累加值,形成一个种子点。
    与求主方向不同的是,此时,每个子区域梯度方向直方图将0°~360°划分为8个方向区间,每个区间为45°。即每个种子点有8个方向区间的梯度强度信息。由于存在d×d,即4×4个子区域,所以最终共有4×4×8=128个数据,形成128维SIFT特征矢量。

    对特征矢量需要加权处理,加权采用mσd/2的标准高斯函数。为了除去光照变化影响,还有一步归一化处理。

    源码

    [cpp]  view plain  copy
    1. //计算梯度直方图  
    2.     for( k = 0; k < len; k++ )  
    3.     {  
    4.         float rbin = RBin[k], cbin = CBin[k];  
    5.         float obin = (Ori[k] - ori)*bins_per_rad;  
    6.         float mag = Mag[k]*W[k];  
    7.   
    8.         int r0 = cvFloor( rbin );  
    9.         int c0 = cvFloor( cbin );  
    10.         int o0 = cvFloor( obin );  
    11.         rbin -= r0;  
    12.         cbin -= c0;  
    13.         obin -= o0;  
    14.   
    15.         //n为SIFT_DESCR_HIST_BINS:8,即将360°分为8个区间  
    16.         if( o0 < 0 )  
    17.             o0 += n;  
    18.         if( o0 >= n )  
    19.             o0 -= n;  
    20.           
    21.   
    22.         // histogram update using tri-linear interpolation  
    23.         // 双线性插值  
    24.         float v_r1 = mag*rbin, v_r0 = mag - v_r1;  
    25.         float v_rc11 = v_r1*cbin, v_rc10 = v_r1 - v_rc11;  
    26.         float v_rc01 = v_r0*cbin, v_rc00 = v_r0 - v_rc01;  
    27.         float v_rco111 = v_rc11*obin, v_rco110 = v_rc11 - v_rco111;  
    28.         float v_rco101 = v_rc10*obin, v_rco100 = v_rc10 - v_rco101;  
    29.         float v_rco011 = v_rc01*obin, v_rco010 = v_rc01 - v_rco011;  
    30.         float v_rco001 = v_rc00*obin, v_rco000 = v_rc00 - v_rco001;  
    31.   
    32.         int idx = ((r0+1)*(d+2) + c0+1)*(n+2) + o0;  
    33.         hist[idx] += v_rco000;  
    34.         hist[idx+1] += v_rco001;  
    35.         hist[idx+(n+2)] += v_rco010;  
    36.         hist[idx+(n+3)] += v_rco011;  
    37.         hist[idx+(d+2)*(n+2)] += v_rco100;  
    38.         hist[idx+(d+2)*(n+2)+1] += v_rco101;  
    39.         hist[idx+(d+3)*(n+2)] += v_rco110;  
    40.         hist[idx+(d+3)*(n+2)+1] += v_rco111;  
    41.     }  

    关键点描述源码

    [cpp]  view plain  copy
    1. // SIFT关键点特征描述  
    2. // SIFT描述子是关键点领域高斯图像提取统计结果的一种表示  
    3. static void calcSIFTDescriptor( const Mat& img, Point2f ptf, float ori, float scl,  
    4.                                int d, int n, float* dst )  
    5.                              
    6. {  
    7.     Point pt(cvRound(ptf.x), cvRound(ptf.y));  
    8.     //计算余弦,正弦,CV_PI/180:将角度值转化为幅度值  
    9.     float cos_t = cosf(ori*(float)(CV_PI/180));  
    10.     float sin_t = sinf(ori*(float)(CV_PI/180));  
    11.     float bins_per_rad = n / 360.f;  
    12.     float exp_scale = -1.f/(d * d * 0.5f); //d:SIFT_DESCR_WIDTH 4     
    13.     float hist_width = SIFT_DESCR_SCL_FCTR * scl;  // SIFT_DESCR_SCL_FCTR: 3   
    14.                                                    // scl: size*0.5f  
    15.     // 计算图像区域半径mσ(d+1)/2*sqrt(2)  
    16.     // 1.4142135623730951f 为根号2  
    17.     int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);  
    18.     cos_t /= hist_width;  
    19.     sin_t /= hist_width;  
    20.   
    21.     int i, j, k, len = (radius*2+1)*(radius*2+1), histlen = (d+2)*(d+2)*(n+2);  
    22.     int rows = img.rows, cols = img.cols;  
    23.   
    24.     AutoBuffer<float> buf(len*6 + histlen);  
    25.     float *X = buf, *Y = X + len, *Mag = Y, *Ori = Mag + len, *W = Ori + len;  
    26.     float *RBin = W + len, *CBin = RBin + len, *hist = CBin + len;  
    27.   
    28.     //初始化直方图  
    29.     for( i = 0; i < d+2; i++ )  
    30.     {  
    31.         for( j = 0; j < d+2; j++ )  
    32.             for( k = 0; k < n+2; k++ )  
    33.                 hist[(i*(d+2) + j)*(n+2) + k] = 0.;  
    34.     }  
    35.   
    36.     //计算采样区域点坐标旋转  
    37.     for( i = -radius, k = 0; i <= radius; i++ )  
    38.         for( j = -radius; j <= radius; j++ )  
    39.         {  
    40.             /* 
    41.              Calculate sample's histogram array coords rotated relative to ori. 
    42.              Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e. 
    43.              r_rot = 1.5) have full weight placed in row 1 after interpolation. 
    44.              */  
    45.             float c_rot = j * cos_t - i * sin_t;  
    46.             float r_rot = j * sin_t + i * cos_t;  
    47.             float rbin = r_rot + d/2 - 0.5f;  
    48.             float cbin = c_rot + d/2 - 0.5f;  
    49.             int r = pt.y + i, c = pt.x + j;  
    50.   
    51.             if( rbin > -1 && rbin < d && cbin > -1 && cbin < d &&  
    52.                r > 0 && r < rows - 1 && c > 0 && c < cols - 1 )  
    53.             {  
    54.                 float dx = (float)(img.at<short>(r, c+1) - img.at<short>(r, c-1));  
    55.                 float dy = (float)(img.at<short>(r-1, c) - img.at<short>(r+1, c));  
    56.                 X[k] = dx; Y[k] = dy; RBin[k] = rbin; CBin[k] = cbin;  
    57.                 W[k] = (c_rot * c_rot + r_rot * r_rot)*exp_scale;  
    58.                 k++;  
    59.             }  
    60.         }  
    61.   
    62.     len = k;  
    63.     fastAtan2(Y, X, Ori, len, true);  
    64.     magnitude(X, Y, Mag, len);  
    65.     exp(W, W, len);  
    66.   
    67.       
    68.     //计算梯度直方图  
    69.     for( k = 0; k < len; k++ )  
    70.     {  
    71.         float rbin = RBin[k], cbin = CBin[k];  
    72.         float obin = (Ori[k] - ori)*bins_per_rad;  
    73.         float mag = Mag[k]*W[k];  
    74.   
    75.         int r0 = cvFloor( rbin );  
    76.         int c0 = cvFloor( cbin );  
    77.         int o0 = cvFloor( obin );  
    78.         rbin -= r0;  
    79.         cbin -= c0;  
    80.         obin -= o0;  
    81.   
    82.         //n为SIFT_DESCR_HIST_BINS:8,即将360°分为8个区间  
    83.         if( o0 < 0 )  
    84.             o0 += n;  
    85.         if( o0 >= n )  
    86.             o0 -= n;  
    87.           
    88.   
    89.         // histogram update using tri-linear interpolation  
    90.         // 双线性插值  
    91.         float v_r1 = mag*rbin, v_r0 = mag - v_r1;  
    92.         float v_rc11 = v_r1*cbin, v_rc10 = v_r1 - v_rc11;  
    93.         float v_rc01 = v_r0*cbin, v_rc00 = v_r0 - v_rc01;  
    94.         float v_rco111 = v_rc11*obin, v_rco110 = v_rc11 - v_rco111;  
    95.         float v_rco101 = v_rc10*obin, v_rco100 = v_rc10 - v_rco101;  
    96.         float v_rco011 = v_rc01*obin, v_rco010 = v_rc01 - v_rco011;  
    97.         float v_rco001 = v_rc00*obin, v_rco000 = v_rc00 - v_rco001;  
    98.   
    99.         int idx = ((r0+1)*(d+2) + c0+1)*(n+2) + o0;  
    100.         hist[idx] += v_rco000;  
    101.         hist[idx+1] += v_rco001;  
    102.         hist[idx+(n+2)] += v_rco010;  
    103.         hist[idx+(n+3)] += v_rco011;  
    104.         hist[idx+(d+2)*(n+2)] += v_rco100;  
    105.         hist[idx+(d+2)*(n+2)+1] += v_rco101;  
    106.         hist[idx+(d+3)*(n+2)] += v_rco110;  
    107.         hist[idx+(d+3)*(n+2)+1] += v_rco111;  
    108.     }  
    109.   
    110.     // finalize histogram, since the orientation histograms are circular  
    111.     // 最后确定直方图,目标方向直方图是圆的  
    112.     for( i = 0; i < d; i++ )  
    113.         for( j = 0; j < d; j++ )  
    114.         {  
    115.             int idx = ((i+1)*(d+2) + (j+1))*(n+2);  
    116.             hist[idx] += hist[idx+n];  
    117.             hist[idx+1] += hist[idx+n+1];  
    118.             for( k = 0; k < n; k++ )  
    119.                 dst[(i*d + j)*n + k] = hist[idx+k];  
    120.         }  
    121.     // copy histogram to the descriptor,  
    122.     // apply hysteresis thresholding  
    123.     // and scale the result, so that it can be easily converted  
    124.     // to byte array  
    125.     float nrm2 = 0;  
    126.     len = d*d*n;  
    127.     for( k = 0; k < len; k++ )  
    128.         nrm2 += dst[k]*dst[k];  
    129.     float thr = std::sqrt(nrm2)*SIFT_DESCR_MAG_THR;  
    130.     for( i = 0, nrm2 = 0; i < k; i++ )  
    131.     {  
    132.         float val = std::min(dst[i], thr);  
    133.         dst[i] = val;  
    134.         nrm2 += val*val;  
    135.     }  
    136.     nrm2 = SIFT_INT_DESCR_FCTR/std::max(std::sqrt(nrm2), FLT_EPSILON);  
    137.     for( k = 0; k < len; k++ )  
    138.     {  
    139.         dst[k] = saturate_cast<uchar>(dst[k]*nrm2);  
    140.     }  
    141. }  

    五 【OpenCV】特征检测器 FeatureDetector

    原创  2013年03月08日 23:14:02
    • 39933

    OpenCV提供FeatureDetector实现特征检测及匹配

    [cpp]  view plain  copy
    1. class CV_EXPORTS FeatureDetector  
    2. {  
    3. public:  
    4.     virtual ~FeatureDetector();  
    5.     void detect( const Mat& image, vector<KeyPoint>& keypoints,  
    6.         const Mat& mask=Mat() ) const;  
    7.     void detect( const vector<Mat>& images,  
    8.         vector<vector<KeyPoint> >& keypoints,  
    9.         const vector<Mat>& masks=vector<Mat>() ) const;  
    10.     virtual void read(const FileNode&);  
    11.     virtual void write(FileStorage&) const;  
    12.     static Ptr<FeatureDetector> create( const string& detectorType );  
    13. protected:  
    14.     ...  
    15. };  

    FeatureDetetor是虚类,通过定义FeatureDetector的对象可以使用多种特征检测方法。通过create()函数调用:

    [cpp]  view plain  copy
    1. Ptr<FeatureDetector> FeatureDetector::create(const string& detectorType);  

    OpenCV 2.4.3提供了10种特征检测方法:

    • "FAST" – FastFeatureDetector
    • "STAR" – StarFeatureDetector
    • "SIFT" – SIFT (nonfree module)
    • "SURF" – SURF (nonfree module)
    • "ORB" – ORB
    • "MSER" – MSER
    • "GFTT" – GoodFeaturesToTrackDetector
    • "HARRIS" – GoodFeaturesToTrackDetector with Harris detector enabled
    • "Dense" – DenseFeatureDetector
    • "SimpleBlob" – SimpleBlobDetector
    图片中的特征大体可分为三种:点特征、线特征、块特征。
    FAST算法是Rosten提出的一种快速提取的点特征 [1],Harris与GFTT也是点特征,更具体来说是角点特征( 参考这里)。
    SimpleBlob是简单块特征,可以通过设置 SimpleBlobDetector的参数决定提取图像块的主要性质,提供5种:
    颜色  By color、面积  By area、圆形度  By circularity、最大inertia (不知道怎么翻译)与最小inertia的比例  By ratio of the minimum inertia to maximum inertia、以及凸性  By convexity.
    最常用的当属SIFT,尺度不变特征匹配算法( 参考这里);以及后来发展起来的SURF,都可以看做较为复杂的块特征。这两个算法在OpenCV nonfree的模块里面,需要在附件引用项中添加opencv_nonfree243.lib,同时在代码中加入:
    [cpp]  view plain  copy
    1. initModule_nonfree();  
    至于其他几种算法,我就不太了解了 ^_^

    一个简单的使用演示:
    [cpp]  view plain  copy
    1. int main()  
    2. {  
    3.   
    4.     initModule_nonfree();//if use SIFT or SURF  
    5.     Ptr<FeatureDetector> detector = FeatureDetector::create( "SIFT" );  
    6.     Ptr<DescriptorExtractor> descriptor_extractor = DescriptorExtractor::create( "SIFT" );  
    7.     Ptr<DescriptorMatcher> descriptor_matcher = DescriptorMatcher::create( "BruteForce" );  
    8.     if( detector.empty() || descriptor_extractor.empty() )  
    9.         throw runtime_error("fail to create detector!");  
    10.   
    11.     Mat img1 = imread("images\\box_in_scene.png");  
    12.     Mat img2 = imread("images\\box.png");  
    13.   
    14.     //detect keypoints;  
    15.     vector<KeyPoint> keypoints1,keypoints2;  
    16.     detector->detect( img1, keypoints1 );  
    17.     detector->detect( img2, keypoints2 );  
    18.     cout <<"img1:"<< keypoints1.size() << " points  img2:" <<keypoints2.size()   
    19.         << " points" << endl << ">" << endl;  
    20.   
    21.     //compute descriptors for keypoints;  
    22.     cout << "< Computing descriptors for keypoints from images..." << endl;  
    23.     Mat descriptors1,descriptors2;  
    24.     descriptor_extractor->compute( img1, keypoints1, descriptors1 );  
    25.     descriptor_extractor->compute( img2, keypoints2, descriptors2 );  
    26.   
    27.     cout<<endl<<"Descriptors Size: "<<descriptors2.size()<<" >"<<endl;  
    28.     cout<<endl<<"Descriptor's Column: "<<descriptors2.cols<<endl  
    29.         <<"Descriptor's Row: "<<descriptors2.rows<<endl;  
    30.     cout << ">" << endl;  
    31.   
    32.     //Draw And Match img1,img2 keypoints  
    33.     Mat img_keypoints1,img_keypoints2;  
    34.     drawKeypoints(img1,keypoints1,img_keypoints1,Scalar::all(-1),0);  
    35.     drawKeypoints(img2,keypoints2,img_keypoints2,Scalar::all(-1),0);  
    36.     imshow("Box_in_scene keyPoints",img_keypoints1);  
    37.     imshow("Box keyPoints",img_keypoints2);  
    38.   
    39.     descriptor_extractor->compute( img1, keypoints1, descriptors1 );    
    40.     vector<DMatch> matches;  
    41.     descriptor_matcher->match( descriptors1, descriptors2, matches );  
    42.   
    43.     Mat img_matches;  
    44.     drawMatches(img1,keypoints1,img2,keypoints2,matches,img_matches,Scalar::all(-1),CV_RGB(255,255,255),Mat(),4);  
    45.   
    46.     imshow("Mathc",img_matches);  
    47.     waitKey(10000);  
    48.     return 0;  
    49. }  

    特征检测结果如图:

    Box_in_scene


    Box

    特征点匹配结果:

    Match

    另一点需要一提的是 SimpleBlob的实现是有Bug的。不能直接通过 Ptr<FeatureDetector> detector = FeatureDetector::create("SimpleBlob");  语句来调用,而应该直接创建  SimpleBlobDetector的对象:
    [cpp]  view plain  copy
    1.        Mat image = imread("images\\features.jpg");  
    2. Mat descriptors;  
    3. vector<KeyPoint> keypoints;  
    4. SimpleBlobDetector::Params params;  
    5. //params.minThreshold = 10;  
    6. //params.maxThreshold = 100;  
    7. //params.thresholdStep = 10;  
    8. //params.minArea = 10;   
    9. //params.minConvexity = 0.3;  
    10. //params.minInertiaRatio = 0.01;  
    11. //params.maxArea = 8000;  
    12. //params.maxConvexity = 10;  
    13. //params.filterByColor = false;  
    14. //params.filterByCircularity = false;  
    15. SimpleBlobDetector blobDetector( params );  
    16. blobDetector.create("SimpleBlob");  
    17. blobDetector.detect( image, keypoints );  
    18. drawKeypoints(image, keypoints, image, Scalar(255,0,0));  
    以下是SimpleBlobDetector按颜色检测的图像特征:

    六 计算机视觉】SIFT中LoG和DoG比较

    实际计算时,三种方法计算的金字塔组数noctaves,尺度空间坐标σ,以及每组金字塔内的层数S是一样的。同时,假设图像为640*480的标准图像。

    金字塔层数:


    其中o_min = 0,对于分辨率为640*480的图像N=5。

    每组金字塔内图像数:
    S=3,即在做极值检测时使用金子塔内中间3张图像。
    对于LoG每组金字塔内有S+2张图像(S=-1,0,1,2,3),需要做S+1次高斯模糊操作(后一张图像由前一张做高斯模糊得到);而DoG每组金字塔有S+3张高斯图像,得到S+2张DoG图像。
    尺度空间系数:


    其中,S表示每组金字塔内图像层数,n为当前高斯层数,取0-4。DoG需要5个尺度系数得到6张GSS图像,而LoG只需要前4个尺度系数得到5张图像。

    LoG

    高斯核使用正太分布(高斯函数)计算模糊模版,N维空间正太分布方程为:

     
    于是,二维高斯模板上的距离中心点为(x,y)的元素对应高斯计算公式为:
     
    规范化的高斯拉普拉斯图像为
     
    最终构造LoG金字塔有5层,每层有S+2=5张图像,每层金字塔内每张图像尺度是前一张的k倍,即构成的连续尺度序列:


    其中o为当前金字塔层数,n为在当前金字塔层中图像张数。
    由于卷积计算性质:


    在计算时,通过对前一张图像做尺度系数为的卷积操作,可以减少卷积计算次数。故在金字塔每层内的S+2张图像,需要S+1次卷积操作,每次LoG核的尺度系数为:

     
    图1. LoG金字塔示意图。 左侧为图像尺度空间系数,红色矩形框为实际参与比较的空间系数,右侧为在上一张图像做LoG卷积操作的尺度系数

    DoG

    由于LoG与Gauss核具有如下关系:


    即,

     
    因此,LoG算子可以用高斯差分算子DoG(Difference of Guassians)表示。
     
    于是通过高斯金字塔每层内相邻两张图像相减可以得到DoG金字塔。对于最后需要S张图像寻找极值点,需要S+2张DoG图像,S+3张高斯图像。具体关系如图2.所示。


    图 2. 由高斯金字塔得到DoG金字塔及其对应的尺度空间系数示意图。


    LoG & DoG

    一个直观的比较结果,使用分别计算LoG和DoG,得到:


    可以看到,LoG比DoG明显需要更多的加法运算和乘法运算。虽然DoG需要在每层金字塔多做一次高斯操作(即为了得到S+2张DoG图需要S+3张高斯模糊图),但通过减法取代LoG核的计算过程,显著减少了运算次数,大大节省了运算时间。



由前一篇《 关键点搜索与定位》,我们已经找到了关键点。为了实现图像旋转不变性,需要根据检测到的关键点局部图像结构为特征点方向赋值。也就是在 findScaleSpaceExtrema()函数里看到的alcOrientationHist()语句:
[cpp]  view plain  copy
  1. // 计算梯度直方图  
  2. float omax = calcOrientationHist(gauss_pyr[o*(nOctaveLayers+3) + layer],  
  3.                                                 Point(c1, r1),  
  4.                                                 cvRound(SIFT_ORI_RADIUS * scl_octv),  
  5.                                                 SIFT_ORI_SIG_FCTR * scl_octv,  
  6.                                                 hist, n);  

我们使用图像的梯度直方图法求关键点局部结构的稳定方向。

梯度方向和幅值

在前文中,精确定位关键点后也找到改特征点的尺度值σ,根据这一尺度值,得到最接近这一尺度值的高斯图像:


使用有限差分,计算以关键点为中心,以3×1.5σ为半径的区域内图像梯度的幅角和幅值,公式如下:

梯度直方图

在完成关键点邻域内高斯图像梯度计算后,使用直方图统计邻域内像素对应的梯度方向和幅值。

有关直方图的基础知识可以参考《数字图像直方图》,可以看做是离散点的概率表示形式。此处方向直方图的核心是统计以关键点为原点,一定区域内的图像像素点对关键点方向生成所作的贡献

梯度方向直方图的横轴是梯度方向角,纵轴是剃度方向角对应的梯度幅值累加值。梯度方向直方图将0°~360°的范围分为36个柱,每10°为一个柱。下图是从高斯图像上求取梯度,再由梯度得到梯度方向直方图的例图。

在计算直方图时,每个加入直方图的采样点都使用圆形高斯函数函数进行了加权处理,也就是进行高斯平滑。这主要是因为SIFT算法只考虑了尺度和旋转不变形,没有考虑仿射不变性。通过高斯平滑,可以使关键点附近的梯度幅值有较大权重,从而部分弥补没考虑仿射不变形产生的特征点不稳定。

通常离散的梯度直方图要进行插值拟合处理,以求取更精确的方向角度值。(这和《关键点搜索与定位》中插值的思路是一样的)。

关键点方向

直方图峰值代表该关键点处邻域内图像梯度的主方向,也就是该关键点的主方向。在梯度方向直方图中,当存在另一个相当于主峰值    80%能量的峰值时,则将这个方向认为是该关键点的辅方向。所以一个关键点可能检测得到多个方向,这可以增强匹配的鲁棒性。Lowe的论文指出大概有15%关键点具有多方向,但这些点对匹配的稳定性至为关键。

获得图像关键点主方向后,每个关键点有三个信息(x,y,σ,θ):位置、尺度、方向。由此我们可以确定一个SIFT特征区域。通常使用一个带箭头的圆或直接使用箭头表示SIFT区域的三个值:中心表示特征点位置,半径表示关键点尺度(r=2.5σ),箭头表示主方向。具有多个方向的关键点可以复制成多份,然后将方向值分别赋给复制后的关键点。如下图:


源码

[cpp]  view plain  copy
  1. // Computes a gradient orientation histogram at a specified pixel  
  2. // 计算特定点的梯度方向直方图  
  3. static float calcOrientationHist( const Mat& img, Point pt, int radius,  
  4.                                   float sigma, float* hist, int n )  
  5. {  
  6.     //len:2r+1也就是以r为半径的圆(正方形)像素个数  
  7.     int i, j, k, len = (radius*2+1)*(radius*2+1);  
  8.   
  9.     float expf_scale = -1.f/(2.f * sigma * sigma);  
  10.     AutoBuffer<float> buf(len*4 + n+4);  
  11.     float *X = buf, *Y = X + len, *Mag = X, *Ori = Y + len, *W = Ori + len;  
  12.     float* temphist = W + len + 2;  
  13.   
  14.     for( i = 0; i < n; i++ )  
  15.         temphist[i] = 0.f;  
  16.   
  17.     // 图像梯度直方图统计的像素范围  
  18.     for( i = -radius, k = 0; i <= radius; i++ )  
  19.     {  
  20.         int y = pt.y + i;  
  21.         if( y <= 0 || y >= img.rows - 1 )  
  22.             continue;  
  23.         for( j = -radius; j <= radius; j++ )  
  24.         {  
  25.             int x = pt.x + j;  
  26.             if( x <= 0 || x >= img.cols - 1 )  
  27.                 continue;  
  28.   
  29.             float dx = (float)(img.at<short>(y, x+1) - img.at<short>(y, x-1));  
  30.             float dy = (float)(img.at<short>(y-1, x) - img.at<short>(y+1, x));  
  31.   
  32.             X[k] = dx; Y[k] = dy; W[k] = (i*i + j*j)*expf_scale;  
  33.             k++;  
  34.         }  
  35.     }  
  36.   
  37.     len = k;  
  38.   
  39.     // compute gradient values, orientations and the weights over the pixel neighborhood  
  40.     exp(W, W, len);   
  41.     fastAtan2(Y, X, Ori, len, true);   
  42.     magnitude(X, Y, Mag, len);   
  43.       
  44.     // 计算直方图的每个bin  
  45.     for( k = 0; k < len; k++ )  
  46.     {  
  47.         int bin = cvRound((n/360.f)*Ori[k]);  
  48.         if( bin >= n )  
  49.             bin -= n;  
  50.         if( bin < 0 )  
  51.             bin += n;  
  52.         temphist[bin] += W[k]*Mag[k];  
  53.     }  
  54.   
  55.     // smooth the histogram  
  56.     // 高斯平滑  
  57.     temphist[-1] = temphist[n-1];  
  58.     temphist[-2] = temphist[n-2];  
  59.     temphist[n] = temphist[0];  
  60.     temphist[n+1] = temphist[1];  
  61.     for( i = 0; i < n; i++ )  
  62.     {  
  63.         hist[i] = (temphist[i-2] + temphist[i+2])*(1.f/16.f) +  
  64.             (temphist[i-1] + temphist[i+1])*(4.f/16.f) +  
  65.             temphist[i]*(6.f/16.f);  
  66.     }  
  67.       
  68.     // 得到主方向  
  69.     float maxval = hist[0];  
  70.     for( i = 1; i < n; i++ )  
  71.         maxval = std::max(maxval, hist[i]);  
  72.   
  73.     return maxval;  
  74. }  

《SIFT原理与源码分析》系列文章索引:http://blog.csdn.net/xiaowei_cqu/article/details/8069548


由前一篇《 方向赋值》,为找到的关键点即SIFT特征点赋了值,包含位置、尺度和方向的信息。接下来的步骤是关键点描述,即用用一组向量将这个关键点描述出来,这个描述子不但包括关键点,也包括关键点周围对其有贡献的像素点。用来作为 目标匹配的依据(所以描述子应该有较高的独特性,以保证匹配率),也可使关键点具有更多的不变特性,如光照变化、3D视点变化等。

SIFT描述子h(x,y,θ)是对关键点附近邻域内高斯图像梯度统计的结果,是一个三维矩阵,但通常用一个矢量来表示。矢量通过对三维矩阵按一定规律排列得到。

描述子采样区域

特征描述子与关键点所在尺度有关,因此对梯度的求取应在特征点对应的高斯图像上进行。将关键点附近划分成d×d个子区域,每个子区域尺寸为mσ个像元(d=4,m=3,σ为尺特征点的尺度值)。考虑到实际计算时需要双线性插值,故计算的图像区域为mσ(d+1),再考虑旋转,则实际计算的图像区域为 ,如下图所示:

源码

[cpp]  view plain  copy
  1.    Point pt(cvRound(ptf.x), cvRound(ptf.y));  
  2. //计算余弦,正弦,CV_PI/180:将角度值转化为幅度值  
  3.    float cos_t = cosf(ori*(float)(CV_PI/180));  
  4.    float sin_t = sinf(ori*(float)(CV_PI/180));  
  5.    float bins_per_rad = n / 360.f;  
  6.    float exp_scale = -1.f/(d * d * 0.5f); //d:SIFT_DESCR_WIDTH 4      
  7.    float hist_width = SIFT_DESCR_SCL_FCTR * scl;  // SIFT_DESCR_SCL_FCTR: 3   
  8.                                                // scl: size*0.5f  
  9. // 计算图像区域半径mσ(d+1)/2*sqrt(2)  
  10. // 1.4142135623730951f 为根号2  
  11.    int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);  
  12.    cos_t /= hist_width;  
  13.    sin_t /= hist_width;  



区域坐标轴旋转

为了保证特征矢量具有旋转不变性,要以特征点为中心,在附近邻域内旋转θ角,即旋转为特征点的方向。

旋转后区域内采样点新的坐标为:

源码

[cpp]  view plain  copy
  1. //计算采样区域点坐标旋转  
  2.     for( i = -radius, k = 0; i <= radius; i++ )  
  3.         for( j = -radius; j <= radius; j++ )  
  4.         {  
  5.             /* 
  6.              Calculate sample's histogram array coords rotated relative to ori. 
  7.              Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e. 
  8.              r_rot = 1.5) have full weight placed in row 1 after interpolation. 
  9.              */  
  10.             float c_rot = j * cos_t - i * sin_t;  
  11.             float r_rot = j * sin_t + i * cos_t;  
  12.             float rbin = r_rot + d/2 - 0.5f;  
  13.             float cbin = c_rot + d/2 - 0.5f;  
  14.             int r = pt.y + i, c = pt.x + j;  
  15.   
  16.             if( rbin > -1 && rbin < d && cbin > -1 && cbin < d &&  
  17.                r > 0 && r < rows - 1 && c > 0 && c < cols - 1 )  
  18.             {  
  19.                 float dx = (float)(img.at<short>(r, c+1) - img.at<short>(r, c-1));  
  20.                 float dy = (float)(img.at<short>(r-1, c) - img.at<short>(r+1, c));  
  21.                 X[k] = dx; Y[k] = dy; RBin[k] = rbin; CBin[k] = cbin;  
  22.                 W[k] = (c_rot * c_rot + r_rot * r_rot)*exp_scale;  
  23.                 k++;  
  24.             }  
  25.         }  


计算采样区域梯度直方图

将旋转后区域划分为d×d个子区域(每个区域间隔为mσ像元),在子区域内计算8个方向的梯度直方图,绘制每个方向梯度方向的累加值,形成一个种子点。
与求主方向不同的是,此时,每个子区域梯度方向直方图将0°~360°划分为8个方向区间,每个区间为45°。即每个种子点有8个方向区间的梯度强度信息。由于存在d×d,即4×4个子区域,所以最终共有4×4×8=128个数据,形成128维SIFT特征矢量。

对特征矢量需要加权处理,加权采用mσd/2的标准高斯函数。为了除去光照变化影响,还有一步归一化处理。

源码

[cpp]  view plain  copy
  1. //计算梯度直方图  
  2.     for( k = 0; k < len; k++ )  
  3.     {  
  4.         float rbin = RBin[k], cbin = CBin[k];  
  5.         float obin = (Ori[k] - ori)*bins_per_rad;  
  6.         float mag = Mag[k]*W[k];  
  7.   
  8.         int r0 = cvFloor( rbin );  
  9.         int c0 = cvFloor( cbin );  
  10.         int o0 = cvFloor( obin );  
  11.         rbin -= r0;  
  12.         cbin -= c0;  
  13.         obin -= o0;  
  14.   
  15.         //n为SIFT_DESCR_HIST_BINS:8,即将360°分为8个区间  
  16.         if( o0 < 0 )  
  17.             o0 += n;  
  18.         if( o0 >= n )  
  19.             o0 -= n;  
  20.           
  21.   
  22.         // histogram update using tri-linear interpolation  
  23.         // 双线性插值  
  24.         float v_r1 = mag*rbin, v_r0 = mag - v_r1;  
  25.         float v_rc11 = v_r1*cbin, v_rc10 = v_r1 - v_rc11;  
  26.         float v_rc01 = v_r0*cbin, v_rc00 = v_r0 - v_rc01;  
  27.         float v_rco111 = v_rc11*obin, v_rco110 = v_rc11 - v_rco111;  
  28.         float v_rco101 = v_rc10*obin, v_rco100 = v_rc10 - v_rco101;  
  29.         float v_rco011 = v_rc01*obin, v_rco010 = v_rc01 - v_rco011;  
  30.         float v_rco001 = v_rc00*obin, v_rco000 = v_rc00 - v_rco001;  
  31.   
  32.         int idx = ((r0+1)*(d+2) + c0+1)*(n+2) + o0;  
  33.         hist[idx] += v_rco000;  
  34.         hist[idx+1] += v_rco001;  
  35.         hist[idx+(n+2)] += v_rco010;  
  36.         hist[idx+(n+3)] += v_rco011;  
  37.         hist[idx+(d+2)*(n+2)] += v_rco100;  
  38.         hist[idx+(d+2)*(n+2)+1] += v_rco101;  
  39.         hist[idx+(d+3)*(n+2)] += v_rco110;  
  40.         hist[idx+(d+3)*(n+2)+1] += v_rco111;  
  41.     }  

关键点描述源码

[cpp]  view plain  copy
  1. // SIFT关键点特征描述  
  2. // SIFT描述子是关键点领域高斯图像提取统计结果的一种表示  
  3. static void calcSIFTDescriptor( const Mat& img, Point2f ptf, float ori, float scl,  
  4.                                int d, int n, float* dst )  
  5.                              
  6. {  
  7.     Point pt(cvRound(ptf.x), cvRound(ptf.y));  
  8.     //计算余弦,正弦,CV_PI/180:将角度值转化为幅度值  
  9.     float cos_t = cosf(ori*(float)(CV_PI/180));  
  10.     float sin_t = sinf(ori*(float)(CV_PI/180));  
  11.     float bins_per_rad = n / 360.f;  
  12.     float exp_scale = -1.f/(d * d * 0.5f); //d:SIFT_DESCR_WIDTH 4     
  13.     float hist_width = SIFT_DESCR_SCL_FCTR * scl;  // SIFT_DESCR_SCL_FCTR: 3   
  14.                                                    // scl: size*0.5f  
  15.     // 计算图像区域半径mσ(d+1)/2*sqrt(2)  
  16.     // 1.4142135623730951f 为根号2  
  17.     int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);  
  18.     cos_t /= hist_width;  
  19.     sin_t /= hist_width;  
  20.   
  21.     int i, j, k, len = (radius*2+1)*(radius*2+1), histlen = (d+2)*(d+2)*(n+2);  
  22.     int rows = img.rows, cols = img.cols;  
  23.   
  24.     AutoBuffer<float> buf(len*6 + histlen);  
  25.     float *X = buf, *Y = X + len, *Mag = Y, *Ori = Mag + len, *W = Ori + len;  
  26.     float *RBin = W + len, *CBin = RBin + len, *hist = CBin + len;  
  27.   
  28.     //初始化直方图  
  29.     for( i = 0; i < d+2; i++ )  
  30.     {  
  31.         for( j = 0; j < d+2; j++ )  
  32.             for( k = 0; k < n+2; k++ )  
  33.                 hist[(i*(d+2) + j)*(n+2) + k] = 0.;  
  34.     }  
  35.   
  36.     //计算采样区域点坐标旋转  
  37.     for( i = -radius, k = 0; i <= radius; i++ )  
  38.         for( j = -radius; j <= radius; j++ )  
  39.         {  
  40.             /* 
  41.              Calculate sample's histogram array coords rotated relative to ori. 
  42.              Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e. 
  43.              r_rot = 1.5) have full weight placed in row 1 after interpolation. 
  44.              */  
  45.             float c_rot = j * cos_t - i * sin_t;  
  46.             float r_rot = j * sin_t + i * cos_t;  
  47.             float rbin = r_rot + d/2 - 0.5f;  
  48.             float cbin = c_rot + d/2 - 0.5f;  
  49.             int r = pt.y + i, c = pt.x + j;  
  50.   
  51.             if( rbin > -1 && rbin < d && cbin > -1 && cbin < d &&  
  52.                r > 0 && r < rows - 1 && c > 0 && c < cols - 1 )  
  53.             {  
  54.                 float dx = (float)(img.at<short>(r, c+1) - img.at<short>(r, c-1));  
  55.                 float dy = (float)(img.at<short>(r-1, c) - img.at<short>(r+1, c));  
  56.                 X[k] = dx; Y[k] = dy; RBin[k] = rbin; CBin[k] = cbin;  
  57.                 W[k] = (c_rot * c_rot + r_rot * r_rot)*exp_scale;  
  58.                 k++;  
  59.             }  
  60.         }  
  61.   
  62.     len = k;  
  63.     fastAtan2(Y, X, Ori, len, true);  
  64.     magnitude(X, Y, Mag, len);  
  65.     exp(W, W, len);  
  66.   
  67.       
  68.     //计算梯度直方图  
  69.     for( k = 0; k < len; k++ )  
  70.     {  
  71.         float rbin = RBin[k], cbin = CBin[k];  
  72.         float obin = (Ori[k] - ori)*bins_per_rad;  
  73.         float mag = Mag[k]*W[k];  
  74.   
  75.         int r0 = cvFloor( rbin );  
  76.         int c0 = cvFloor( cbin );  
  77.         int o0 = cvFloor( obin );  
  78.         rbin -= r0;  
  79.         cbin -= c0;  
  80.         obin -= o0;  
  81.   
  82.         //n为SIFT_DESCR_HIST_BINS:8,即将360°分为8个区间  
  83.         if( o0 < 0 )  
  84.             o0 += n;  
  85.         if( o0 >= n )  
  86.             o0 -= n;  
  87.           
  88.   
  89.         // histogram update using tri-linear interpolation  
  90.         // 双线性插值  
  91.         float v_r1 = mag*rbin, v_r0 = mag - v_r1;  
  92.         float v_rc11 = v_r1*cbin, v_rc10 = v_r1 - v_rc11;  
  93.         float v_rc01 = v_r0*cbin, v_rc00 = v_r0 - v_rc01;  
  94.         float v_rco111 = v_rc11*obin, v_rco110 = v_rc11 - v_rco111;  
  95.         float v_rco101 = v_rc10*obin, v_rco100 = v_rc10 - v_rco101;  
  96.         float v_rco011 = v_rc01*obin, v_rco010 = v_rc01 - v_rco011;  
  97.         float v_rco001 = v_rc00*obin, v_rco000 = v_rc00 - v_rco001;  
  98.   
  99.         int idx = ((r0+1)*(d+2) + c0+1)*(n+2) + o0;  
  100.         hist[idx] += v_rco000;  
  101.         hist[idx+1] += v_rco001;  
  102.         hist[idx+(n+2)] += v_rco010;  
  103.         hist[idx+(n+3)] += v_rco011;  
  104.         hist[idx+(d+2)*(n+2)] += v_rco100;  
  105.         hist[idx+(d+2)*(n+2)+1] += v_rco101;  
  106.         hist[idx+(d+3)*(n+2)] += v_rco110;  
  107.         hist[idx+(d+3)*(n+2)+1] += v_rco111;  
  108.     }  
  109.   
  110.     // finalize histogram, since the orientation histograms are circular  
  111.     // 最后确定直方图,目标方向直方图是圆的  
  112.     for( i = 0; i < d; i++ )  
  113.         for( j = 0; j < d; j++ )  
  114.         {  
  115.             int idx = ((i+1)*(d+2) + (j+1))*(n+2);  
  116.             hist[idx] += hist[idx+n];  
  117.             hist[idx+1] += hist[idx+n+1];  
  118.             for( k = 0; k < n; k++ )  
  119.                 dst[(i*d + j)*n + k] = hist[idx+k];  
  120.         }  
  121.     // copy histogram to the descriptor,  
  122.     // apply hysteresis thresholding  
  123.     // and scale the result, so that it can be easily converted  
  124.     // to byte array  
  125.     float nrm2 = 0;  
  126.     len = d*d*n;  
  127.     for( k = 0; k < len; k++ )  
  128.         nrm2 += dst[k]*dst[k];  
  129.     float thr = std::sqrt(nrm2)*SIFT_DESCR_MAG_THR;  
  130.     for( i = 0, nrm2 = 0; i < k; i++ )  
  131.     {  
  132.         float val = std::min(dst[i], thr);  
  133.         dst[i] = val;  
  134.         nrm2 += val*val;  
  135.     }  
  136.     nrm2 = SIFT_INT_DESCR_FCTR/std::max(std::sqrt(nrm2), FLT_EPSILON);  
  137.     for( k = 0; k < len; k++ )  
  138.     {  
  139.         dst[k] = saturate_cast<uchar>(dst[k]*nrm2);  
  140.     }  
  141. }  

OpenCV提供FeatureDetector实现特征检测及匹配

[cpp]  view plain  copy
  1. class CV_EXPORTS FeatureDetector  
  2. {  
  3. public:  
  4.     virtual ~FeatureDetector();  
  5.     void detect( const Mat& image, vector<KeyPoint>& keypoints,  
  6.         const Mat& mask=Mat() ) const;  
  7.     void detect( const vector<Mat>& images,  
  8.         vector<vector<KeyPoint> >& keypoints,  
  9.         const vector<Mat>& masks=vector<Mat>() ) const;  
  10.     virtual void read(const FileNode&);  
  11.     virtual void write(FileStorage&) const;  
  12.     static Ptr<FeatureDetector> create( const string& detectorType );  
  13. protected:  
  14.     ...  
  15. };  

FeatureDetetor是虚类,通过定义FeatureDetector的对象可以使用多种特征检测方法。通过create()函数调用:

[cpp]  view plain  copy
  1. Ptr<FeatureDetector> FeatureDetector::create(const string& detectorType);  

OpenCV 2.4.3提供了10种特征检测方法:

  • "FAST" – FastFeatureDetector
  • "STAR" – StarFeatureDetector
  • "SIFT" – SIFT (nonfree module)
  • "SURF" – SURF (nonfree module)
  • "ORB" – ORB
  • "MSER" – MSER
  • "GFTT" – GoodFeaturesToTrackDetector
  • "HARRIS" – GoodFeaturesToTrackDetector with Harris detector enabled
  • "Dense" – DenseFeatureDetector
  • "SimpleBlob" – SimpleBlobDetector
图片中的特征大体可分为三种:点特征、线特征、块特征。
FAST算法是Rosten提出的一种快速提取的点特征 [1],Harris与GFTT也是点特征,更具体来说是角点特征( 参考这里)。
SimpleBlob是简单块特征,可以通过设置 SimpleBlobDetector的参数决定提取图像块的主要性质,提供5种:
颜色  By color、面积  By area、圆形度  By circularity、最大inertia (不知道怎么翻译)与最小inertia的比例  By ratio of the minimum inertia to maximum inertia、以及凸性  By convexity.
最常用的当属SIFT,尺度不变特征匹配算法( 参考这里);以及后来发展起来的SURF,都可以看做较为复杂的块特征。这两个算法在OpenCV nonfree的模块里面,需要在附件引用项中添加opencv_nonfree243.lib,同时在代码中加入:
[cpp]  view plain  copy
  1. initModule_nonfree();  
至于其他几种算法,我就不太了解了 ^_^

一个简单的使用演示:
[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.   
  4.     initModule_nonfree();//if use SIFT or SURF  
  5.     Ptr<FeatureDetector> detector = FeatureDetector::create( "SIFT" );  
  6.     Ptr<DescriptorExtractor> descriptor_extractor = DescriptorExtractor::create( "SIFT" );  
  7.     Ptr<DescriptorMatcher> descriptor_matcher = DescriptorMatcher::create( "BruteForce" );  
  8.     if( detector.empty() || descriptor_extractor.empty() )  
  9.         throw runtime_error("fail to create detector!");  
  10.   
  11.     Mat img1 = imread("images\\box_in_scene.png");  
  12.     Mat img2 = imread("images\\box.png");  
  13.   
  14.     //detect keypoints;  
  15.     vector<KeyPoint> keypoints1,keypoints2;  
  16.     detector->detect( img1, keypoints1 );  
  17.     detector->detect( img2, keypoints2 );  
  18.     cout <<"img1:"<< keypoints1.size() << " points  img2:" <<keypoints2.size()   
  19.         << " points" << endl << ">" << endl;  
  20.   
  21.     //compute descriptors for keypoints;  
  22.     cout << "< Computing descriptors for keypoints from images..." << endl;  
  23.     Mat descriptors1,descriptors2;  
  24.     descriptor_extractor->compute( img1, keypoints1, descriptors1 );  
  25.     descriptor_extractor->compute( img2, keypoints2, descriptors2 );  
  26.   
  27.     cout<<endl<<"Descriptors Size: "<<descriptors2.size()<<" >"<<endl;  
  28.     cout<<endl<<"Descriptor's Column: "<<descriptors2.cols<<endl  
  29.         <<"Descriptor's Row: "<<descriptors2.rows<<endl;  
  30.     cout << ">" << endl;  
  31.   
  32.     //Draw And Match img1,img2 keypoints  
  33.     Mat img_keypoints1,img_keypoints2;  
  34.     drawKeypoints(img1,keypoints1,img_keypoints1,Scalar::all(-1),0);  
  35.     drawKeypoints(img2,keypoints2,img_keypoints2,Scalar::all(-1),0);  
  36.     imshow("Box_in_scene keyPoints",img_keypoints1);  
  37.     imshow("Box keyPoints",img_keypoints2);  
  38.   
  39.     descriptor_extractor->compute( img1, keypoints1, descriptors1 );    
  40.     vector<DMatch> matches;  
  41.     descriptor_matcher->match( descriptors1, descriptors2, matches );  
  42.   
  43.     Mat img_matches;  
  44.     drawMatches(img1,keypoints1,img2,keypoints2,matches,img_matches,Scalar::all(-1),CV_RGB(255,255,255),Mat(),4);  
  45.   
  46.     imshow("Mathc",img_matches);  
  47.     waitKey(10000);  
  48.     return 0;  
  49. }  

特征检测结果如图:

Box_in_scene


Box

特征点匹配结果:

Match

另一点需要一提的是 SimpleBlob的实现是有Bug的。不能直接通过 Ptr<FeatureDetector> detector = FeatureDetector::create("SimpleBlob");  语句来调用,而应该直接创建  SimpleBlobDetector的对象:
[cpp]  view plain  copy
  1.        Mat image = imread("images\\features.jpg");  
  2. Mat descriptors;  
  3. vector<KeyPoint> keypoints;  
  4. SimpleBlobDetector::Params params;  
  5. //params.minThreshold = 10;  
  6. //params.maxThreshold = 100;  
  7. //params.thresholdStep = 10;  
  8. //params.minArea = 10;   
  9. //params.minConvexity = 0.3;  
  10. //params.minInertiaRatio = 0.01;  
  11. //params.maxArea = 8000;  
  12. //params.maxConvexity = 10;  
  13. //params.filterByColor = false;  
  14. //params.filterByCircularity = false;  
  15. SimpleBlobDetector blobDetector( params );  
  16. blobDetector.create("SimpleBlob");  
  17. blobDetector.detect( image, keypoints );  
  18. drawKeypoints(image, keypoints, image, Scalar(255,0,0));  
以下是SimpleBlobDetector按颜色检测的图像特征:

实际计算时,三种方法计算的金字塔组数noctaves,尺度空间坐标σ,以及每组金字塔内的层数S是一样的。同时,假设图像为640*480的标准图像。

金字塔层数:


其中o_min = 0,对于分辨率为640*480的图像N=5。

每组金字塔内图像数:
S=3,即在做极值检测时使用金子塔内中间3张图像。
对于LoG每组金字塔内有S+2张图像(S=-1,0,1,2,3),需要做S+1次高斯模糊操作(后一张图像由前一张做高斯模糊得到);而DoG每组金字塔有S+3张高斯图像,得到S+2张DoG图像。
尺度空间系数:


其中,S表示每组金字塔内图像层数,n为当前高斯层数,取0-4。DoG需要5个尺度系数得到6张GSS图像,而LoG只需要前4个尺度系数得到5张图像。

LoG

高斯核使用正太分布(高斯函数)计算模糊模版,N维空间正太分布方程为:

 
于是,二维高斯模板上的距离中心点为(x,y)的元素对应高斯计算公式为:
 
规范化的高斯拉普拉斯图像为
 
最终构造LoG金字塔有5层,每层有S+2=5张图像,每层金字塔内每张图像尺度是前一张的k倍,即构成的连续尺度序列:


其中o为当前金字塔层数,n为在当前金字塔层中图像张数。
由于卷积计算性质:


在计算时,通过对前一张图像做尺度系数为的卷积操作,可以减少卷积计算次数。故在金字塔每层内的S+2张图像,需要S+1次卷积操作,每次LoG核的尺度系数为:

 
图1. LoG金字塔示意图。 左侧为图像尺度空间系数,红色矩形框为实际参与比较的空间系数,右侧为在上一张图像做LoG卷积操作的尺度系数

DoG

由于LoG与Gauss核具有如下关系:


即,

 
因此,LoG算子可以用高斯差分算子DoG(Difference of Guassians)表示。
 
于是通过高斯金字塔每层内相邻两张图像相减可以得到DoG金字塔。对于最后需要S张图像寻找极值点,需要S+2张DoG图像,S+3张高斯图像。具体关系如图2.所示。


图 2. 由高斯金字塔得到DoG金字塔及其对应的尺度空间系数示意图。


LoG & DoG

一个直观的比较结果,使用分别计算LoG和DoG,得到:


可以看到,LoG比DoG明显需要更多的加法运算和乘法运算。虽然DoG需要在每层金字塔多做一次高斯操作(即为了得到S+2张DoG图需要S+3张高斯模糊图),但通过减法取代LoG核的计算过程,显著减少了运算次数,大大节省了运算时间。

猜你喜欢

转载自blog.csdn.net/darlingqiang/article/details/79511137