OpenCV: Invert a mask?

Question:

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.

Asked By: David Wolever

||

Answers:

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.

Answered By: Matt Montag

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.

Answered By: Andres Hurtis

cv2.bitwise_not(mask) would help here

Answered By: Rikesh Subedi

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>()
);
Answered By: Owen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.