0
votes

I would like to create a mask in OpenCV containing some full rectangular regions (say 1 to 10 regions). Think of it as a mask showing the location of features of interest on an image. I know the pixel coordinates of the corners of each region.

Right now, I am first initializing a Mat to 0, then I am looping through each element. Using "if" logic, I put each pixel to 255 if they belong to the region, such as:

for (int i = 0; i<mymask.cols, i++) {
   for (int j = 0; j<mymask.rows, j++) {
      if ( ((i > x_lowbound1) && (i < x_highbound1) &&  
         (j > y_lowbound1) && (j < y_highbound1)) || 
         ((i > x_lowbound2) && (i < x_highbound2) &&  
         (j > y_lowbound2) && (j < y_highbound2))) {
         mymask.at<uchar>(i,j) = 255;
      }
   }
}

But this is very clumsy and I think inefficient. In this case, I "fill" 2 rectangular region with 255. But there is no viable way to change the number of region I fill, beside using a switch-case and repeating the code n times.

Is there anyone thinking of something more intelligent? I would rather not use a 3rd party stuff (beside OpenCV ;) ) and I am using VisualStudio 2012.

1
mymask.at<i*mymask.rows + j> = 255; - shouldn't that be mymask.at<some_type>(j,i) = 255; ?berak
Yeah possible when I wrote the question I had no access to my code so I wrote what I remembered...Doombot
Well by "yeah possible" I mean you are totally right ;) Thanks I will correct it!Doombot

1 Answers

2
votes

Use cv::rectangle():

//bounds are inclusive in this code!
cv::Rect region(x_lowbound1, y_lowbound1,
                x_highbound1 - x_lowbound1 + 1, y_highbound1 - y_lowbound1 + 1)
cv::rectangle(mymask, region, cv::Scalar(255), CV_FILLED);