利用OpenCV进行ORB角点提取和匹配

首先构建CMakeLists.txt

cmake_minimum_required(VERSION 3.21) project(ORB)set(CMAKE_CXX_STANDARD 14)find_package( OpenCV REQUIRED ) include_directories( ${OPENCV_INCLUDE_DIRS} )add_executable(ORB main.cpp) target_link_libraries(ORB ${OpenCV_LIBS})

编写cpp
#include #include #include #include using namespace std;

首先读取图片
cv::Mat img_1 = cv::imread("../1.png"); cv::Mat img_2 = cv::imread("../2.png"); cv::imshow("img_1", img_1); cv::imshow("img_2", img_2); cv::waitKey(0); cv::destroyAllWindows();

其次进行ORB角点提取的一些初始化工作
vector keypoints_1, keypoints_2; cv::Mat descripions_1, descripions_2; cv::Ptr detector = cv::ORB::create(); //检测FAST角点 cv::Ptr extractor = cv::ORB::create(); //提取描述子 cv::Ptr matcher = cv::DescriptorMatcher::create("BruteForce-Hamming"); //匹配器,使用汉明距离

STEP1 & STEP2 检测FAST角点、计算BRIEF描述子
//STEP1 检测FAST角点 detector->detect(img_1, keypoints_1); //提取img_1中的角点,存储到keypoints_1中 detector->detect(img_2, keypoints_2); //STEP2 计算BRIEF描述子 extractor->compute(img_1, keypoints_1, descripions_1); extractor->compute(img_2, keypoints_2, descripions_2); cv::Mat outimg_1, outimg_2; cv::drawKeypoints(img_1, keypoints_1, outimg_1, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT); cv::drawKeypoints(img_2, keypoints_2, outimg_2, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT); cv::imshow("ORB Keypoints_img_1", outimg_1); cv::imshow("ORB Keypoints_img_2", outimg_2); cv::waitKey(0); cv::destroyAllWindows();

STEP3 & STEP4 特征点匹配、特征点筛选
//STEP3 Match vector matches; //用来存储匹配关系 matcher->match(descripions_1, descripions_2, matches); //将descripions_1和descripions_2的匹配关系储存到DMatch中//STEP4 匹配点筛选 auto min_max = minmax_element(matches.begin(), matches.end(), [](const cv::DMatch &m1, const cv::DMatch &m2){return m1.distance < m2.distance; } ); //计算最小距离和最大距离 double min_dist = min_max.first->distance; double max_dist = min_max.second->distance; vector good_matches; for(int i = 0; i < descripions_1.rows; i++){ if (matches[i].distance <= max(2 * min_dist, 30.0)){ good_matches.push_back(matches[i]); } }

【利用OpenCV进行ORB角点提取和匹配】STEP5 绘制匹配结果
//STEP5 绘制匹配结果 cv::Mat img_match; cv::Mat img_goodmatch; cv::drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_match); cv::drawMatches(img_1, keypoints_1, img_2, keypoints_2, good_matches, img_goodmatch); cv::imshow("all matches", img_match); cv::imshow("good matches", img_goodmatch); cv::waitKey(0); cv::destroyAllWindows();

    推荐阅读