SURFによる特徴点抽出

18 2月 2010 Under: opencv2.x-samples

C++

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string>
 
#include <cv.h>
#include <highgui.h>
 
using namespace std;
using namespace cv;
 
 
int main(int argc, char *argv[])
{
  // (1)load Color Image
  const char *imagename = argc > 1 ? argv[1] : "../image/lenna.png";
  Mat colorImage = imread(imagename,1);
  if(colorImage.empty())
    return -1;
 
  // (2)convert Color Image to Grayscale for Feature Extraction
  Mat grayImage;
  cvtColor(colorImage, grayImage, CV_BGR2GRAY);
 
  // (3)initialize SURF class
  SURF calc_surf = SURF(500,4,2,true);
 
  // (4)extract SURF
  vector<KeyPoint> kp_vec;
  vector<float> desc_vec;    
  calc_surf(grayImage, Mat(), kp_vec, desc_vec);
 
  // (5)draw keypoints
  cout << "Image Keypoints: " << kp_vec.size() << endl;
#if 1
  vector<KeyPoint>::iterator it = kp_vec.begin(), it_end = kp_vec.end();
  for(; it!=it_end; ++it) {
    circle(colorImage, Point(it->pt.x, it->pt.y),
       saturate_cast<int>(it->size*0.25), Scalar(255,255,0));
  }
#else
  for(int i = 0; i < kp_vec.size(); i++) {
    KeyPoint* point = &(kp_vec[i]);
    Point center;  // Key Point's Center
    int radius;      // Radius of Key Point
    center.x = cvRound(point->pt.x);
    center.y = cvRound(point->pt.y);
    radius = cvRound(point->size*0.25);
    circle(colorImage, center, radius, Scalar(255,255,0), 1, 8, 0);
  }
#endif
 
  namedWindow("SURF",CV_WINDOW_AUTOSIZE);
  imshow("SURF", colorImage);
  waitKey(0);
 
  return 0;
}

// (1)指定ファイルをカラー画像として読み込みます.

コマンドライン引数で指定されたファイルを,カラー画像として読み込みます.

// (2)画像を,グレースケールに変換します.

SURF特徴の抽出は,グレースケール画像に対して行う必要があります.cvtColorでカラー画像をCV_8UC1のグレースケール画像に変換します.

// (3)SURFクラスを初期化します.

C++インタフェースではcv::SURFクラスを使用してSURF特徴を抽出します.SURFコンストラクタは,第一引数がFast Hessian Detectorの閾値,第二引数が特徴検出に用いられるオクターブ数,第三引数が各オクターブ内に存在するレイヤ数,第四引数は拡張ディスクリプタの使用有無を指定します.trueにした場合128次元のディスクリプタが取得されます(falseの場合は64次元).

// (4)グレースケール画像からSURF特徴を抽出します.

SURF特徴の抽出結果は,std::vector<cv::KeyPoint>に格納されます.ここには各キーポイントの位置,方向,スケールなどが格納されます.また,第四引数にstd::vector<float>を指定した場合,各キーポイント毎にディスクリプタの抽出処理を行います.拡張ディスクリプタを指定しなかった場合はキーポイントの数×64個の値が,指定した場合はキーポイントの数×128個の値が格納されます.このサンプルでは,kp_vec[i]に格納されたキーポイントに対応するディスクリプタは,desc_vec[128*i]からdesc_vec[128*i + 127]に格納されていることになります.

// (5)抽出したSURF特徴の位置とスケールを,カラー画像上へ描画します.

入力画像(カラー)に対して,SURF特徴の位置とスケールを円で描画します.

実行結果例

Loading...