OpenCV在同一窗口中相邻显示2个图像

时间:2012-10-30 05:16:56

标签: image-processing opencv roi

我正在尝试使用OpenCV在同一窗口中水平相邻显示2个图像。

我尝试过使用adjustROI功能。图像1的宽度为1088像素,高度为2208像素,而图像2的宽度为1280像素,高度为2208像素。请在下面的代码中提出可能出现的问题。我所得到的是图像大小为Image2,同时包含Image2中的内容。

Mat img_matches=Mat(2208,2368,imgorig.type());//set size as combination of img1 and img2
img_matches.adjustROI(0,0,0,-1280); 
imgorig.copyTo(img_matches);
img_matches.adjustROI(0,0,1088,1280);
imgorig2.copyTo(img_matches);

3 个答案:

答案 0 :(得分:28)

编辑:以下是我如何做您想做的事情:

Mat left(img_matches, Rect(0, 0, 1088, 2208)); // Copy constructor
imgorig.copyTo(left);
Mat right(img_matches, Rect(1088, 0, 1280, 2208)); // Copy constructor
imgorig2.copyTo(right);

复制构造函数创建Mat标题的副本,该标题指向每个Rect定义的ROI。

完整代码:

#include <cv.h>
#include <highgui.h>

using namespace cv;

int
main(int argc, char **argv)
{
    Mat im1 = imread(argv[1]);
    Mat im2 = imread(argv[2]);
    Size sz1 = im1.size();
    Size sz2 = im2.size();
    Mat im3(sz1.height, sz1.width+sz2.width, CV_8UC3);
    Mat left(im3, Rect(0, 0, sz1.width, sz1.height));
    im1.copyTo(left);
    Mat right(im3, Rect(sz1.width, 0, sz2.width, sz2.height));
    im2.copyTo(right);
    imshow("im3", im3);
    waitKey(0);
    return 0;
}

编译:

g++ foo.cpp -o foo.out `pkg-config --cflags --libs opencv`

<强> EDIT2:

以下是adjustROI

的外观
#include <cv.h>
#include <highgui.h>

using namespace cv;

int
main(int argc, char **argv)
{
    Mat im1 = imread(argv[1]);
    Mat im2 = imread(argv[2]);
    Size sz1 = im1.size();
    Size sz2 = im2.size();
    Mat im3(sz1.height, sz1.width+sz2.width, CV_8UC3);
    // Move right boundary to the left.
    im3.adjustROI(0, 0, 0, -sz2.width);
    im1.copyTo(im3);
    // Move the left boundary to the right, right boundary to the right.
    im3.adjustROI(0, 0, -sz1.width, sz2.width);
    im2.copyTo(im3);
    // restore original ROI.
    im3.adjustROI(0, 0, sz1.width, 0);
    imshow("im3", im3);
    waitKey(0);
    return 0;
}

您必须跟踪当前的投资回报率,并且移动投资回报率的语法可能有点不直观。结果与第一个代码块相同。

答案 1 :(得分:8)

由于图像的高度(Mat的行)相同,函数hconcat可能用于水平连接两个图像(Mat),因此可以用于在同一窗口中并排显示它们。 OpenCV doc
它适用于灰度和彩色图像。

Mat im1, im2;
// source images im1 and im2

Mat newImage;
hconcat(im1, im2, newImage);

imshow("Display side by side", newImage);
waitKey(0);

为了完整起见,vconcat可用于垂直连接。

答案 2 :(得分:5)

这里的解决方案受到了@ misha的回答。

#include <cv.h>
#include <highgui.h>

using namespace cv;

int
main(int argc, char **argv)
{
    Mat im1 = imread(argv[1]);
    Mat im2 = imread(argv[2]);
    Size sz1 = im1.size();
    Size sz2 = im2.size();
    Mat im3(sz1.height, sz1.width+sz2.width, CV_8UC3);
    im1.copyTo(im3(Rect(0, 0, sz1.width, sz1.height)));
    im2.copyTo(im3(Rect(sz1.width, 0, sz2.width, sz2.height)));
    imshow("im3", im3);
    waitKey(0);
    return 0;
}

此解决方案使用Mat::operator()(const Rect& roi),而不是使用复制构造函数。虽然两种解决方案都是O(1),但这种解决方案似乎更清晰。

相关问题