21

在 openCV 中创建蒙版

      /** result I want
          0 0 0 0 0 0 0 0
          0 0 0 0 0 0 0 0
          0 0 1 1 1 1 0 0
          0 0 1 1 1 1 0 0
          0 0 1 1 1 1 0 0
          0 0 1 1 1 1 0 0
          0 0 0 0 0 0 0 0
          0 0 0 0 0 0 0 0
      */    
cv::Mat mask = cv::Mat::zeros(8, 8, CV_8U);
std::cout<<"before : \n"<<mask<<std::endl;
for(int i = 2; i != 6; ++i)
{
     auto ptr = mask.ptr<uchar>(i) + 2;
     for(int j = 0; j != 4; ++j)
     {
         *ptr++ = 1;
     }
}
std::cout<<"after : \n"<<mask<<std::endl;   

openCV 是否为我们提供了任何内置函数来创建这样的掩码?为这个任务创建一个函数是微不足道的,但是 openCV 的函数总是比天真的手工代码快

4

2 回答 2

54

当然,有一种更简单的方法,使用 roi 运算符:

cv::Mat mask = cv::Mat::zeros(8, 8, CV_8U); // all 0
mask(Rect(2,2,4,4)) = 1;

完毕!

于 2013-08-08T21:10:11.250 回答
5

如果有人正在寻找创建一个非矩形蒙版,然后将其应用到图像上,那么请看这里:

Mat& obtainIregularROI(Mat& origImag, Point2f topLeft, Point2f topRight, Point2f botLeft, Point2f botRight){

        static Mat black(origImag.rows, origImag.cols, origImag.type(), cv::Scalar::all(0));
        Mat mask(origImag.rows, origImag.cols, CV_8UC1, cv::Scalar(0));
        vector< vector<Point> >  co_ordinates;
        co_ordinates.push_back(vector<Point>());
        co_ordinates[0].push_back(topLeft);
        co_ordinates[0].push_back(botLeft);
        co_ordinates[0].push_back(botRight);
        co_ordinates[0].push_back(topRight);
        drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );

        origImag.copyTo(black,mask);
        return black;
    }

“黑色”是我们最终将通过从原始图像中裁剪掉不规则的 ROI 来获得结果的图像。

 static Mat black(origImag.rows, origImag.cols, origImag.type(), cv::Scalar::all(0));

“mask”是一个Mat,初始化为和原图一样大小,填充0。 Mat mask(origImag.rows, origImag.cols, CV_8UC1, cv::Scalar(0));

将坐标置于逆时针方向

    vector< vector<Point> >  co_ordinates;
    co_ordinates.push_back(vector<Point>());
    co_ordinates[0].push_back(topLeft);
    co_ordinates[0].push_back(botLeft);
    co_ordinates[0].push_back(botRight);
    co_ordinates[0].push_back(topRight);

现在实际生成掩码

drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );

最后从原始图像(origImag)复制蒙版部分/ ROI,并将原始图像(使用蒙版)的ROI部分粘贴到名为“黑色”的图像中

origImag.copyTo(black,mask);
于 2017-12-24T14:25:14.520 回答