OpenCV2簡單的特征匹配


特征的匹配大致可以分為3個步驟:

  1. 特征的提取
  2. 計算特征向量
  3. 特征匹配

對於3個步驟,在OpenCV2中都進行了封裝。所有的特征提取方法都實現FeatureDetector接口,DescriptorExtractor接口則封裝了對特征向量(特征描述符)的提取,而所有特征向量的匹配都繼承了DescriptorMatcher接口。

簡單的特征匹配

int main()
{
    const string imgName1 = "x://image//01.jpg";
    const string imgName2 = "x://image//02.jpg";

    Mat img1 = imread(imgName1);
    Mat img2 = imread(imgName2);

    if (!img1.data || !img2.data)
        return -1;

    //step1: Detect the keypoints using SURF Detector
    int minHessian = 400;

    SurfFeatureDetector detector(minHessian);

    vector<KeyPoint> keypoints1, keypoints2;

    detector.detect(img1, keypoints1);
    detector.detect(img2, keypoints2);

    //step2: Calculate descriptors (feature vectors)
    SurfDescriptorExtractor extractor;
    Mat descriptors1, descriptors2;
    extractor.compute(img1, keypoints1, descriptors1);
    extractor.compute(img2, keypoints2, descriptors2);

    //step3:Matching descriptor vectors with a brute force matcher
    BFMatcher matcher(NORM_L2);
    vector<DMatch> matches;
    matcher.match(descriptors1, descriptors2,matches);

    //Draw matches
    Mat imgMatches;
    drawMatches(img1, keypoints1, img2, keypoints2, matches, imgMatches);

    namedWindow("Matches");
    imshow("Matches", imgMatches);

    waitKey();

    return 0;
}

 

  1. 實例化了一個特征提取器SurfFeatureDetector,其構造函數參數(minHessian)用來平衡提取到的特征點的數量和特征提取的穩定性的,對於不同的特征提取器改參數具有不同的含義和取值范圍。
  2. 對得到的特征點提取特征向量(特征描述符)
  3. 匹配,上面代碼使用了暴力匹配的方法,最后的匹配結果保存在vector<DMatch>中。

DMatch用來保存匹配后的結果

 

struct DMatch
{         //三個構造函數
    DMatch() :
    queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(std::numeric_limits<float>::max()) {}
    DMatch(int  _queryIdx, int  _trainIdx, float  _distance) :
        queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {}
    DMatch(int  _queryIdx, int  _trainIdx, int  _imgIdx, float  _distance) : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {}
    int queryIdx;  //此匹配對應的查詢圖像的特征描述子索引
    int trainIdx;   //此匹配對應的訓練(模板)圖像的特征描述子索引
    int imgIdx;    //訓練圖像的索引(若有多個)
    float distance;  //兩個特征向量之間的歐氏距離,越小表明匹配度越高。
    bool operator < (const DMatch &m) const;
};

 

然后使用drawMatches方法可以匹配后的結構保存為Mat

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM