-
Today, I will introduce how to use opencv to achieve merge image.
-
Stitching the up and down image requires the same number of columns.
-
Stitching the left and right image needs to ensure that the number of rows is equal.
-
The next two functions are implemented,you can refer to the following code:,The mergeCols function,you can input the image A and Image B,merge A and B,I use the vector of the Mat to save the Mat A and Mat B.The mergeRows function,input the image A and Image B,merge A and B.The function of mergeCols requries the image A.rows is equal the imageB.rows,if not,you can use the function of assert to interrupt the current process.So,you can use the resize to ensure the imageA.rows= the imageB.rows. The function of mergeRows is similar to the function of mergeCols, requries the image A.cols is equal to the imageB.cols.The resize function is not added in the following code,you can add.I will offer a possible solution,you can use this code: resize(A, A, Size(A.cols, B.rows), 0, 0, INTER_LINEAR); in the mergeCols(Mat A, Mat B) function,This ensures that the image has the same number of rows.MeanWhile,mergeRows(Mat A, Mat B) is similar to the mergeCols(Mat A, Mat B),you can use this code:resize(A, A, Size(B.cols, A.rows), 0, 0, INTER_LINEAR);
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/stitching.hpp"
using namespace std;
using namespace cv;
vector<Mat> imgs;
//左右row相等
Mat mergeCols(Mat A, Mat B)
{
//assert(A.rows == B.rows&&A.type() == B.type());
int totalCols = A.cols + B.cols;
Mat mergedDescriptors(A.rows, totalCols, A.type());
Mat submat = mergedDescriptors.colRange(0, A.cols);
A.copyTo(submat);
submat = mergedDescriptors.colRange(A.cols, totalCols);
B.copyTo(submat);
return mergedDescriptors;
}
//上下cols相等
Mat mergeRows(Mat A, Mat B)
{
//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;
}
int main(int argc, char * argv[])
{
Mat img1 = imread("2.jpg");
Mat img2 = imread("2.jpg");
if (img1.empty() || img2.empty())
{
cout << "Can't read image" << endl;
return -1;
}
imgs.push_back(img1);
imgs.push_back(img2);
Mat OUTPUT = mergeRows(img1, img2);
namedWindow("OUTPUT", 0);//创建窗口
cvResizeWindow("OUTPUT", 1000, 1000); //创建一个500*500大小的窗口
imshow("OUTPUT", OUTPUT);
waitKey(0);
imwrite("output.jpg", OUTPUT);
}
I hope I can help you,If you have any questions, please comment on this blog or send me a private message. I will reply in my free time.