【OpenCV學習筆記】三十七、特徵檢測與匹配(二)——SIFT特徵點匹配
阿新 • • 發佈:2018-12-31
特徵檢測與匹配(二)——SIFT特徵點匹配
1.SIFT特徵點提取
2.繪製特徵點
3.特徵點描述符(特徵向量)提取
4.使用暴力匹配器進行暴力匹配
5.對匹配結果進行篩選(依據DMatch結構體中的float型別變數distance進行篩選)
6.繪製匹配結果
先上ppt:
程式碼:SIFT特徵點匹配
///SIFT特徵點匹配 #include "opencv2/opencv.hpp" using namespace cv; #include "opencv2/nonfree/nonfree.hpp"//SIFT相關 #include "opencv2/legacy/legacy.hpp"//匹配器相關 #include <iostream> using namespace std; int main() { //1.SIFT特徵點提取——detect()方法 Mat srcImg1 = imread("1.jpg", CV_LOAD_IMAGE_COLOR); Mat srcImg2 = imread("2.jpg", CV_LOAD_IMAGE_COLOR); Mat dstImg1, dstImg2; SiftFeatureDetector siftDetector;//SiftFeatureDetector是SIFT類的別名 vector<KeyPoint> keyPoints1; vector<KeyPoint> keyPoints2; siftDetector.detect(srcImg1, keyPoints1); siftDetector.detect(srcImg2, keyPoints2); drawKeypoints(srcImg1, keyPoints1, dstImg1); drawKeypoints(srcImg2, keyPoints2, dstImg2); imshow("dstImg1", dstImg1); imshow("dstImg2", dstImg2); //2.特徵點描述符(特徵向量)提取——compute()方法 SiftDescriptorExtractor descriptor;//SiftDescriptorExtractor是SIFT類的別名 Mat description1; Mat description2; descriptor.compute(srcImg1, keyPoints1, description1);//注意原圖和特徵點要對應,不要寫錯 descriptor.compute(srcImg2, keyPoints2, description2); imshow("description1", description1); imshow("description2", description2); //3.使用暴力匹配器進行暴力匹配——BruteForceMatcher類的match()方法 BruteForceMatcher<L2<float>> matcher;//例項化暴力匹配器 vector<DMatch> matches; //定義匹配結果變數 matcher.match(description1, description2, matches);//實現描述符之間的匹配 //4.對匹配結果進行篩選(依據DMatch結構體中的float型別變數distance進行篩選) float minDistance = 100; float maxDistance = 0; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance < minDistance) minDistance = matches[i].distance; if (matches[i].distance > maxDistance) maxDistance = matches[i].distance; } cout << "minDistance: " << minDistance << endl; cout << "maxDistance: " << maxDistance << endl; vector<DMatch> goodMatches; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance < 2 * minDistance) { goodMatches.push_back(matches[i]); } } //5.繪製匹配結果——drawMatches() Mat dstImg3; drawMatches(srcImg1, keyPoints1, srcImg2, keyPoints2, goodMatches, dstImg3); imshow("dstImg3", dstImg3); waitKey(0); return 0; }
執行結果: