13

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.

Jackson Dean Goodwin
  • 617
  • 3
  • 11
  • 20

3 Answers3

23

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.

Antonio Sesto
  • 2,868
  • 5
  • 33
  • 51
  • 1
    This is the best answer. Bitwise and requires you to separate out the channels (say you have a 3 channel image you want masked via a 1 channel image), and each one, and then merge them. This handles all that on its own. – Jdban101 Mar 10 '15 at 07:33
  • 1
    In Python: `cv2.copyTo(image_to_mask, mask_array)` – eric Aug 12 '19 at 23:07
10

You can simply use bitwise_and() function.

Check the documentation.

Abid Rahman K
  • 51,886
  • 31
  • 146
  • 157
3

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;
Sam
  • 19,708
  • 4
  • 59
  • 82