OpenCV: the role of mask, how to make a mask mask

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

Many functions in OpenCV use mask, what is mask? How to make a mask? will be the main content of this article.


1. What is the mask?

mask is not Musk, but a mask, which can be used to cover non-interest areas and highlight interest areas, so that image processing can only focus on the ROI part.

2. Several methods of OpenCV generating mask

Note: the mask needs to be consistent with the size and type of the input image to be applied

rectangle

#include <opencv2/opencv.hpp>

using namespace cv;

int main() {
    
    
  Mat src = imread("img1.png", IMREAD_GRAYSCALE);
  imshow("src", src);
  // 定义mask,大小640*480,像素全0
  Mat mask = cv::Mat::zeros(Size(640, 480), CV_8UC1);

  // 作一个从坐标(220,120),宽200,高200的矩形框,框内填充白色,从方法1,2,3中任选一
  // 方法1
  rectangle(mask, cv::Rect(220, 120, 200, 200), Scalar(255), -1);
  // 方法2
  mask(cv::Rect(320, 50, 240, 310)) = 255;
  // 方法3
  mask(cv::Rect(320, 50, 240, 310)).setTo(255);
  
  Mat dst;
  // 将src中对应对应掩膜ROI中区域拷贝到dst
  src.copyTo(dst, mask);
  
  imshow("mask",mask);
  imshow("dst", dst);
  waitKey();
  
  return 0;
}

The result of the operation is as follows:

Please wait, opening the picture

src

Please wait, opening the picture
mask

Please wait, opening the picture

dst

round

in the same way

#include <opencv2/opencv.hpp>

using namespace cv;

int main() {
    
    
  Mat src = imread("img1.png", IMREAD_GRAYSCALE);
  
  // 定义mask,大小640*480,像素全0
  Mat mask = cv::Mat::zeros(Size(640, 480), CV_8UC1);
  // 作一个以点坐标(320,50)为圆心,150为半径的圆,圆内填充白色
  circle(mask, Point(440, 205), 150, Scalar(255),-1);
  
  Mat dst;
  // 将src中对应对应掩膜ROI中区域拷贝到dst
  src.copyTo(dst, mask);
  
  imshow("mask",mask);
  imshow("dst", dst);
  waitKey();
  
  return 0;
}

Please wait, opening the picture

mask

Please wait, opening the picture

dst

Masks can be in various shapes and styles, and there are many methods. Here are just a few.


Summarize

Define the mask, set the ROI, fill the inside of the ROI with white, and fill the others with black, you can operate on the ROI area and cover other areas. You can also reverse the mask to cover the data in the rectangular frame and process the data outside the frame.

Guess you like

Origin blog.csdn.net/weixin_42286660/article/details/124542309