37

Is there a simple way to invert a mask using OpenCV? For example, if I've got a mask like this:

010
111
010

I'd like to invert it and get this:

101
000
101

Note: I'm using OpenCV's Python bindings, so while it would be possible to simply loop over each element in the mask, execution speed could become an issue.

3
  • 4
    Use a bitwise Not to flip all bits in a matrix. Jul 20, 2010 at 14:40
  • It's possible that I'm doing something stupid and wrong, but I don't think a bitwite-not is what I want… Because then I'll end up with 255,254,255,.... Possibly it's because my mask is an Image? Jul 20, 2010 at 19:53
  • 1
    It depends upon the bit depth of your mask. Normally a mask should have a depth of 1 bit, which would flip the single bit from 0 to 1 and vise versa. You might need to convert your mask to a 1 bit deep image first. If you have a greater bit depth (ex 4), then yes it would flip from 0001 to 1110 and from 0000 to 1111 Jul 20, 2010 at 21:24

4 Answers 4

51

cv2.bitwise_not(mask) would help here

2
  • 1
    This is a great suggestion, but it won't work for masks with different max_value, for example if one mask is 255 and zeros and the other is 1 and zeros, because it is a bit operator.
    – Antonio
    Apr 12, 2021 at 16:41
  • it not works for me, I see no changes
    – actnmk
    Nov 12, 2021 at 10:31
41

If you have an 8-bit mask, then you should do mask = 255 - mask. cv::Mat subtraction operator is overloaded to do scalar per-element subtraction.

7

For an 8 bit mask using 255 as "on" value:

mask = cv::Mat::ones(mask.size(), mask.type()) * 255 - mask;

I'm using this one instead of Matt M solution as I'm still using OpenCV 2.1.0 for one of my projects.

0
1

I think something like this might handle the case where the input mask may have various non-zero values:

cv::Mat1b inputMask = ....;
cv::Mat1b invertedMask(inputMask.rows, inputMask.cols);

std::transform(
    inputMask.begin(), inputMask.end(), invertedMask.begin(),
    std::logical_not<uint8_t>()
);
1
  • it's not a c++ question Jul 3, 2020 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.