How to Apply Mask to Image in OpenCV?

fdh picture fdh · Sep 20, 2011 · Viewed 104.4k times · Source

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?

Answer

Chaos_99 picture Chaos_99 · Aug 10, 2013

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.