多区域掩码 OpenCV

Multi region mask OpenCV

本文关键字:OpenCV 掩码 区域      更新时间:2023-10-16

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

现在,我首先将 Mat 初始化为 0,然后循环遍历每个元素。使用"if"逻辑,如果每个像素属于该区域,我将每个像素设置为 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;
      }
   }
}

但这非常笨拙,我认为效率低下。在这种情况下,我用 2 个矩形区域"填充"255。但是除了使用开关盒并重复代码 n 次之外,没有可行的方法来更改我填充的区域数量。

有没有人想着更聪明的东西?我宁愿不使用第三方的东西(除了OpenCV ;)),我正在使用VisualStudio 2012。

使用 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);