Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Apply Mask to Image in OpenCV?

Tags:

I want to apply a binary mask to a color image. Please provide a basic code example with proper explanation of how the code works.

Also, is there some option to apply a mask permanently so all functions operate only within the mask?

like image 977
fdh Avatar asked Sep 20 '11 01:09

fdh


People also ask

How do I mask an image in OpenCV?

Masking is a common technique to extract the Region of Interest (ROI). In openCV, it is possible to construct arbitrary masking shape using draw function and bitwise operation.

How do you mask in image processing?

How it is done. The general process of filtering and applying masks is consists of moving the filter mask from point to point in an image. At each point (x,y) of the original image, the response of a filter is calculated by a pre defined relationship. All the filters values are pre defined and are a standard.


1 Answers

While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:

inputMat.copyTo(outputMat, maskMat);

All objects are of type cv::Mat.

Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.

Also be aware that the .copyTo() function does not clear the output before copying.

If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.

like image 69
Chaos_99 Avatar answered Oct 07 '22 12:10

Chaos_99