Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "zero" everything within a masked part of an image in OpenCV

Tags:

c++

opencv

mask

If I have an image (IplImage 8-bit) and a binary mask (which is also an 8-bit IplImage of the same size, where every pixel has a value of either 0 or 255), how can I make every pixel in the image that corresponds with a pixel in the mask with a value of zero have a value of zero, and every pixel in the image that corresponds with a pixel in the mask with any other value (namely 255) have the same value as in the original image?

In other words, anything that is "in the mask area" will keep its original value, and anything outside the mask area will become zero.

like image 512
Jackson Dean Goodwin Avatar asked Jul 10 '12 14:07

Jackson Dean Goodwin


3 Answers

Simplest way, with 'Mat img' (image to be masked, input) and 'Mat masked' (masked image, output):

  img.copyTo(masked, mask)

where 'Mat mask' is a matrix not necessarily binary (copyTo considers elements with zero value). Masked can be of any size and type; it is reallocated if needed.

See the doc.

like image 187
Antonio Sesto Avatar answered Nov 12 '22 22:11

Antonio Sesto


You can simply use bitwise_and() function.

Check the documentation.

like image 38
Abid Rahman K Avatar answered Nov 12 '22 23:11

Abid Rahman K


Multiply or bit-and the mask with the image. There are some OpenCV functions for that, but I do not know their names for the C interface.

in C++:

Mat image, mask;

image = image * mask;
// or 
image = image & mask;
like image 3
Sam Avatar answered Nov 12 '22 21:11

Sam