在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的功能总是比天真的手工编码快
确定,有一种更简单的方法,使用roi运算符:
cv::Mat mask = cv::Mat::zeros(8, 8, CV_8U); // all 0
mask(Rect(2,2,4,4)) = 1;
完成了!
如果有人正在寻找创建非矩形蒙版然后将其应用于图像,那么看看这里:
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));
“掩码”是一个Mat,初始化为原始图像的相同大小并填充0. Mat mask(origImag.rows,origImag.cols,CV_8UC1,cv :: Scalar(0));
将坐标放在ANTICLOCKWISE方向
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);