OpenCV : 一种拼接图像的简易方法

用iphone拍摄的两幅图像:

OpenCV : 一种拼接图像的简易方法_第1张图片
 
OpenCV : 一种拼接图像的简易方法_第2张图片
 

 

 拼接后的图像:

OpenCV : 一种拼接图像的简易方法_第3张图片
 
 

 

相关代码如下:

//读取图像
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 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 matches;
matcher.match(leftDescriptor,rightDescriptor,matches);	
int matchCount=leftDescriptor.rows;
if(matchCount>15)
{
	matchCount=15;
	sort(matches.begin(),matches.begin()+leftDescriptor.rows,DistanceLessThan);
}	
vector leftPoints;
vector rightPoints;
for(int i=0; i(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);

 

 

你可能感兴趣的:(图像)