SIFT原理

轉載請註明出處:http://blog.csdn.NET/luoshixian099/article/details/47377611


相關: KD樹+BBF算法解析

           SURF原理與源碼解析

     SIFT的原理已經有很多大牛的博客上做了解析,本文重點將以Rob Hess等人用C實現的代碼做解析,結合代碼SIFT原理會更容易理解。一些難理解點的用了標註。

      歡迎大家批評指正!

     SIFT(Scale-invariant feature transform)即尺度不變特徵轉換,提取的局部特徵點具有尺度不變性,且對於旋轉,亮度,噪聲等有很高的穩定性。


下圖中,涉及到圖像的旋轉,仿射,光照等變化,SIFT算法依然有很好的匹配效果。


SIFT特徵點提取

本文將以下函數爲參照順序介紹SIFT特徵點提取與描述方法。

 1.圖像預處理

 2.構建高斯金字塔(不同尺度下的圖像)

 3.生成DOG尺度空間

 4.關鍵點搜索與定位

 5.計算特徵點所在的尺度

 6.爲特徵點分配方向角

 7.構建特徵描述子


  1. /** 
  2.    Finds SIFT features in an image using user-specified parameter values.  All 
  3.    detected features are stored in the array pointed to by \a feat. 
  4. */  
  5. int _sift_features( IplImage* img, struct feature** feat, int intvls,  
  6.             double sigma, double contr_thr, int curv_thr,  
  7.             int img_dbl, int descr_width, int descr_hist_bins )  
  8. {  
  9.   IplImage* init_img;  
  10.   IplImage*** gauss_pyr, *** dog_pyr;  
  11.   CvMemStorage* storage;  
  12.   CvSeq* features;  
  13.   int octvs, i, n = 0;  
  14.     
  15.   /* check arguments */  
  16.   if( ! img )  
  17.     fatal_error( "NULL pointer error, %s, line %d",  __FILE__, __LINE__ );  
  18.   if( ! feat )  
  19.     fatal_error( "NULL pointer error, %s, line %d",  __FILE__, __LINE__ );  
  20.   
  21.   /* build scale space pyramid; smallest dimension of top level is ~4 pixels */  
  22.   init_img = create_init_img( img, img_dbl, sigma );                            //對進行圖片預處理         
  23.   octvs = log( MIN( init_img->width, init_img->height ) ) / log(2) - 2;  //計算高斯金字塔的組數(octave),同時保證頂層至少有4個像素點  
  24.   gauss_pyr = build_gauss_pyr( init_img, octvs, intvls, sigma );  //建立高斯金字塔  
  25.   dog_pyr = build_dog_pyr( gauss_pyr, octvs, intvls );   //DOG尺度空間  
  26.     
  27.   storage = cvCreateMemStorage( 0 );  
  28.   features = scale_space_extrema( dog_pyr, octvs, intvls, contr_thr,   //極值點檢測,並去除不穩定特徵點  
  29.                   curv_thr, storage );  
  30.   calc_feature_scales( features, sigma, intvls );                      //計算特徵點所在的尺度  
  31.   if( img_dbl )  
  32.     adjust_for_img_dbl( features );                                       //如果圖像初始被擴大了2倍,所有座標與尺度要除以2  
  33.   calc_feature_oris( features, gauss_pyr );                               //計算特徵點所在尺度內的方向角  
  34.   compute_descriptors( features, gauss_pyr, descr_width, descr_hist_bins );//計算特徵描述子 128維向量  
  35.   
  36.   /* sort features by decreasing scale and move from CvSeq to array */  
  37.   cvSeqSort( features, (CvCmpFunc)feature_cmp, NULL );   //對特徵點按尺度排序  
  38.   n = features->total;  
  39.   *feat = calloc( n, sizeof(struct feature) );  
  40.   *feat = cvCvtSeqToArray( features, *feat, CV_WHOLE_SEQ );         
  41.   for( i = 0; i < n; i++ )  
  42.     {  
  43.       free( (*feat)[i].feature_data );  
  44.       (*feat)[i].feature_data = NULL;  
  45.     }  
  46.     
  47.   cvReleaseMemStorage( &storage );  
  48.   cvReleaseImage( &init_img );  
  49.   release_pyr( &gauss_pyr, octvs, intvls + 3 );  
  50.   release_pyr( &dog_pyr, octvs, intvls + 2 );  
  51.   return n;  
  52. }  


  —————————————————————————————————————————————————————


 1.圖像預處理


  1. /************************ Functions prototyped here **************************/  
  2.   
  3. /* 
  4.   Converts an image to 8-bit grayscale and Gaussian-smooths it.  The image is 
  5.   optionally doubled in size prior to smoothing. 
  6.  
  7.   @param img input image 
  8.   @param img_dbl if true, image is doubled in size prior to smoothing 
  9.   @param sigma total std of Gaussian smoothing 
  10. */  
  11. static IplImage* create_init_img( IplImage* img, int img_dbl, double sigma )  
  12. {  
  13.   IplImage* gray, * dbl;  
  14.   double sig_diff;  
  15.   
  16.   gray = convert_to_gray32( img );   //轉換爲32位灰度圖  
  17.   if( img_dbl )                                  // 圖像被放大二倍  
  18.     {  
  19.       sig_diff = sqrt( sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA * 4 );   //  sigma = 1.6 , SIFT_INIT_SIGMA = 0.5  lowe認爲圖像在尺度0.5下最清晰  
  20.       dbl = cvCreateImage( cvSize( img->width*2, img->height*2 ),  
  21.                IPL_DEPTH_32F, 1 );  
  22.       cvResize( gray, dbl, CV_INTER_CUBIC );  //雙三次插值方法 放大圖像  
  23.       cvSmooth( dbl, dbl, CV_GAUSSIAN, 0, 0, sig_diff, sig_diff );     //高斯平滑  
  24.       cvReleaseImage( &gray );  
  25.       return dbl;  
  26.     }  
  27.   else  
  28.     {  
  29.       sig_diff = sqrt( sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA );  
  30.       cvSmooth( gray, gray, CV_GAUSSIAN, 0, 0, sig_diff, sig_diff ); // 高斯平滑  
  31.       return gray;  
  32.     }  
  33. }  
