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

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值