很有趣的功能:左边是原始图,右边是结果图,是不是清晰很多。
实现步骤:
//1.模板+用户输入的图
//2.ORB 特征检测,用15%的点做匹配
//3.找H 矩阵
//4.使用透视将拍的照变换到模板上
Mat imReference = imread(path1);
Mat img = imread(path2);
int MAX_FEATURES = 500;
float GOOD_MATCH_PERCENT = 0.15f;
//2.ORB 特征检测,用15%的点做匹配
Mat im1Gray, im2Gray;
cvtColor(img, im1Gray, COLOR_BGR2GRAY);
cvtColor(imReference, im2Gray, COLOR_BGR2GRAY);
vector<KeyPoint> keypoints1, keypoints2;//关键点
Mat descriptors1, descriptors2; //描述子
Ptr<Feature2D> orb = ORB::create(MAX_FEATURES);
orb->detectAndCompute(im1Gray, Mat(), keypoints1, descriptors1);
orb->detectAndCompute(im2Gray, Mat(), keypoints2, descriptors2);
//暴力匹配 15%的点放在容器matches里
vector<DMatch> matches;
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");
matcher->match(descriptors1, descriptors2, matches, Mat());//原始匹配值
sort(matches.begin(), matches.end());
const int numGoodMatches = matches.size() * GOOD_MATCH_PERCENT;//GOOD_MATCH_PERCENT应该是15%
matches.erase(matches.begin() + numGoodMatches, matches.end());//取了前15%,后面的都去掉了
Mat imMatches;// 显示的是两张图 和特征点连线。
drawMatches(img, keypoints1, imReference, keypoints2, matches, imMatches);
//imwrite("matches.jpg", imMatches);
//imshow("matches.jpg", imMatches);
//waitKey(0);
//destroyAllWindows();
//3.找H矩阵 findHomography 输入是point坐标,所以要把描述子->point
vector<Point2f> points1, points2;
for (size_t i = 0; i < matches.size(); i++)
{
points1.push_back(keypoints1[matches[i].queryIdx].pt);
points2.push_back(keypoints2[matches[i].trainIdx].pt);
}
Mat h = findHomography(points1, points2, RANSAC);
//4.使用透视将拍的照变换到模板上
// 原图+H->新图 用warpPerspective函数实现
Mat im1Reg;
warpPerspective(img, im1Reg, h, imReference.size());
imshow("input", img);
imshow("algined Image", im1Reg);
waitKey(0);