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
| #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d/nonfree.hpp> #include <opencv2/features2d.hpp>
using namespace std; using namespace cv; using namespace cv::xfeatures2d;
const int MAX_FEATURES = 500; const float GOOD_MATCH_PERCENT = 0.15f;
void alignImage(Mat& img1, Mat& img2, Mat& dst, Mat h) { Mat img1Gray, img2Gray;//灰度图 cvtColor(img1, img1Gray, COLOR_BGR2GRAY); cvtColor(img2, img2Gray, COLOR_BGR2GRAY);//灰度处理
vector<KeyPoint> keypoints1, keypoints2;//图1 关键点 图2 关键点 Mat descriptors1, descriptors2; Ptr<Feature2D> orb = ORB::create(MAX_FEATURES);
orb->detectAndCompute(img1Gray, Mat(), keypoints1, descriptors1);//检测匹配
orb->detectAndCompute(img2Gray, Mat(), keypoints2, descriptors2);//检测匹配
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;
matches.erase(matches.begin() + numGoodMatches, matches.end());
Mat imMatches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, imMatches); imshow("match", imMatches); imwrite("F:\\match.jpg", imMatches); vector<Point2f> points1, points2; for (auto x : matches) { points1.push_back(keypoints1[x.queryIdx].pt); points2.push_back(keypoints2[x.trainIdx].pt); }
h = findHomography(points1, points2, RANSAC); warpPerspective(img1, dst, h, img2.size());//旋转矫正
}
int main() { string refFilename="F:\\picture\\src.jpg";//原图路径
Mat src = imread(refFilename); string scanFilename = "F:\\picture\\scanned.jpg";//扫描的或者电子版的图 Mat scan_src = imread(scanFilename);
Mat imageRege, homo;//完成图像 和 homo矩阵 alignImage(src, scan_src, imageRege, homo); cout << homo << endl; imshow("dst", imageRege); imwrite("F:\\change.jpg", imageRege); waitKey();
}
|