用c++opencv写一个图像拼接算法
时间: 2024-05-14 07:15:24 浏览: 244
好的,以下是一个简单的图像拼接算法的 C++ 代码,需要使用 OpenCV 库:
```
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
if (argc < 3)
{
cout << "Usage: " << argv[0] << " <image1> <image2>" << endl;
return -1;
}
Mat img1 = imread(argv[1], IMREAD_COLOR);
Mat img2 = imread(argv[2], IMREAD_COLOR);
if (img1.empty() || img2.empty())
{
cout << "Could not read the image(s)." << endl;
return -1;
}
Mat img1_gray, img2_gray;
cvtColor(img1, img1_gray, COLOR_BGR2GRAY);
cvtColor(img2, img2_gray, COLOR_BGR2GRAY);
vector<KeyPoint> keypoints1, keypoints2;
Mat descriptors1, descriptors2;
Ptr<ORB> orb = ORB::create();
orb->detectAndCompute(img1_gray, Mat(), keypoints1, descriptors1);
orb->detectAndCompute(img2_gray, Mat(), keypoints2, descriptors2);
BFMatcher matcher(NORM_HAMMING);
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
double max_dist = 0;
double min_dist = 100;
for (int i = 0; i < descriptors1.rows; i++)
{
double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
vector<DMatch> good_matches;
for (int i = 0; i < descriptors1.rows; i++)
{
if (matches[i].distance <= max(2 * min_dist, 0.02))
{
good_matches.push_back(matches[i]);
}
}
vector<Point2f> points1, points2;
for (size_t i = 0; i < good_matches.size(); i++)
{
points1.push_back(keypoints1[good_matches[i].queryIdx].pt);
points2.push_back(keypoints2[good_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);
namedWindow("Result", WINDOW_NORMAL);
imshow("Result", result);
waitKey(0);
return 0;
}
```
这个算法使用了 ORB 特征检测器和描述符来检测和匹配两张图片中的特征点,然后使用 RANSAC 算法找到这些特征点之间的单应性矩阵,最终将图像拼接在一起。
阅读全文