写一个orb特征点匹配的c++代码,要求如下:1 将shi-tomasi算法加入 2 加入GMS算法和ransac算法去除误匹配
时间: 2023-06-02 15:02:31 浏览: 113
一种基于ORB的特征匹配算法
由于orb特征点匹配的代码较为复杂,下面只给出主要的代码框架和一些关键点的注释。
首先是包含头文件和命名空间声明:
```c
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>
using namespace cv;
using namespace std;
```
然后是定义主函数:
```c
int main(int argc, char** argv)
{
// 读取图像
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
// 定义ORB特征点检测器
Ptr<ORB> orb = ORB::create();
// 定义Shi-Tomasi角点检测器
int max_corners = 500;
double quality_level = 0.01;
double min_distance = 10;
int block_size = 3;
bool use_harris_detector = false;
double k = 0.04;
vector<Point2f> corners1, corners2;
goodFeaturesToTrack(img1, corners1, max_corners, quality_level, min_distance, Mat(), block_size, use_harris_detector, k);
goodFeaturesToTrack(img2, corners2, max_corners, quality_level, min_distance, Mat(), block_size, use_harris_detector, k);
// 提取ORB特征点
vector<KeyPoint> keypoints1, keypoints2;
orb->detect(img1, keypoints1);
orb->detect(img2, keypoints2);
// 计算ORB描述子
Mat descriptors1, descriptors2;
orb->compute(img1, keypoints1, descriptors1);
orb->compute(img2, keypoints2, descriptors2);
// 匹配ORB特征点
BFMatcher matcher(NORM_HAMMING);
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
// 前n个匹配特征点
int n = matches.size();
vector<Point2f> points1, points2;
for (int i = 0; i < n; i++)
{
points1.push_back(keypoints1[matches[i].queryIdx].pt);
points2.push_back(keypoints2[matches[i].trainIdx].pt);
}
// GMS算法去除误匹配
vector<bool> inliers;
vector<DMatch> gms_matches;
bool result = GMS(points1, img1.size(), points2, img2.size(), matches, gms_matches, inliers);
// RANSAC算法去除误匹配
vector<Point2f> inlier_points1, inlier_points2;
for (int i = 0; i < n; i++)
{
if (inliers[i])
{
inlier_points1.push_back(points1[i]);
inlier_points2.push_back(points2[i]);
}
}
Mat H = findHomography(inlier_points1, inlier_points2, RANSAC);
// 显示匹配结果
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, gms_matches, img_matches);
imshow("Matches", img_matches);
waitKey(0);
return 0;
}
```
其中,Shi-Tomasi角点检测器的参数需要根据图像具体情况进行调整,GMS算法和RANSAC算法的实现可以使用OpenCV提供的函数。
阅读全文