计算机视觉—OpenCV中的SIFT(应用)
brycezou@163.com
#include <opencv2/opencv.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
if(argc != 3)
{
cout<<"only two args are needed, usage: ./xx img1 img2"<<endl;
return -1;
}
//首先,加载输入图像
Mat input1 = imread(argv[1], 1);
Mat input2 = imread(argv[2], 1);
if(input1.empty() || input2.empty())
{
cout<<"can\'t read image"<<endl;
return -1;
}
//其次,提取关键点
SiftFeatureDetector sift_detector;
vector<KeyPoint> key_pt1;
Mat output1;
sift_detector.detect(input1, key_pt1);
drawKeypoints(input1, key_pt1, output1);
imshow("key points detected in inputs1", output1);
cout << "key points\' number in inputs1:" << key_pt1.size() << endl;
vector<KeyPoint> key_pt2;
Mat output2;
sift_detector.detect(input2, key_pt2);
drawKeypoints(input2, key_pt2, output2);
imshow("key points detected in inputs2", output2);
cout << "key points\' number in inputs2:" << key_pt2.size() << endl;
//然后,提取关键点的特征描述子
SiftDescriptorExtractor sift_descriptor;
Mat description1;
sift_descriptor.compute(input1, key_pt1, description1);
Mat description2;
sift_descriptor.compute(input2, key_pt2, description2);
//然后,匹配特征点
FlannBasedMatcher matcher;
vector<DMatch> all_matches;
matcher.match(description1, description2, all_matches);
//再次,计算最大与最小距离
double max_dist = -1, min_dist = 65535;
for(int i = 0; i < description1.rows; i++)
{
if (all_matches.at(i).distance > max_dist)
{
max_dist = all_matches[i].distance;
}
if (all_matches[i].distance < min_dist)
{
min_dist = all_matches[i].distance;
}
}
cout<<"min_dist:"<<min_dist<<endl;
cout<<"max_dist:"<<max_dist<<endl;
//最后,仅保留好的特征匹配点
vector<DMatch> good_matches;
for(int i = 0; i < all_matches.size(); i++)
{
if(all_matches[i].distance < (19*min_dist+max_dist)/10)
{
good_matches.push_back(all_matches[i]);
cout<<"第一个图中的"<<all_matches[i].queryIdx
<<"匹配了第二个图中的"<<all_matches[i].trainIdx<<endl;
}
}
Mat image_match;
drawMatches(input1, key_pt1, input2, key_pt2, good_matches, image_match);
imshow("匹配后的图片", image_match);
imwrite("result.jpg" ,image_match);
cout<<"匹配的特征点数为:"<<good_matches.size()<< endl;
waitKey(0);
return 0;
}
##在QT下开发代码,需要添加依赖
INCLUDEPATH += /usr/local/include
LIBS += -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_features2d -lopencv_calib3d
LIBS += -L/usr/local/lib -lopencv_nonfree -lopencv_flann
SOURCES += main.cpp