OpenCV图像拼接(3)图像拼接的类cv::detail::BestOf2NearestMatcher
#include <opencv2/opencv.hpp>
#include <opencv2/stitching/detail/matchers.hpp>
using namespace cv;
using namespace cv::detail;
void drawMatchingResult(const Mat& img1, const Mat& img2, const std::vector<KeyPoint>& keypoints1,
const std::vector<KeyPoint>& keypoints2, const std::vector<DMatch>& matches)
{
// 创建一个输出图像来展示两张图片和它们之间的匹配
Mat outputImg;
drawMatches(img1, keypoints1, img2, keypoints2, matches, outputImg,
Scalar::all(-1), Scalar::all(-1), std::vector<char>(),
DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
// 显示匹配结果
imshow("Feature Matches", outputImg);
waitKey(0);
}
int main()
{
// 读取两张待匹配的图片
Mat img1 = imread("/media/dingxin/data/study/OpenCV/sources/images/stich1.png");
Mat img2 = imread("/media/dingxin/data/study/OpenCV/sources/images/stich2.png");
if (img1.empty() || img2.empty())
{
std::cerr << "Could not open or find the images!" << std::endl;
return -1;
}
// 初始化ORB特征检测器
Ptr<Feature2D> feature_detector = ORB::create();
// 检测特征点并计算描述符
std::vector<KeyPoint> keypoints1, keypoints2;
Mat descriptors1, descriptors2;
feature_detector->detectAndCompute(img1, noArray(), keypoints1, descriptors1);
feature_detector->detectAndCompute(img2, noArray(), keypoints2, descriptors2);
// 创建ImageFeatures对象并将特征点和描述符填入
ImageFeatures features1, features2;
features1.img_idx = 0; // 图片索引
features1.keypoints = keypoints1;
features1.descriptors = descriptors1.getUMat(ACCESS_READ); // 使用getUMat方法转换
features2.img_idx = 1; // 图片索引
features2.keypoints = keypoints2;
features2.descriptors = descriptors2.getUMat(ACCESS_READ); // 使用getUMat方法转换
// 创建BestOf2NearestMatcher实例
Ptr<BestOf2NearestMatcher> matcher = BestOf2NearestMatcher::create();
// 使用()运算符来进行匹配
MatchesInfo matches_info;
(*matcher)(features1, features2, matches_info);
// 输出匹配结果的数量
std::cout << "Found " << matches_info.matches.size() << " matches" << std::endl;
// 将MatchesInfo中的matches转换为std::vector<DMatch>类型,以便于绘制
std::vector<DMatch> matches_vector(matches_info.matches.begin(), matches_info.matches.end());
// 绘制匹配结果
drawMatchingResult(img1, img2, keypoints1, keypoints2, matches_vector);
return 0;
}