lowe建議把初始圖像放大二倍,可以得到更多的特徵點,提取到更多細節,並且認爲圖像在尺度σ = 0.5時圖像最清晰,初始高斯尺度爲σ = 1.6。
第19行因爲圖像被放大二倍,此時σ = 1.0 。因爲對二倍化後的圖像平滑是在σ = 0.5 上疊加的高斯模糊,
  所以有模糊係數有sig_diff = sqrt (sigma *sigma - 0.5*0.5*4)=sqrt(1.6*1.6 -1) ;

 2.構建高斯金字塔


構建高斯金字塔過程即構建出圖像在不同尺度上圖像,提取到的特徵點可有具有尺度不變性。
圖像的尺度空間L(x,y,σ)可以用一個高斯函數G(x,y,σ)與圖像I(x,y)卷積產生,即L(x,y,σ) = G(x,y,σ) * I(x,y) 
其中二維高斯核的計算爲             
不同的尺度空間即用不同的高斯核函數平滑圖像, 平滑係數越大,圖像越模糊。即模擬出動物的視覺效果,因爲事先不知道物體的大小,在不同的尺度下,圖像的細節會表現的不同。當尺度由小變大的過程中,是一個細節逐步簡化的過程,圖像中特徵不夠明顯的物體,就模糊的多了,而有些物體還可以看得到大致的輪廓。所以要在不同尺度下,觀察物體的尺度響應,提取到的特徵才能具有尺度不變性。

SIFT算法採用高斯金字塔實現連續的尺度空間的圖像。金字塔共分爲O(octave)組,每組有S(intervals)層 ,下一組是由上一組隔點採樣得到(即降2倍分辨率),這是爲了減輕卷積運算的工作量。
構建高斯金字塔(octave = 5, intervals +3=6):
                        
全部空間尺度爲: 
                                         

☆1.這個尺度因子都是在原圖上進行的,而在算法實現過程中,採用高斯平滑是在上一層圖像上再疊加高斯平滑,即我們在程序中看到的平滑因子爲   

            
Eg. 在第一層上爲了得到kσ的高斯模糊圖像,可以在原圖上直接採用kσ平滑,也可以在上一層圖像上(已被σ平滑)的圖像上採用平滑因子爲平滑圖像,效果是一樣的。
 ☆2.我們在源碼上同時也沒有看到組間的2倍的關係,實際在對每組的平滑因子都是一樣的,2倍的關係是由於在降採樣的過程中產生的,第二層的第一張圖是由第一層的平滑因子爲2σ的圖像上(即倒數第三張)降採樣得到,此時圖像平滑因子爲σ,所以繼續採用以上的平滑因子。但在原圖上看,形成了全部的空間尺度。
