Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in OpenCV is mask a bitwise and operation

Tags:

c++

opencv

I'm starting with opencv in python and I have a questions about how mask is applied for

bitwise_and(src1, src2, mask=mask)

Which of these describes the implementation:

  • A. all bitwise, mask first

    1. src1 is ANDed with mask
    2. src2 is ANDed with mask
    3. what's left of src1 and src2 are ANDed together
  • B. all bitwise, images first

    1. src1 is ANDed with src2
    2. result is ANDed with mask
  • C. conditional AND

    1. mask is "iterated" through (eg a loop)
    2. for each pixel in mask, if it's nonzero, then corresponding pixels in src1,src2 are ANDed and copied to output

I would think the performance characteristics of each could vary slightly.

Which of these (or how else) is the actual implementation? (and why, if I may ask)

I was trying to look at the source, but couldn't quite make out what they did: https://github.com/opencv/opencv/blob/ca0b6fbb952899a1c7de91b909d3acd8e682cedf/modules/core/src/arithm.cpp

like image 742
AwokeKnowing Avatar asked Mar 21 '17 07:03

AwokeKnowing


2 Answers

I have worked out two implementations of cv2.bitwise_and() using color images and binary images.

1. Using Binary Images

Let us assume we have the following binary images:

Screen 1:

enter image description here

Screen 2:

enter image description here

Upon performing bitwise:

fin = cv2.bitwise_and(screen1, screen2)
cv2.imwrite("Final image.jpg", fin)

we obtain the following:

enter image description here

2. Performing masking on color images:

You can mask out a certain region of a given color image using the same function as well.

Consider the following image:

enter image description here

and consider Screen 1 (given above) to be the mask

fin = cv2.bitwise_and(image, image, mask = screen1)
cv2.imwrite("Masked image.jpg", fin)

gives you:

enter image description here

Note: While performing bitwise AND operation the images must have the same size

like image 199
Jeru Luke Avatar answered Sep 21 '22 13:09

Jeru Luke


If you look at the docs, the 3rd parameter is a destination image which you missed.

This operation will change the values of the destination image only if the mask says so (in this case it will do the bitwise and of the two source images). For the pixels that are not in the mask, the destination will contain the same values that it contained before.

like image 35
user2518618 Avatar answered Sep 21 '22 13:09

user2518618