Masking with Bitwise Operation

Bitwise Operation

bitwise_and(), bitwise_not() and more

Computes bitwise conjunction of the two arrays (src1, src2) and calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.

bitwise_and()

void cv::bitwise_and

(

src1,

src2,

dst,

mask = noArray()

)

Example

bitwise_and(src1,src1,dst1, mask1)

This means dst1(I)= src1(I) & src1(I), if mask(I) !=0

Assume src[10][20] = 1111 0001 / / 8-bit data per pixel

Case 1

Since binary logic AND is X & X=X

1111 0001 & 1111 0001 = 1111 0001

The output of bitwise operation becomes

dst=src & src = src

Case 2

Since binary logic AND is X & 1=X

1111 0001 & 1111 1111 = 1111 0001

The output of bitwise operation becomes

dst=src & 1 = src

Case 3

Since binary logic AND is X & 0=0

1111 0001 & 0000 0000 = 0000 0000

The output of bitwise operation becomes all black.

Masking and Merging

dst1 and dst2 can be obtained using bitwise operation as

For both 1-CH and 3-CH images

bitwise_and(src1, src1, dst1, mask1);
bitwise_and(src2, src2, dst2, mask2);
dst3=dst1+dst2;

Also, you can apply as

dst1=src1 & mask1;         // This is NOT the same as  && operation 
dst2=src2 & mask2;
dst3=dst1 + dst2;

Last updated