Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to apply mask in OpenCV

📅 2015-Aug-20 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ mask, opencv ⬩ 📚 Archive

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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