#include <iostream>
#include <fstream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/stitcher.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
//按行拼接图像A和B
Mat mergeRows(Mat A, Mat B)
{
//CV_ASSERT(A.cols == B.cols&&A.type() == B.type());
int totalRows = A.rows + B.rows;
Mat mergedDescriptors(totalRows, A.cols, A.type());
Mat submat = mergedDescriptors.rowRange(0, A.rows);
A.copyTo(submat);
submat = mergedDescriptors.rowRange(A.rows, totalRows);
B.copyTo(submat);
return mergedDescriptors;
}
void main()
{
Mat image_one = imread("E:\\testpictures\\0\\1\\12.jpg");//待拼接左图
Mat image_two = imread("E:\\testpictures\\0\\1\\18.jpg");//待拼接右图
if (image_one.rows >= image_two.rows)
{ //创建一个image_one.rows-image_two.rows行image_two.cols列的黑色图像
#define HEIGHT image_one.rows-image_two.rows //行rows
#define WIDTH image_two.cols //列cols
//Scalar()是向量,表示初始化每个像素值是多少,向量长度与通道数目(深度)一致
cv::Mat image(HEIGHT, WIDTH, image_two.type(), cv::Scalar(0));
Mat outimage;
//将黑色图像与image_two按行拼接成outimage,黑色图像放下面,因为c++的原点在左上角
outimage=mergeRows(mage_two, image);
//将image_one和outimage按列拼接为result并保存
Mat result(image_one.rows, image_one.cols + outimage.cols, image_one.type());
//colRange(int x,int y) 取图像的第x~y-1行
image_one.colRange(0, image_one.cols).copyTo(result.colRange(0, image_one.cols));
outimage.colRange(0, outimage.cols).copyTo(result.colRange(image_one.cols, result.cols));
imwrite("result.jpg", result);
waitKey(0);
}
else
{ //创建一个image_two.rows-image_one.rows行image_one.cols列的黑色图像
#define HEIGHT image_two.rows-image_one.rows //行rows
#define WIDTH image_one.cols //列cols
//Scalar()是向量,表示初始化每个像素值是多少,向量长度与通道数目(深度)一致
cv::Mat image(HEIGHT, WIDTH, image_one.type(), cv::Scalar(0));
Mat outimage;
//将黑色图像与image_one按行拼接成outimage,黑色图像放下面,因为c++的原点在左上角
outimage=mergeRows(image_one,image);
//将image_two和outimage按列拼接为result并保存
Mat result(image_two.rows, outimage.cols + image_two.cols, image_two.type());
//colRange(int x,int y) 取图像的第x~y-1行
outimage.colRange(0, outimage.cols).copyTo(result.colRange(0, outimage.cols));
image_two.colRange(0, image_two.cols).copyTo(result.colRange(outimage.cols, result.cols));
imwrite("result.jpg", result);
waitKey(0);
}
return ;
}