☆3.每組(octave)有S+3層圖像,是由於在DOG尺度空間上尋找極值點的方法是在一個立方體內進行,即上下層比較,所以不在DOG空間的第一層與最後一層尋找,即DOG需要S+2層圖像,由於DOG尺度空間是由高斯金字塔相鄰圖像相減得到,即每組需要S+3層圖像。
  1. /* 
  2.   Builds Gaussian scale space pyramid from an image 
  3.   @param base base image of the pyramid 
  4.   @param octvs number of octaves of scale space 
  5.   @param intvls number of intervals per octave 
  6.   @param sigma amount of Gaussian smoothing per octave 
  7.  
  8.   @return Returns a Gaussian scale space pyramid as an octvs x (intvls + 3) 
  9.     array  
  10.      
  11. 給定組數(octave)和層數(intvls),以及初始平滑係數sigma,構建高斯金字塔 
  12. 返回的每組中層數爲intvls+3 
  13. */  
  14. static IplImage*** build_gauss_pyr( IplImage* base, int octvs,  
  15.                  int intvls, double sigma )  
  16. {  
  17.   IplImage*** gauss_pyr;  
  18.   const int _intvls = intvls;             // lowe 採用了每組層數(intvls)爲 3  
  19.  // double  sig_total, sig_prev;  
  20.      double  k;  
  21.   int i, o;  
  22.   double *sig = (double *)malloc(sizeof(int)*(_intvls+3));  //存儲每組的高斯平滑因子,每組對應的平滑因子都相同  
  23.   
  24.   gauss_pyr = calloc( octvs, sizeof( IplImage** ) );                
  25.   for( i = 0; i < octvs; i++ )  
  26.     gauss_pyr[i] = calloc( intvls + 3, sizeof( IplImage *) );  
  27.   
  28.   /* 
  29.     precompute Gaussian sigmas using the following formula: 
  30.  
  31.     \sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2 
  32.  
  33.     sig[i] is the incremental sigma value needed to compute  
  34.     the actual sigma of level i. Keeping track of incremental 
  35.     sigmas vs. total sigmas keeps the gaussian kernel small. 
  36.   */  
  37.   k = pow( 2.0, 1.0 / intvls );                 // k = 2^(1/S)  
  38.   sig[0] = sigma;  
  39.   sig[1] = sigma * sqrt( k*k- 1 );  
  40.   for (i = 2; i < intvls + 3; i++)  
  41.       sig[i] = sig[i-1] * k;                       //每組對應的平滑因子爲 σ ,  sqrt(k^2 -1)* σ, sqrt(k^2 -1)* kσ , ...  
  42.   
  43.   for( o = 0; o < octvs; o++ )  
  44.     for( i = 0; i < intvls + 3; i++ )  
  45.       {  
  46.     if( o == 0  &&  i == 0 )  
  47.       gauss_pyr[o][i] = cvCloneImage(base);                       //第一組,第一層爲原圖  
  48.   
  49.     /* base of new octvave is halved image from end of previous octave */  
  50.     else if( i == 0 )  
  51.       gauss_pyr[o][i] = downsample( gauss_pyr[o-1][intvls] );  //第一層圖像由上一層倒數第三張隔點採樣得到  
  52.         
  53.     /* blur the current octave's last image to create the next one */  
  54.     else  
  55.       {  
  56.         gauss_pyr[o][i] = cvCreateImage( cvGetSize(gauss_pyr[o][i-1]),  
  57.                          IPL_DEPTH_32F, 1 );  
  58.         cvSmooth( gauss_pyr[o][i-1], gauss_pyr[o][i],  
  59.               CV_GAUSSIAN, 0, 0, sig[i], sig[i] );                       //高斯平滑  
  60.       }  
  61.       }  
  62.        
  63.      
  64.   return gauss_pyr;  
  65. }  

3.生成DOG尺度空間

Lindeberg發現高斯差分函數(Difference of Gaussian ,簡稱DOG算子)與尺度歸一化的高斯拉普拉斯函數非常近似,且






 
差分近似:

lowe建議採用相鄰尺度的圖像相減來獲得高斯差分圖像D(x,y,σ)來近似LOG來進行極值檢測。
D(x,y,σ) = G(x,y,kσ)*I(x,y)-G(x,y,σ)*I(x,y)
              =L(x,y,kσ) - L(x,y,σ)
對高斯金字塔的每組內相鄰圖像相減,形成DOG尺度空間,這時DOG中每組有S+2層圖像


  1. static IplImage*** build_dog_pyr( IplImage*** gauss_pyr, int octvs, int intvls )  
  2. {  
  3.   IplImage*** dog_pyr;  
  4.   int i, o;  
  5.   
  6.   dog_pyr = calloc( octvs, sizeof( IplImage** ) );  
  7.   for( i = 0; i < octvs; i++ )  
  8.     dog_pyr[i] = calloc( intvls + 2, sizeof(IplImage*) );  
  9.   
  10.   for( o = 0; o < octvs; o++ )  
  11.     for( i = 0; i < intvls + 2; i++ )  
  12.       {  
  13.     dog_pyr[o][i] = cvCreateImage( cvGetSize(gauss_pyr[o][i]),  
  14.                        IPL_DEPTH_32F, 1 );  
  15.     cvSub( gauss_pyr[o][i+1], gauss_pyr[o][i], dog_pyr[o][i], NULL );   //相鄰兩層圖像相減,結果放在dog_pyr數組內  
  16.       }  
  17.   
  18.   return dog_pyr;  
  19. }  


 4.關鍵點搜索與定位

  在DOG尺度空間上,首先尋找極值點,插值處理,找到準確的極值點座標,再排除不穩定的特徵點(邊界點)
  1. /* 
  2.   Detects features at extrema in DoG scale space.  Bad features are discarded 
  3.   based on contrast and ratio of principal curvatures. 
  4.  
  5.   @return Returns an array of detected features whose scales, orientations, 
  6.     and descriptors are yet to be determined. 
  7. */  
  8. static CvSeq* scale_space_extrema( IplImage*** dog_pyr, int octvs, int intvls,  
  9.                    double contr_thr, int curv_thr,  
  10.                    CvMemStorage* storage )  
  11. {  
  12.   CvSeq* features;  
  13.   double prelim_contr_thr = 0.5 * contr_thr / intvls; //極值比較前的閾值處理  
  14.   struct feature* feat;  
  15.   struct detection_data* ddata;  
  16.   int o, i, r, c;  
  17.   
  18.   features = cvCreateSeq( 0, sizeof(CvSeq), sizeof(struct feature), storage );  
  19.   for( o = 0; o < octvs; o++ )                     //對DOG尺度空間上,遍歷從第二層圖像開始到倒數第二層圖像上,每個像素點  
  20.     for( i = 1; i <= intvls; i++ )  
  21.       for(r = SIFT_IMG_BORDER; r < dog_pyr[o][0]->height-SIFT_IMG_BORDER; r++)          
  22.     for(c = SIFT_IMG_BORDER; c < dog_pyr[o][0]->width-SIFT_IMG_BORDER; c++)  
  23.       /* perform preliminary check on contrast */  
  24.       if( ABS( pixval32f( dog_pyr[o][i], r, c ) ) > prelim_contr_thr )    // 排除像素值小於閾值prelim_contr_thr的點,提高穩定性  
  25.         if( is_extremum( dog_pyr, o, i, r, c ) )             //與周圍26個像素值比較,是否極大值或者極小值點  
  26.           {  
  27.         feat = interp_extremum(dog_pyr, o, i, r, c, intvls, contr_thr); //插值處理,找到準確的特徵點座標  
  28.         if( feat )  
  29.           {  
  30.             ddata = feat_detection_data( feat );  
  31.             if( ! is_too_edge_like( dog_pyr[ddata->octv][ddata->intvl],   //根據Hessian矩陣 判斷是否爲邊緣上的點  
  32.                         ddata->r, ddata->c, curv_thr ) )  
  33.               {  
  34.             cvSeqPush( features, feat );          //是特徵點進入特徵點序列  
  35.               }  
  36.             else  
  37.               free( ddata );  
  38.             free( feat );  
  39.           }  
  40.           }  
  41.     
  42.   return features;  
  43. }  

