I did not exactly understand what the "bitwise_and" operator does when used in openCV. I would also like to know about it's parameters.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The answer by @mannyglover with the US flag example is a great one! I would also just quickly add that for actual images, any pixel value above 0 would translate to 'true' (or 1 in @mannyglover's example), and '0' (pitch black) would be 'false'.
This means after doing bitwise_and, any pitch black pixel of the mask would turn that respective pixel in the original image black. (since 0 & anything = 0)
Here is an example, done in OpenCV:
Original image: stack.jpg
Mask: mask.jpg
After applying
result = cv2.bitwise_and(stack, stack, mask=mask)
: result.jpgbitwise_and
Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.
Parameters:
Here is an example found on the web: http://docs.opencv.org/trunk/d0/d86/tutorial_py_image_arithmetics.html
The general usage is that you want to get a subset of an image defined by another image, typically referred to as a "mask".
So suppose you want to "grab" the top left quadrant of an 8x8 image. You could form a mask that looks like:
You could produce the above image with Python with:
Then suppose you had an image like:
For concreteness, imagine that the above image is a simplified representation of the U.S.A. flag: stars in the top left, bars everywhere else. Suppose you wanted to form the above image. You could use the mask, and bitwise_and and bitwise_or to help you.
Now you have an image of stars:
And an image of bars:
And you want to combine them in a particular way, to form the flag, with the stars in the upper left quadrant and the bars everywhere else.
imageStarsCropped
will look like:Do you see how it was formed? The
bitwise_and
returns1
at every pixel whereimageStars
is1
ANDmask
is1
; else, it returns0
.Now let's get
imageBarsCropped
. First, let's reverse the mask:bitwise_not
turns1
's into0
's and0
's into1
's. It "flips the bits".maskReversed
will look like:Now, we will use
maskReversed
to "grab" the portion ofimageBars
that we want.imageBarsCropped
will look like:Now, let's combined the two "cropped" images to form the flag!
imageFlag
will look like:Do you see why?
bitwise_or
returns1
wheneverimageStarsCropped[r,c]==1
ORimageBarsCropped[r,c]==1
.Well, I hope this helps you to understand bitwise operations in OpenCV. These properties have a one-to-one correspondences with bitwise operations with binary numbers that the computer does to do arithmetic.