table of Contents
Common bitwise logic operations
In OpenCV, common bitwise arithmetic functions are shown in the following table:
Function name | meaning |
---|---|
bitwise_and() | Bitwise and |
bitwise_or() | Bitwise or |
bitwise_xor() | Bitwise XOR |
bitwise_not() | Bitwise negation |
Bitwise AND operation
In the bitwise AND operation of mathematics, the simple summary is that only when the corresponding two binary bits are both 1, the result bit is 1. In python, the bitwise AND operation is performed through the "&" symbol, and the specific operation results are as follows:
Count 1 | Count 2 | result | Corresponding python code |
---|---|---|---|
0 | 0 | 0 | 0&0 |
0 | 1 | 0 | 0&1 |
1 | 0 | 0 | 1&0 |
1 | 1 | 1 | 1&1 |
Bitwise AND operation is to perform operations on the corresponding position after converting the value to binary. For example, the blogger randomly takes two pieces of data here, and the calculation results are as follows:
Numerical value | Decimal | Binary result |
---|---|---|
Value 1 | 165 | 10100101 |
Value 2 | 122 | 01111010 |
result | 32 | 00100000 |
Mask image
To obtain the mask image, we need to first introduce the bitwise AND function in OpenCV: cv2.bitwise_and(). The specific syntax is:
dst=cv2.bitwise_and(src1,src2[,mask])
dst: Indicates that the input value has the same size array output value.
src1: represents the input value of the first array or scalar type
src2: represents the input value of the second array or scalar type
mask: represents the optional operation mask, 8-bit single-channel array
Through the above bitwise AND calculation, we know that any image is not 0 as long as it is not black. Therefore, we will get 1 if we calculate the bitwise AND of black 0 with any number. In this way, we can remove the parts that we don't want to display.
First, we need to construct a mask image, the specific code is as follows:
a = cv2.imread("2_2.png", 1)
b=np.zeros(a.shape,dtype=np.uint8)
b[100:400,200:400]=255
Here b is the mask image, and the white part is the part of the image we need to intercept. Here [100:400,200:400], you can imagine the image as a coordinate system, the upper left corner (100, 200), the lower right corner (200, 400).
After running, the mask image b and original image a are as follows:
Through the mask image, keep the required image
Now that we have obtained the mask image, we can directly calculate it through the function provided by OpenCV. The specific code is as follows:
import cv2
import numpy as np
a = cv2.imread("2_2.png", 1)
b=np.zeros(a.shape,dtype=np.uint8)
b[100:400,200:400]=255
c=cv2.bitwise_and(a,b)
cv2.imshow("a", a)
cv2.imshow("b", b)
cv2.imshow("c", c)
cv2.waitKey()
cv2.destroyAllWindows()
After running, the display effect is as follows: