How to show images in split window in OpenCV

A typical scenario in computer vision is to show multiple images in different parts of a single window, like a split window. However, OpenCV can only display a single cv::Mat in a single window using cv::imshow(). So, to achieve what we want, we create a single cv::Mat whose size is equal to the window. We copy our multiple images into this mat at the locations we want and just display the big mat.

(Note that this is far easier than the ROI regions you would need to use with IplImage.)

This sample illustrates showing two 640x480 images side-by-side in a single window:

// 640x480 images
cv::Mat mat_1;
cv::Mat mat_2;

// Create 1280x480 mat for window
cv::Mat win_mat(cv::Size(1280, 480), CV_8UC3);

// Copy small images into big mat
mat_1.copyTo(win_mat(cv::Rect(  0, 0, 640, 480)));
mat_2.copyTo(win_mat(cv::Rect(640, 0, 640, 480)));

// Display big mat
cv::imshow("Images", win_mat);

Tried with: OpenCV 2.4.8 and Ubuntu 14.04

How to work with ROI in OpenCV

Many common image operations are performed using Region of Interest in OpenCV. A ROI allows us to operate on a rectangular subset of the image.

The typical series of steps to use ROI is: create a ROI on the image, perform the operation you want on this subregion of the image, reset back the ROI.

Remember that in OpenCV, the origin is the top-left corner of the image. And a ROI is specified using a CvRect structure.

To copy a cropped region of an image to another image:

IplImage* img; // Source image
IplImage* cropImg; // Destination cropped image
CvRect cropRect = cvRect(10, 12, 100, 300); // ROI in source image

cvSetImageROI(img, cropRect);
cvCopy(img, cropImg, NULL); // Copies only crop region

To set only a region of an image to a certain value:

IplImage* img;
CvRect setRect = cvRect(10, 12, 100, 300); // ROI in image

cvSetImageROI(img, setRect);
cvSet(img, cvScalar(255)); // Set region of image to 255