opencv图像拼接 C++
时间: 2023-11-27 13:05:19 浏览: 133
以下是使用OpenCV C++进行图像拼接的示例代码:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 读取需要拼接的两张图片
Mat img1 = imread("image1.jpg");
Mat img2 = imread("image2.jpg");
// 转换为灰度图
Mat gray1, gray2;
cvtColor(img1, gray1, COLOR_BGR2GRAY);
cvtColor(img2, gray2, COLOR_BGR2GRAY);
// 提取特征点
vector<KeyPoint> keypoints1, keypoints2;
Ptr<FeatureDetector> detector = ORB::create();
detector->detect(gray1, keypoints1);
detector->detect(gray2, keypoints2);
// 计算特征描述子
Mat descriptors1, descriptors2;
Ptr<DescriptorExtractor> descriptor = ORB::create();
descriptor->compute(gray1, keypoints1, descriptors1);
descriptor->compute(gray2, keypoints2, descriptors2);
// 特征点匹配
vector<DMatch> matches;
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");
matcher->match(descriptors1, descriptors2, matches);
// 筛选匹配点
vector<Point2f> points1, points2;
for (int i = 0; i < matches.size(); i++)
{
points1.push_back(keypoints1[matches[i].queryIdx].pt);
points2.push_back(keypoints2[matches[i].trainIdx].pt);
}
// 计算单应性矩阵
Mat H = findHomography(points2, points1, RANSAC);
// 图像拼接
Mat result;
warpPerspective(img2, result, H, Size(img1.cols + img2.cols, img1.rows));
Mat half(result, Rect(0, 0, img1.cols, img1.rows));
img1.copyTo(half);
// 显示拼接结果
imshow("Result", result);
waitKey(0);
return 0;
}
```
阅读全文