在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的功能 总是比天真的手工制作的代码更快
答案 0 :(得分:46)
当然,有一种更简单的方法,使用roi操作符:
cv::Mat mask = cv::Mat::zeros(8, 8, CV_8U); // all 0
mask(Rect(2,2,4,4)) = 1;
完成!
答案 1 :(得分:2)
如果有人正在寻找创建非矩形蒙版,然后将其应用于图像,请查看此处:
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;
}
&#34;黑色&#34;是我们最终通过从原始图像中裁剪出不规则ROI来获得结果的图像。
static Mat black(origImag.rows, origImag.cols, origImag.type(), cv::Scalar::all(0));
&#34;面具&#34;是一个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部分粘贴到名为&#34;黑色&#34;
的图像中origImag.copyTo(black,mask);