OpenCV 4 Computer Vision Application Programming Cookbook(Fourth Edition)
上QQ阅读APP看书,第一时间看更新

Using image masks

Some OpenCV operations allow you to define a mask that will limit the applicability of a given function or method, which is normally supposed to operate on all the image pixels. A mask is an 8-bit image that should be nonzero at all locations where you want an operation to be applied. At the pixel locations that correspond to the zero values of the mask, the image is untouched. For example, the copyTo method can be called with a mask. We can use it here to copy only the white portion of the logo shown previously, as follows:

// define image ROI at image bottom-right 
imageROI= image(cv::Rect(image.cols-logo.cols,image.rows-logo.rows,  logo.cols,logo.rows)); 
// use the logo as a mask (must be gray-level) 
cv::Mat mask(logo); 
 
// insert by copying only at locations of non-zero mask 
logo.copyTo(imageROI,mask); 

The following image is obtained by executing the previous code:

The background of our logo was black (therefore, it had the value 0); therefore, it was easy to use it as both the copied image and the mask. Of course, you can define the mask of your choice in your application; most OpenCV pixel-based operations give you the opportunity to use masks.