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

百般思念 提交于 2019-12-10 02:02:09

问题


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.


回答1:


You can simply use bitwise_and() function.

Check the documentation.




回答2:


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.




回答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;


来源:https://stackoverflow.com/questions/11416032/how-to-zero-everything-within-a-masked-part-of-an-image-in-opencv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!