OpenCV实现拼接图像的简单方法

时间:2021-05-20

本文实例为大家分享了OpenCV实现拼接图像的具体方法,供大家参考,具体内容如下

用iphone拍摄的两幅图像:

拼接后的图像:

相关代码如下:

//读取图像Mat leftImg=imread("left.jpg");Mat rightImg=imread("right.jpg");if(leftImg.data==NULL||rightImg.data==NULL) return; //转化成灰度图Mat leftGray;Mat rightGray;cvtColor(leftImg,leftGray,CV_BGR2GRAY);cvtColor(rightImg,rightGray,CV_BGR2GRAY); //获取两幅图像的共同特征点int minHessian=400;SurfFeatureDetector detector(minHessian);vector<KeyPoint> leftKeyPoints,rightKeyPoints;detector.detect(leftGray,leftKeyPoints);detector.detect(rightGray,rightKeyPoints);SurfDescriptorExtractor extractor;Mat leftDescriptor,rightDescriptor;extractor.compute(leftGray,leftKeyPoints,leftDescriptor);extractor.compute(rightGray,rightKeyPoints,rightDescriptor);FlannBasedMatcher matcher;vector<DMatch> matches;matcher.match(leftDescriptor,rightDescriptor,matches); int matchCount=leftDescriptor.rows;if(matchCount>15){ matchCount=15; sort(matches.begin(),matches.begin()+leftDescriptor.rows,DistanceLessThan);} vector<Point2f> leftPoints;vector<Point2f> rightPoints;for(int i=0; i<matchCount; i++){ leftPoints.push_back(leftKeyPoints[matches[i].queryIdx].pt); rightPoints.push_back(rightKeyPoints[matches[i].trainIdx].pt);} //获取左边图像到右边图像的投影映射关系Mat homo=findHomography(leftPoints,rightPoints);Mat shftMat=(Mat_<double>(3,3)<<1.0,0,leftImg.cols, 0,1.0,0, 0,0,1.0); //拼接图像Mat tiledImg;warpPerspective(leftImg,tiledImg,shftMat*homo,Size(leftImg.cols+rightImg.cols,rightImg.rows));rightImg.copyTo(Mat(tiledImg,Rect(leftImg.cols,0,rightImg.cols,rightImg.rows))); //保存图像imwrite("tiled.jpg",tiledImg); //显示拼接的图像imshow("tiled image",tiledImg);waitKey(0);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章