Custom ROI (Region Of Interest) with OpenCV

Today, I was in need of a custom ROI (a parallellogram). In OpenCV, the way to do this is to use a mask. This can be created by puting a filled white shape on a black one-channel image (CV_U8C1 format). After this the CopyTo-method can be used to subtract the ROI from the image. The code I used can be seen in the code block below. The vector "ROI_Vertices" contains the vertices of the parallogram I want to use as the ROI, so you will have to define this first. I first fit a polygon around it (ROI_Poly) because OpenCV likes this better, and then fill it with white.

/* ROI by creating mask for the parallelogram */
Mat mask = cvCreateMat(480, 640, CV_8UC1);
// Create black image with the same size as the original
for(int i=0; i<mask.cols; i++)
   for(int j=0; j<mask.rows; j++)
       mask.at<uchar>(Point(i,j)) = 0;
 
// Create Polygon from vertices
vector<Point> ROI_Poly;
approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, true);
 
// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);                 
 
// Create new image for result storage
Mat imageDest = cvCreateMat(480, 640, CV_8UC3);
 
// Cut out ROI and store it in imageDest
image->copyTo(imageDest, mask);    

The mask looks like this:

The subtracted part is shown here: