in OpenCV is mask a bitwise and operation

2020-07-11 05:02发布

问题:

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

回答1:

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.



回答2:

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:

Screen 2:

Upon performing bitwise:

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

we obtain the following:

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:

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:

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



标签: c++ opencv