Ask Your Question

how to make a composite mask?

asked 2017-01-23 16:09:34 -0500

jp2112 gravatar image

I have several masks that I created using the compare() function. They are all CV_8U type. Now I want to make a composite mask in one step, if possible, using all of these submasks. I know how to make a logical OR'd mask using

final_mask = mask1 + mask2 + mask3...

but I want a logical AND'd mask. Doing this:

final_mask = mask1 * mask2 * mask3...

hangs up my application, likely because the result blows up too large for the saturate_cast<> operation. How do I do this? I see there's a bitwise_and() but I want pixelwise. Thanks.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2017-01-23 20:02:38 -0500

berak gravatar image

there are binary operations in opencv , use:

mask = mask1 | mask2 | mask3 // for OR (not + !)
mask = mask1 & mask2 & mask3 // for AND
edit flag offensive delete link more



That makes it simple, thanks for pointing it out. I couldn't find any description of this in the documentation.

jp2112 gravatar imagejp2112 ( 2017-01-23 22:24:45 -0500 )edit

answered 2017-01-23 16:38:57 -0500

Tetragramm gravatar image

If the values in the masks are all the same, whether it's 255 or 1, bitwise_and will do what you want.

edit flag offensive delete link more


I can't guarantee that the values are all the same, just that they are zero or nonzero. One mask might have 0 and 255 values but another may have 0 and 8bit grayscale values and another may have 0 and 1 values.

Am I correct in saying that if you were to bitwise_and a mask of all 128s with a mask of all 1s you would get a mask of all 0s, but pixelwise should return a mask of all 255 which is what I want since both masks contain all nonzero (i.e. true) pixels.

Sounds like there is no convenient command for this desired action.

jp2112 gravatar imagejp2112 ( 2017-01-23 16:53:31 -0500 )edit

You just need to make them 255, then bitwise_and.

Just call maskX > 0 and carry on.

Tetragramm gravatar imageTetragramm ( 2017-01-23 17:12:10 -0500 )edit

what is maskX?

jp2112 gravatar imagejp2112 ( 2017-01-23 18:59:13 -0500 )edit

Anyhow, it would seem trivial for OpenCV to add two mask-level functions that treat mask elements pixelwise. Nice and clean.

i.e. for each array pixel, mask_or() would be zero, zero = 0 zero, nonzero = 255 nonzero, nonzero = 255

mask_and() would be zero, zero = 0 zero, nonzero = 0 nonzero, nonzero = 255

jp2112 gravatar imagejp2112 ( 2017-01-23 19:10:11 -0500 )edit

All it would do is maskX > 0 and then the normal bit-wise function. maskX is whichever mask you're using now. So mask = (mask1 > 0) & (mask2 > 0) & ... This is the same as using bitwise_and

Tetragramm gravatar imageTetragramm ( 2017-01-23 20:12:13 -0500 )edit

Question Tools

1 follower


Asked: 2017-01-23 16:09:34 -0500

Seen: 3,428 times

Last updated: Jan 23 '17