多区域掩码OpenCV

时间:2014-11-27 19:30:03

标签: c++ opencv mask mat

我想在OpenCV中创建一个包含一些完整矩形区域(比如1到10个区域)的掩码。可以将其视为一个掩码,显示图像上感兴趣的特征的位置。我知道每个区域角落的像素坐标。

现在,我首先将Mat初始化为0,然后循环遍历每个元素。使用"如果"逻辑,如果它们属于该区域,我将每个像素设置为255,例如:

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;
      }
   }
}

但这非常笨拙,我认为效率低下。在这种情况下,我&#34;填写&#34; 2个矩形区域有255.但是没有可行的方法来改变我填充的区域数量,除了使用switch-case并重复代码n次。

有没有人想过更聪明的事情?我宁愿不使用第三方的东西(在OpenCV旁边;))我正在使用VisualStudio 2012。

1 个答案:

答案 0 :(得分:2)

使用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);
相关问题