opencv 特徵點匹配 ORB、SURF、SIFT 以及 RANSAC 過濾的範例代碼
void sift1(string name1, string name2){
Mat img_1 = imread(name1, CV_LOAD_IMAGE_GRAYSCALE);
Mat img_2 = imread(name2, CV_LOAD_IMAGE_GRAYSCALE);
Mat img_matches;
Mat img_test;
if(!img_1.data || !img_2.data){
cout << "opencv error" << endl;
return;
}
cv::Ptr<Feature2D> f2d = ORB::create();
std::vector<KeyPoint> keypoints_1, keypoints_2;
f2d->detect(img_1, keypoints_1);
f2d->detect(img_2, keypoints_2);
img_test = img_1;
drawKeypoints(img_1, keypoints_1, img_test, Scalar::all(-1));
imshow("Keypoints", img_test);
Mat descriptors_1, descriptors_2;
f2d->compute(img_1, keypoints_1, descriptors_1);
f2d->compute(img_2, keypoints_2, descriptors_2);
BFMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_1, descriptors_2, matches);
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
imshow("Matches", img_matches);
double max_dist = 0; double min_dist = 100;
for(int i = 0; i < descriptors_1.rows; i++){
double dist = matches[i].distance;
if(dist < min_dist) min_dist = dist;
if(dist > max_dist) max_dist = dist;
}
printf("-- Max dist : %f \n", max_dist);
printf("-- Min dist : %f \n", min_dist);
std::vector< DMatch > good_matches;
for(int i = 0; i < descriptors_1.rows; i++){
if(matches[i].distance < 3 * min_dist)
good_matches.push_back(matches[i]);
}
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
imshow("Good Matches", img_matches);
vector<DMatch>& Input_matches = matches;
vector<Point2f> featPoint1;
vector<Point2f> featPoint2;
for(size_t i = 0; i < Input_matches.size(); i++){
featPoint1.push_back(keypoints_1[Input_matches[i].queryIdx].pt);
featPoint2.push_back(keypoints_2[Input_matches[i].trainIdx].pt);
}
vector<char> RANSAC_mask;
Mat Hog = findHomography(featPoint1, featPoint2, RANSAC, 3, RANSAC_mask, 2000, 0.995);
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
Input_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
RANSAC_mask, DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
imshow("RANSAC Matches", img_matches);
waitKey(0);
}