How to apply mask in OpenCV

In OpenCV, a mask image is of type uint8_t. Pixels of value 0xFF are true and pixels of value 0 are false.

A mask can be applied on an image of the same dimensions, but of any type. By applying a mask M on an image I, the pixels of I whose corresponding pixel in M are true are copied into a new image. The rest of the pixels in the new image are set to 0.

Applying a mask in OpenCV is easy:

cv::Mat in_mat;   // Already created
cv::Mat mask_mat; // Already created
cv::Mat out_mat;  // New and empty

in_mat.copyTo(out_mat, mask_mat);

Note that the input and output image should not be the same! OpenCV does not throw an error, but the behavior is undefined.

Tried with: OpenCV 2.4.8 and Ubuntu 14.04

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s