我在写CV中图片拼接过程中,有段代码如下:
//特征点描述,为特征点匹配做准备
OrbDescriptorExtractor orbDescriptor;
vector<Mat> imagesDesc;
for (int i = 0; i < cvt_s_imgs.size(); i++)
{
Mat imageDesc;
orbDescriptor.compute(cvt_s_imgs[i], keyPoints[i], imageDesc);
imagesDesc.push_back(imageDesc);
}
flann::Index flannIndex(imagesDesc[0], flann::LshIndexParams(12, 20, 2), cvflann::FLANN_DIST_HAMMING);
vector<DMatch> GoodMatchPoints;
Mat matchIndex(imagesDesc[1].rows, 2, CV_32SC1), matchDistance(imagesDesc[1].rows, 2, CV_32FC1);
flannIndex.knnSearch(imagesDesc[1], matchIndex, matchDistance, 2, flann::SearchParams());
//采用Lowe's 算法选取优秀匹配点
for (int i = 0; i < matchDistance.rows; i++)
{
if (matchDistance.at<float>(i, 0) < 0.6*matchDistance.at<float>(i, 1))
{
DMatch dmatches(i, matchIndex.at<int>(i, 0), matchDistance.at<float>(i, 0));
GoodMatchPoints.push_back(dmatches);
}
}
//将goodmatch点集进行转换
vector<vector<Point2f>> Points2f;
vector<Point2f> imagePoint1, imagePoint2;
Points2f.push_back(imagePoint1);
Points2f.push_back(imagePoint2);
vector<KeyPoint> keyPoint1, keyPoint2;
keyPoint1 = keyPoints[0];
keyPoint2 = keyPoints[1];
for (int i = 0; i < GoodMatchPoints.size(); i++)
{
Points2f[1].push_back(keyPoint2[GoodMatchPoints[i].queryIdx].pt);
Points2f[0].push_back(keyPoint1[GoodMatchPoints[i].trainIdx].pt);
}
Mat match;
drawMatches(img1, keyPoint1, img2, keyPoint2, GoodMatchPoints, match);
imshow("match", match);
waitKey();
在调试时,OpenCV的内置函数drawMatches()断言报了题目中的错,进过思考和查阅资料,原来是我的关键点矩阵没有对应上,想想自己大概也能理解错误的根源:矩阵运算中被乘矩阵的行列对应不上乘数矩阵的行列,也就是keyPoint1,keyPoint2用反了。所以将
drawMatches(img1, keyPoint1, img2, keyPoint2, GoodMatchPoints, match);
改为
drawMatches(img1, keyPoint2, img2, keyPoint1, GoodMatchPoints, match);
即可!
网友评论