编写以下代码:C++,OpenCV4.6,显示两张图片特征点连线图
时间: 2024-05-13 18:14:07 浏览: 143
以下是基于OpenCV4.6的C++代码,可以显示两张图片的特征点连线图:
```cpp
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取两张需要匹配的图片
Mat img1 = imread("img1.jpg", IMREAD_GRAYSCALE);
Mat img2 = imread("img2.jpg", IMREAD_GRAYSCALE);
// 提取图片的特征点
Ptr<FeatureDetector> detector = ORB::create();
std::vector<KeyPoint> keypoints1, keypoints2;
detector->detect(img1, keypoints1);
detector->detect(img2, keypoints2);
// 计算特征点的描述符
Ptr<DescriptorExtractor> extractor = ORB::create();
Mat descriptors1, descriptors2;
extractor->compute(img1, keypoints1, descriptors1);
extractor->compute(img2, keypoints2, descriptors2);
// 匹配特征点
Ptr<DescriptorMatcher> matcher = BFMatcher::create(NORM_HAMMING, true);
std::vector<DMatch> matches;
matcher->match(descriptors1, descriptors2, matches);
// 选择最优的匹配
double min_dist = 1000000;
for (int i = 0; i < descriptors1.rows; i++)
{
double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
}
std::vector<DMatch> good_matches;
for (int i = 0; i < descriptors1.rows; i++)
{
if (matches[i].distance < 3 * min_dist)
{
good_matches.push_back(matches[i]);
}
}
// 绘制特征点连线图
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, good_matches, img_matches);
imshow("Matches", img_matches);
waitKey(0);
return 0;
}
```
注意,这段代码使用了ORB算法提取特征点,并使用了BFMatcher计算特征点之间的匹配关系。如果需要使用其他算法,可以将代码中的ORB::create()和BFMatcher::create()替换为其他算法的接口。
阅读全文