共计 2370 个字符,预计需要花费 6 分钟才能阅读完成。
首先构建 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 <iostream>
#include <opencv2//core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
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<cv::KeyPoint> keypoints_1, keypoints_2;
cv::Mat descripions_1, descripions_2;
cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create(); // 检测 FAST 角点
cv::Ptr<cv::DescriptorExtractor> extractor = cv::ORB::create(); // 提取形容子
cv::Ptr<cv::DescriptorMatcher> 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<cv::DMatch> 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<cv::DMatch> 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]);
}
}
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();
正文完