步骤
加载图像:加载待匹配的图像和要搜索的模板图像。
**特征检测:**使用关键点检测算法(如SIFT、SURF、ORB等)检测图像中的关键点。
描述符计算:计算每个关键点的描述符,描述符是一个向量,用于描述关键点周围的图像信息。
**特征匹配:**将模板图像的特征描述符与待匹配图像的特征描述符进行匹配,找到最佳匹配点。
**绘制匹配结果:**可选,将匹配结果可视化,例如绘制匹配的关键点或者画出匹配的线段。
示例代码:
#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
int main() {
// 加载图像
Mat img_scene = imread("image1.jpg", IMREAD_GRAYSCALE);
Mat img_object = imread("image2.jpg", IMREAD_GRAYSCALE);
if (img_scene.empty() || img_object.empty()) {
std::cerr << "Error loading images!" << std::endl;
return -1;
}
// 定义特征检测器和描述符提取器
Ptr<Feature2D> detector = SIFT::create();
std::vector<KeyPoint> keypoints_scene, keypoints_object;
Mat descriptors_scene, descriptors_object;
// 检测关键点和计算描述符
detector->detectAndCompute(img_scene, Mat(), keypoints_scene, descriptors_scene);
detector->detectAndCompute(img_object, Mat(), keypoints_object, descriptors_object);
// 定义匹配器
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED);
std::vector<DMatch> matches;
// 进行匹配
matcher->match(descriptors_object, descriptors_scene, matches);
// 绘制匹配结果
Mat img_matches;
drawMatches(img_object, keypoints_object, img_scene, keypoints_scene,
matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
// 显示结果
imshow("Matches", img_matches);
waitKey(0);
return 0;
}