在使用OpenCV进行可视化的过程中,经常有对多张图像进行合并的需求,需要小心处理不同图像的类型、尺寸等属性,下面直接给出开发常用的代码。
如果已经知道需要合并的两张图像的尺寸是完全一致的,直接用下面的代码即可:
#include
void MergeTwoImages() {
cv::Mat img1(800, 600, CV_8UC3, cv::Scalar(0));
cv::Mat img2(800, 600, CV_8UC3, cv::Scalar(128, 128, 128));
cv::Mat merged_img(img1.rows, img1.cols + img2.cols + 1,
img1.type(), cv::Scalar(0));
img1.copyTo(merged_img.colRange(0, img1.cols));
img2.copyTo(merged_img.colRange(img2.cols + 1, merged_img.cols));
// Draw the boundary line
cv::line(merged_img, cv::Point(img1.cols, 0), cv::Point(img1.cols, merged_img.rows),
cv::Scalar(255, 255, 255));
cv::imshow("merged_img", merged_img);
cv::waitKey(0);
}
如果两张合并的图像尺寸不一致,则需要对上述代码做一些修改,得到如下的代码:
void MergeTwoImages2() {
cv::Mat img1(800, 600, CV_8UC3, cv::Scalar(128, 255, 0));
cv::Mat img2(700, 500, CV_8UC3, cv::Scalar(128, 128, 128));
int merged_rows = std::max(img1.rows, img2.rows);
int merged_cols = img1.cols + img2.cols;
cv::Mat merged_img(merged_rows, merged_cols + 1, img1.type(), cv::Scalar(0));
img1.copyTo(merged_img(cv::Rect(0, 0, img1.cols, img1.rows)));
img2.copyTo(merged_img(cv::Rect(img1.cols + 1, 0, img2.cols, img2.rows)));
// Draw the boundary line
cv::line(merged_img, cv::Point(img1.cols, 0), cv::Point(img1.cols, merged_img.rows),
cv::Scalar(255, 255, 255));
cv::imshow("merged_img2", merged_img);
cv::waitKey(0);
}
【参考】:
OpenCV中Mat类rowRange和colRange的用法