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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <opencv2/opencv.hpp> #include <opencv2/features2d.hpp> #include <iostream>
using namespace std; using namespace cv;
float cacSIFTFeatureAndCompare(cv::Mat srcImage1, cv::Mat srcImage2, float paraHessian) { CV_Assert(srcImage1.data != NULL && srcImage2.data != NULL); cv::Mat grayMat1, grayMat2; cv::cvtColor(srcImage1, grayMat1, COLOR_RGB2GRAY); cv::cvtColor(srcImage2, grayMat2, COLOR_RGB2GRAY); cv::Ptr<SIFT> sift = SIFT::create();
vector<cv::KeyPoint> keyPoints1, keyPoints2; cv::Mat descriptorMat1, descriptorMat2;
sift->detectAndCompute(grayMat1, Mat(), keyPoints1, descriptorMat1); sift->detectAndCompute(grayMat2, Mat(), keyPoints2, descriptorMat2); float result = 0; if (keyPoints1.size() > 0 && keyPoints2.size() > 0) { cv::FlannBasedMatcher matcher; vector< cv::DMatch > matches; std::vector<cv::DMatch> viewMatches; matcher.match(descriptorMat1, descriptorMat2, matches); double minDist = 100; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance < minDist) minDist = matches[i].distance; } int num = 0; std::cout << "minDist: " << minDist << std::endl; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance <= 2 * minDist) { result += matches[i].distance * matches[i].distance; viewMatches.push_back(matches[i]); num++; } } result /= num; cv::Mat matchMat; cv::drawMatches(srcImage1, keyPoints1, srcImage2, keyPoints2, matches, matchMat); cv::imshow("matchMat", matchMat); cv::waitKey(0); } return result; } int main() { cv::Mat srcImage1 = cv::imread("box.png", 1); if (srcImage1.empty()) return -1; cv::Mat srcImage2 = cv::imread("box_in_scene.png", 1); if (srcImage2.empty()) return -1; float matchRate = cacSIFTFeatureAndCompare(srcImage1, srcImage2, 1000); std::cout << "matchRate: " << matchRate << std::endl; return 0; }
|