4.1

尋找極值點

在DOG尺度空間上,每組有S+2層圖像,每一組都從第二層開始每一個像素點都要與它相鄰的像素點比較,看是否比它在圖像域或尺度域的所有點的值大或者小。與它同尺度的相鄰像素點有8個,上下相鄰尺度的點共有2×9=18,共有26個像素點。也就在一個3×3的立方體內進行。搜索的過程是第二層開始到倒數第二層結束,共檢測了octave組,每組S層。
  
  1. /* 
  2.   Determines whether a pixel is a scale-space extremum by comparing it to it's 
  3.   3x3x3 pixel neighborhood. 
  4. */  
  5. static int is_extremum( IplImage*** dog_pyr, int octv, int intvl, int r, int c )  
  6. {  
  7.   double val = pixval32f( dog_pyr[octv][intvl], r, c );  
  8.   int i, j, k;  
  9.   
  10.   /* check for maximum */  
  11.   if( val > 0 )  
  12.     {  
  13.       for( i = -1; i <= 1; i++ )  
  14.     for( j = -1; j <= 1; j++ )  
  15.       for( k = -1; k <= 1; k++ )  
  16.         if( val < pixval32f( dog_pyr[octv][intvl+i], r + j, c + k ) )  
  17.           return 0;  
  18.     }  
  19.   
  20.   /* check for minimum */  
  21.   else  
  22.     {  
  23.       for( i = -1; i <= 1; i++ )  
  24.     for( j = -1; j <= 1; j++ )  
  25.       for( k = -1; k <= 1; k++ )  
  26.         if( val > pixval32f( dog_pyr[octv][intvl+i], r + j, c + k ) )  
  27.           return 0;  
  28.     }  
  29.   
  30.   return 1;  
  31. }  

4.2

準確定位特徵點

      以上的極值點搜索是在離散空間進行的,極值點不真正意義上的極值點。通過對空間尺度函數擬合,可以得到亞像素級像素點座標。
尺度空間的Taylor展開式:
                                      ,其中
求導並令其爲0,得到亞像素級:
                                           
對應的函數值爲:
                                        

 
是一個三維矢量,矢量在任何一個方向上的偏移量大於0.5時,意味着已經偏離了原像素點,這樣的特徵座標位置需要更新或者繼續插值計算。算法實現過程中,爲了保證插值能夠收斂,設置了最大插值次數(lowe 設置了5次)。同時當時(本文閾值採用了0.04/S) ,特徵點才被保留,因爲響應值過小的點,容易受噪聲的干擾而不穩定。
對離散空間進行函數擬合(插值):
  1. /* 
  2.   Performs one step of extremum interpolation.  Based on Eqn. (3) in Lowe's 
  3.   paper. 
  4.  
  5.   r,c 爲特徵點位置,xi,xr,xc,保存三個方向的偏移量 
  6. */  
  7.   
  8. static void interp_step( IplImage*** dog_pyr, int octv, int intvl, int r, int c,  
  9.              double* xi, double* xr, double* xc )  
  10. {  
  11.   CvMat* dD, * H, * H_inv, X;  
  12.   double x[3] = { 0 };  
  13.     
  14.   dD = deriv_3D( dog_pyr, octv, intvl, r, c );      //計算三個方向的梯度  
  15.   H = hessian_3D( dog_pyr, octv, intvl, r, c );    // 計算3維空間的hessian矩陣  
  16.   H_inv = cvCreateMat( 3, 3, CV_64FC1 );  
  17.   cvInvert( H, H_inv, CV_SVD );           //計算逆矩陣  
  18.   cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP );  
  19.   cvGEMM( H_inv, dD, -1, NULL, 0, &X, 0 );   //廣義乘法   
  20.     
  21.   cvReleaseMat( &dD );  
  22.   cvReleaseMat( &H );  
  23.   cvReleaseMat( &H_inv );  
  24.   
  25.   *xi = x[2];  
  26.   *xr = x[1];  
  27.   *xc = x[0];  
  28. }  
  1. /* 
  2.   Interpolates a scale-space extremum's location and scale to subpixel 
  3.   accuracy to form an image feature.  
  4. */  
  5. static struct feature* interp_extremum( IplImage*** dog_pyr, int octv,          //通過擬合求取準確的特徵點位置  
  6.                     int intvl, int r, int c, int intvls,  
  7.                     double contr_thr )  
  8. {  
  9.   struct feature* feat;  
  10.   struct detection_data* ddata;  
  11.   double xi, xr, xc, contr;  
  12.   int i = 0;  
  13.     
  14.   while( i < SIFT_MAX_INTERP_STEPS )   //在最大迭代次數範圍內進行  
  15.     {  
  16.       interp_step( dog_pyr, octv, intvl, r, c, &xi, &xr, &xc );          //插值後得到的三個方向的偏移量(xi,xr,xc)  
  17.       if( ABS( xi ) < 0.5  &&  ABS( xr ) < 0.5  &&  ABS( xc ) < 0.5 )  
  18.     break;  
  19.         
  20.       c += cvRound( xc );    //更新位置  
  21.       r += cvRound( xr );  
  22.       intvl += cvRound( xi );  
  23.         
  24.       if( intvl < 1  ||                            
  25.       intvl > intvls  ||  
  26.       c < SIFT_IMG_BORDER  ||  
  27.       r < SIFT_IMG_BORDER  ||  
  28.       c >= dog_pyr[octv][0]->width - SIFT_IMG_BORDER  ||  
  29.       r >= dog_pyr[octv][0]->height - SIFT_IMG_BORDER )  
  30.     {  
  31.       return NULL;  
  32.     }  
  33.         
  34.       i++;  
  35.     }  
  36.     
  37.   /* ensure convergence of interpolation */  
  38.   if( i >= SIFT_MAX_INTERP_STEPS )     
  39.     return NULL;  
  40.     
  41.   contr = interp_contr( dog_pyr, octv, intvl, r, c, xi, xr, xc );     //計算插值後對應的函數值  
  42.   if( ABS( contr ) < contr_thr / intvls )   //小於閾值(0.04/S)的點,則丟棄  
  43.     return NULL;  
  44.   
  45.   feat = new_feature();  
  46.   ddata = feat_detection_data( feat );  
  47.   feat->img_pt.x = feat->x = ( c + xc ) * pow( 2.0, octv );       // 計算特徵點根據降採樣的次數對應於原圖中位置  
  48.   feat->img_pt.y = feat->y = ( r + xr ) * pow( 2.0, octv );  
  49.   ddata->r = r;                  // 在本尺度內的座標位置  
  50.   ddata->c = c;  
  51.   ddata->octv = octv;                 //組信息  
  52.   ddata->intvl = intvl;                 // 層信息  
  53.   ddata->subintvl = xi;              // 層方向的偏移量  
  54.   
  55.   return feat;  
  56. }  


4.3

刪除邊緣效應

爲了得到穩定的特徵點,要刪除掉落在圖像邊緣上的點。一個落在邊緣上的點,可以根據主曲率計算判斷。主曲率可以通過2維的 Hessian矩陣求出;

在邊緣上的點,必定使得Hessian矩陣的兩個特徵值相差比較大,而特徵值與矩陣元素有以下關係;

令α=rβ ,所以有:

我們可以判斷上述公式的比值大小,大於閾值(lowe採用 r =10)的點排除。
  1. static int is_too_edge_like( IplImage* dog_img, int r, int c, int curv_thr )  
  2. {  
  3.   double d, dxx, dyy, dxy, tr, det;  
  4.   
  5.   /* principal curvatures are computed using the trace and det of Hessian */              
  6.   d = pixval32f(dog_img, r, c);                                                                             //計算Hessian 矩陣內的4個元素值  
  7.   dxx = pixval32f( dog_img, r, c+1 ) + pixval32f( dog_img, r, c-1 ) - 2 * d;  
  8.   dyy = pixval32f( dog_img, r+1, c ) + pixval32f( dog_img, r-1, c ) - 2 * d;  
  9.   dxy = ( pixval32f(dog_img, r+1, c+1) - pixval32f(dog_img, r+1, c-1) -  
  10.       pixval32f(dog_img, r-1, c+1) + pixval32f(dog_img, r-1, c-1) ) / 4.0;  
  11.   tr = dxx + dyy;                          //矩陣的跡  
  12.   det = dxx * dyy - dxy * dxy;     //矩陣的值  
  13.   
  14.   /* negative determinant -> curvatures have different signs; reject feature */  
  15.   if( det <= 0 )     // 矩陣值爲負值,說明曲率有不同符號,丟棄  
  16.     return 1;  
  17.   
  18.   if( tr * tr / det < ( curv_thr + 1.0 )*( curv_thr + 1.0 ) / curv_thr )   //比值小於閾值的特徵點被保留  curv_thr = 10  
  19.     return 0;  
  20.   return 1;  
  21. }  

 5.計算特徵點對應的尺度

  1. static void calc_feature_scales( CvSeq* features, double sigma, int intvls )  
  2. {  
  3.   struct feature* feat;  
  4.   struct detection_data* ddata;  
  5.   double intvl;  
  6.   int i, n;  
  7.   
  8.   n = features->total;  
  9.   for( i = 0; i < n; i++ )  
  10.     {  
  11.       feat = CV_GET_SEQ_ELEM( struct feature, features, i );  
  12.       ddata = feat_detection_data( feat );  
  13.       intvl = ddata->intvl + ddata->subintvl;                          
  14.       feat->scl = sigma * pow( 2.0, ddata->octv + intvl / intvls );      // feat->scl 保存特徵點在總體上尺度  
  15.       ddata->scl_octv = sigma * pow( 2.0, intvl / intvls );     // feat->feature_data->scl__octv 保存特徵點在組內的尺度,用來下面計算方向角  
  16.     }  
  17. }  


 6.爲特徵點分配方向角

這部分包括:計算鄰域內梯度直方圖,平滑直方圖,複製特徵點(有輔方向的特徵點)
  1. static void calc_feature_oris( CvSeq* features, IplImage*** gauss_pyr )    
  2. {  
  3.   struct feature* feat;  
  4.   struct detection_data* ddata;  
  5.   double* hist;  
  6.   double omax;  
  7.   int i, j, n = features->total;  
  8.   
  9.   for( i = 0; i < n; i++ )  
  10.     {  
  11.       feat = malloc( sizeofstruct feature ) );  
  12.       cvSeqPopFront( features, feat );  
  13.       ddata = feat_detection_data( feat );  
  14.       hist = ori_hist( gauss_pyr[ddata->octv][ddata->intvl],     // 計算鄰域內的梯度直方圖,鄰域半徑radius = 3*1.5*sigma;  高斯加權係數= 1.5 *sigma   
  15.                ddata->r, ddata->c, SIFT_ORI_HIST_BINS,  
  16.                cvRound( SIFT_ORI_RADIUS * ddata->scl_octv ),  
  17.                SIFT_ORI_SIG_FCTR * ddata->scl_octv );  
  18.       for( j = 0; j < SIFT_ORI_SMOOTH_PASSES; j++ )  
  19.     smooth_ori_hist( hist, SIFT_ORI_HIST_BINS );    // 對直方圖平滑  
  20.       omax = dominant_ori( hist, SIFT_ORI_HIST_BINS ); // 返回直方圖的主方向  
  21.       add_good_ori_features( features, hist, SIFT_ORI_HIST_BINS,//大於主方向的80%爲輔方向  
  22.                  omax * SIFT_ORI_PEAK_RATIO, feat );  
  23.       free( ddata );  
  24.       free( feat );  
  25.       free( hist );  
  26.     }  
  27. }  

6.1

建立特徵點鄰域內的直方圖

上一步scl_octv保存了每個特徵點所在的組內尺度,下面計算特徵點所在尺度內的高斯圖像,以3×1.5×scl_octv爲半徑的區域內的所有像素點的梯度幅值與幅角;
計算公式:

在計算完所有特徵點的幅值與幅角後,使用直方圖統計。直方圖橫軸爲梯度方向角,縱軸爲對應幅值的累加值(與權重),梯度方向範圍爲0~360度,劃分爲36個bin,每個bin的寬度爲10。
下圖描述的劃分爲8個bin,每個bin的寬度爲45的效果圖:

其次,每個被加入直方圖的幅值,要進行權重處理,權重也是採用高斯加權函數,其中高斯係數爲1.5×scl_octv。通過高斯加權使特徵點附近的點有較大的權重,可以彌補部分因沒有仿射不變性而產生的不穩定問題;
即每個bin值按下面的公式累加,mag是幅值,後面爲權重;i,j,爲偏離特徵點距離:

程序上可以幫助你理解上面的概念:
  1. static double* ori_hist( IplImage* img, int r, int c, int n, int rad,  
  2.              double sigma )  
  3. {  
  4.   double* hist;  
  5.   double mag, ori, w, exp_denom, PI2 = CV_PI * 2.0;  
  6.   int bin, i, j;  
  7.   
  8.   hist = calloc( n, sizeofdouble ) );  
  9.   exp_denom = 2.0 * sigma * sigma;  
  10.   for( i = -rad; i <= rad; i++ )  
  11.     for( j = -rad; j <= rad; j++ )  
  12.       if( calc_grad_mag_ori( img, r + i, c + j, &mag, &ori ) )    //計算領域像素點的梯度幅值mag與方向ori  
  13.     {  
  14.       w = exp( -( i*i + j*j ) / exp_denom );                    //高斯權重  
  15.       bin = cvRound( n * ( ori + CV_PI ) / PI2 );  
  16.       bin = ( bin < n )? bin : 0;  
  17.       hist[bin] += w * mag;                             //直方圖上累加  
  18.     }  
  19.   
  20.   return hist;  //返回累加完成的直方圖  
  21. }  
6.2

平滑直方圖

lowe建議對直方圖進行平滑,減少突變的影響。
  1. static void smooth_ori_hist( double* hist, int n )  
  2. {  
  3.   double prev, tmp, h0 = hist[0];  
  4.   int i;  
  5.   
  6.   prev = hist[n-1];  
  7.   for( i = 0; i < n; i++ )  
  8.     {  
  9.       tmp = hist[i];  
  10.       hist[i] = 0.25 * prev + 0.5 * hist[i] +   
  11.     0.25 * ( ( i+1 == n )? h0 : hist[i+1] );  
  12.       prev = tmp;  
  13.     }  
  14. }  
