首页 > 代码库 > 使用Opencv2.4.9进行SIFT特征点提取和匹配

使用Opencv2.4.9进行SIFT特征点提取和匹配

主要使用的类:FeatureDetector FeatureExtractor FeatureMatcher#include <opencv2/core/core.hpp>

?
1
2
3
4
5
6
7
8
9
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
<em id="__mceDel">#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <iostream>
 
using namespace cv;
using namespace std;
 
int main(){
    cv::initModule_nonfree();
    Mat img1_mat = imread("1.bmp",CV_LOAD_IMAGE_GRAYSCALE);
    Mat img2_mat = imread("2.bmp",CV_LOAD_IMAGE_GRAYSCALE);
     
    std::vector<KeyPoint> img1_keypoint,img2_keypoint;<br>
        /*特征点检测*/
//  FeatureDetector *sift_detector = FeatureDetector::create("SIFT");
    Ptr<FeatureDetector> sift_detector = FeatureDetector::create("SIFT");
    sift_detector->detect(img1_mat,img1_keypoint);
    sift_detector->detect(img2_mat,img2_keypoint);<br>
    /*在图片上显示特征点*/
    Mat img_kp_1,img_kp_2;
    drawKeypoints(img1_mat,img1_keypoint,img_kp_1,Scalar::all(-1),DrawMatchesFlags::DEFAULT);
    drawKeypoints(img2_mat,img2_keypoint,img_kp_2,Scalar::all(-1),DrawMatchesFlags::DEFAULT);
    imshow("sift_keypoint_image 1",img_kp_1);
    imshow("sift_keypoint_image 2",img_kp_2);<br>
        /*特征向量提取*/
    Mat img1_descriptor,img2_descriptor;
    Ptr<DescriptorExtractor> sift_descriptor_extractor = DescriptorExtractor::create("SIFT");
    sift_descriptor_extractor->compute(img1_mat,img1_keypoint,img1_descriptor);
    sift_descriptor_extractor->compute(img2_mat,img2_keypoint,img2_descriptor);
        /*特征点匹配*/
    std::vector<DMatch> img_match;
    Ptr<DescriptorMatcher> bruteforce_matcher = DescriptorMatcher::create("BruteForce");
    bruteforce_matcher->match(img1_descriptor,img2_descriptor,img_match);
 
        /*在图片上显示匹配结果*/
    Mat match_img;
    drawMatches(img1_mat,img1_keypoint,img2_mat,img2_keypoint,accurate_match,match_img);
    imshow("match image",match_img);
    waitKey(0);
 
    system("pause");
    return 0;
}
</em>

 需要注意的地方:

如果完全按老版本的opencv的写法会出现下图中Access violation的异常,解决方法如下:

 

1.在新版本的opencv中,像SIFT,SURF等专利方法放在了单独的模块中,使用前需

  a) include <opencv2/nonfree/nonfree.hpp>

  b) 使用前添加语句 cv::initModule_nonfree()

  c) 在链接库中添加 opencv_nonfree2.4.9.lib,一般在配置opencv时已经添加

2.FeatureDetector 等是三个抽象基类,不能直接实例化,也不能直接使用 *,必须用Ptr<>的方式来使用

 Ptr<FeatureDetector> sift_detector = FeatureDetector::create("SIFT");

运行结果如下: