opencv图像拼接demo

来源:互联网 发布:mac mnmp 一键安装包 编辑:程序博客网 时间:2024/06/03 17:50
int main(void)
{


Mat leftImg = imread("E:/test/xml_operation/left.jpg");


Mat rightImg = imread("E:/test/xml_operation/right.jpg");




if (leftImg.data == NULL || rightImg.data == NULL)


return 0;




//转化成灰度图  


Mat leftGray;


Mat rightGray;
while (1)
{


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);


imshow("rightDescriptor image", rightDescriptor);


//imshow("leftDescriptor image", leftDescriptor);
//imshow("rightDescriptor image", 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);  


sort(matches.begin(), matches.begin() + leftDescriptor.rows);


}


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("E:/test/xml_operation/tiled.jpg", tiledImg);






//显示拼接的图像  


imshow("tiled image", tiledImg);


waitKey(100);
}


return 0;


}




0 0