6.3

複製特徵點

在上面的直方圖上,我們已經找到了特徵點主方向的峯值omax,當存在另一個大於主峯值80%的峯值時,將這個方向作爲特徵點的輔方向,即一個特徵點有多個方向,這可以增強匹配的魯棒性。在算法上,即把該特徵點複製多份作爲新的特徵點,新特徵點的方向爲這些輔方向,其他屬性保持一致。
  1. static void add_good_ori_features( CvSeq* features, double* hist, int n,  
  2.                    double mag_thr, struct feature* feat )  
  3. {  
  4.   struct feature* new_feat;  
  5.   double bin, PI2 = CV_PI * 2.0;  
  6.   int l, r, i;  
  7.   
  8.   for( i = 0; i < n; i++ )                   //檢查所有的方向  
  9.     {  
  10.       l = ( i == 0 )? n - 1 : i-1;  
  11.       r = ( i + 1 ) % n;  
  12.         
  13.       if( hist[i] > hist[l]  &&  hist[i] > hist[r]  &&  hist[i] >= mag_thr ) //判斷是不是幅方向  
  14.     {  
  15.       bin = i + interp_hist_peak( hist[l], hist[i], hist[r] );     //插值離散處理,取得更精確的方向  
  16.       bin = ( bin < 0 )? n + bin : ( bin >= n )? bin - n : bin;  
  17.       new_feat = clone_feature( feat );       //複製特徵點  
  18.       new_feat->ori = ( ( PI2 * bin ) / n ) - CV_PI;//  爲特徵點方向賦值[-180,180]  
  19.       cvSeqPush( features, new_feat );  //  
  20.       free( new_feat );  
  21.     }  
  22.     }  
  23. }  

 7.構建特徵描述子

目前每個特徵點具有屬性有位置、方向、尺度三個信息,現在要用一個向量去描述這個特徵點,使其具有高度的唯一特徵性。
1.lowe採用了把特徵點鄰域劃分成 d×d (lowe建議d=4) 個子區域,然後再統計每個子區域的方向直方圖(8個方向),直方圖橫軸有8個bin,縱軸爲梯度幅值(×權重)的累加。這樣描述這個特徵點的向量爲4×4×8=128維。每個子區域的寬度建議爲3×octv,octv爲組內的尺度。考慮到插值問題,特徵點的鄰域範圍邊長爲3×octv×(d+1),考慮到旋轉問題,鄰域的範圍邊長爲3×octv×(d+1)×sqrt(2),最後半徑爲:

2.把座標系旋轉到主方向位置,再次統計鄰域內所有像素點的梯度幅值與方向,計算所在子區域,並把幅值×權重累加到這個子區域的直方圖上。
算法上即統計每個鄰域的方向直方圖時,全部是相對於這個特徵點的主方向的方向。如果主方向爲30度,某個像素點的梯度方向爲50度,這時統計到該子區域直方圖上就成了20度。同時由於旋轉,這時權重也必須是按旋轉後的座標。

計算所在的子區域的位置:
  
權重按高斯加權函數,係數爲描述子寬度的一半,即0.5d:
  1. static double*** descr_hist( IplImage* img, int r, int c, double ori,  
  2.                  double scl, int d, int n )  
  3. {  
  4.   double*** hist;  
  5.   double cos_t, sin_t, hist_width, exp_denom, r_rot, c_rot, grad_mag,  
  6.     grad_ori, w, rbin, cbin, obin, bins_per_rad, PI2 = 2.0 * CV_PI;  
  7.   int radius, i, j;  
  8.   
  9.   hist = calloc( d, sizeofdouble** ) );  
  10.   for( i = 0; i < d; i++ )  
  11.     {  
  12.       hist[i] = calloc( d, sizeofdouble* ) );  
  13.       for( j = 0; j < d; j++ )  
  14.     hist[i][j] = calloc( n, sizeofdouble ) );  
  15.     }  
  16.     
  17.   cos_t = cos( ori );  
  18.   sin_t = sin( ori );  
  19.   bins_per_rad = n / PI2;  
  20.   exp_denom = d * d * 0.5;  
  21.   hist_width = SIFT_DESCR_SCL_FCTR * scl;  
  22.   radius = hist_width * sqrt(2) * ( d + 1.0 ) * 0.5 + 0.5;   //計算鄰域範圍半徑,+0.5爲了取得更多元素  
  23.   for( i = -radius; i <= radius; i++ )  
  24.     for( j = -radius; j <= radius; j++ )  
  25.       {  
  26.     /* 
  27.       Calculate sample's histogram array coords rotated relative to ori. 
  28.       Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e. 
  29.       r_rot = 1.5) have full weight placed in row 1 after interpolation. 
  30.     */  
  31.     c_rot = ( j * cos_t - i * sin_t ) / hist_width;              //  
  32.     r_rot = ( j * sin_t + i * cos_t ) / hist_width;  
  33.     rbin = r_rot + d / 2 - 0.5;                                        //旋轉後對應的x``及y''  
  34.     cbin = c_rot + d / 2 - 0.5;  
  35.       
  36.     if( rbin > -1.0  &&  rbin < d  &&  cbin > -1.0  &&  cbin < d )  
  37.       if( calc_grad_mag_ori( img, r + i, c + j, &grad_mag, &grad_ori ))       //計算每一個像素點的梯度方向、幅值、  
  38.         {  
  39.           grad_ori -= ori;              //每個像素點相對於特徵點的梯度方向  
  40.           while( grad_ori < 0.0 )  
  41.         grad_ori += PI2;  
  42.           while( grad_ori >= PI2 )  
  43.         grad_ori -= PI2;  
  44.             
  45.           obin = grad_ori * bins_per_rad;     //像素梯度方向轉換成8個方向  
  46.           w = exp( -(c_rot * c_rot + r_rot * r_rot) / exp_denom );     //每個子區域內像素點,對應的權重  
  47.           interp_hist_entry( hist, rbin, cbin, obin, grad_mag * w, d, n );   //爲了減小突變影響對附近三個bin值三線性插值處理  
  48.         }  
  49.       }  
  50.   
  51.   return hist;  
  52. }  
每個維度上bin值累加方法,即計算一個像素的幅值對於相鄰的方向,以及位置的貢獻,dr,dc爲相鄰位置,do爲相鄰方向
這就是128維向量的數據,計算方法
  1. static void interp_hist_entry( double*** hist, double rbin, double cbin,  
  2.                    double obin, double mag, int d, int n )  
  3. {  
  4.   double d_r, d_c, d_o, v_r, v_c, v_o;  
  5.   double** row, * h;  
  6.   int r0, c0, o0, rb, cb, ob, r, c, o;  
  7.   
  8.   r0 = cvFloor( rbin );  
  9.   c0 = cvFloor( cbin );  
  10.   o0 = cvFloor( obin );  
  11.   d_r = rbin - r0;  
  12.   d_c = cbin - c0;  
  13.   d_o = obin - o0;  
  14.   
  15.   /* 
  16.     The entry is distributed into up to 8 bins.  Each entry into a bin 
  17.     is multiplied by a weight of 1 - d for each dimension, where d is the 
  18.     distance from the center value of the bin measured in bin units. 
  19.   */  
  20.   for( r = 0; r <= 1; r++ )  
  21.     {  
  22.       rb = r0 + r;  
  23.       if( rb >= 0  &&  rb < d )  
  24.     {  
  25.       v_r = mag * ( ( r == 0 )? 1.0 - d_r : d_r );  
  26.       row = hist[rb];  
  27.       for( c = 0; c <= 1; c++ )  
  28.         {  
  29.           cb = c0 + c;  
  30.           if( cb >= 0  &&  cb < d )  
  31.         {  
  32.           v_c = v_r * ( ( c == 0 )? 1.0 - d_c : d_c );  
  33.           h = row[cb];  
  34.           for( o = 0; o <= 1; o++ )  
  35.             {  
  36.               ob = ( o0 + o ) % n;  
  37.               v_o = v_c * ( ( o == 0 )? 1.0 - d_o : d_o );  
  38.               h[ob] += v_o;  
  39.             }  
  40.         }  
  41.         }  
  42.     }  
  43.     }  
  44. }  
最後爲了去除光照的影響,對128維向量進行歸一化處理,同時設置門限,大於0.2的梯度幅值截斷
  1. static void hist_to_descr( double*** hist, int d, int n, struct feature* feat )  
  2. {  
  3.   int int_val, i, r, c, o, k = 0;  
  4.   
  5.   for( r = 0; r < d; r++ )  
  6.     for( c = 0; c < d; c++ )  
  7.       for( o = 0; o < n; o++ )  
  8.     feat->descr[k++] = hist[r][c][o];  
  9.   
  10.   feat->d = k;  
  11.   normalize_descr( feat );          //向量歸一化  
  12.   for( i = 0; i < k; i++ )  
  13.     if( feat->descr[i] > SIFT_DESCR_MAG_THR )   //設置門限,門限爲0.2  
  14.       feat->descr[i] = SIFT_DESCR_MAG_THR;  
  15.   normalize_descr( feat );      //向量歸一化  
  16.   
  17.   /* convert floating-point descriptor to integer valued descriptor */  
  18.   for( i = 0; i < k; i++ )              //換成整形值  
  19.     {  
  20.       int_val = SIFT_INT_DESCR_FCTR * feat->descr[i];      
  21.       feat->descr[i] = MIN( 255, int_val );  
  22.     }  
  23. }  

最後對特徵點按尺度大小進行排序,強特徵點放在前面;
這樣每個特徵點就對應一個128維的向量,接下來可以用可以用向量做以後的匹配工作了。

特徵點匹配原理後序文章會更新~

------------------------------------------------------------------------------------

在此非常感謝CSDN上幾位圖像上的大牛,我也是通過他們的文章去學習研究的,本文也是參考了他們的文章才寫成

推薦看大牛們的文章,原理寫的很好!

http://blog.csdn.net/abcjennifer/article/details/7639681

http://blog.csdn.Net/zddblog/article/details/7521424

http://blog.csdn.net/chen825919148/article/details/7685952

http://blog.csdn.net/xiaowei_cqu/article/details/8069548


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章