Introduction
A bitwise operator in image processing is used to perform bitwise operations on binary numerals that involve the manipulation of individual bits. Broadly when we do masking, we see for either black or white or any colour and perform operations according to it. We can also perform bitwise operations on the image when we need to extract only the required part of the image. Consider a situation where we need to pull an irregularly shaped object from a photo and paste it on another embodiment. That's when we use a bitwise operation on the image to separate the foreground from the background. We can even perform the morphological structuring of an image using a bitwise operator. The morphological process extracts the boundary of an image.Here we will work with OpenCV python in which there are various inbuilt bitwise methods such as bitwise_and, bitwise_or, and bitwise_xor operations. We will display the image using the imshow( ) method provided by OpenCV. We must import the Imshow explicitly as it's not implicit in Google collab.
The truth table of different bitwise operations is shown in the table below.
Also See, Image Sampling
A | B | AND: A & B | OR: A | B | XOR: A ^ B |
---|---|---|---|---|
T | T | 1 | 1 | 0 |
T | F | 0 | 1 | 1 |
F | T | 0 | 1 | 1 |
F | F | 0 | 0 | 0 |
Implementation
Importing the necessary libraries.
import cv2
from google.colab.patches import cv2_imshow
import numpy as np
Creating a black image filled with zeros to act as the background for various photos. As all the entries are filled with zeros, the image will be black.
img1 = np.zeros((300,300),dtype="uint8")
Creating a rectangle out of the Black image. The intensity of every rectangle pixel is more significant than zero to get a brighter image.
cv2.rectangle(img1, (100,100), (250,250), 255, -1)
cv2_imshow(img1)
Similarly, we can create a disc-shaped out of the black image.
img2 = np.zeros((300,300), dtype="uint8")
cv2.circle(img2, (150, 150), 90,255, -1)
cv2_imshow(img2)
Now it's time to perform bitwise operations on the two images. If the intensity of any pixel is lesser than the intensity of others, the resultant power will be lower. So, the intersection part of both the images is black.
and_bitwise = cv2.bitwise_and(img1,img2)
cv2_imshow(and_bitwise)
If the intensity of any one of the pixels is high, the resultant power will increase. We can see that most of the parts are bright in the output because of the union of the two images.
or_bitwise = cv2.bitwise_or(img1,img2)
cv2_imshow(or_bitwise)
If the intensities of the two pixels are equal, then the resultant power will always be lower; hence the intersection part of two images will result in a black image.
xor_bitwise = cv2.bitwise_xor(img1,img2)
cv2_imshow(xor_bitwise)
Also read, Sampling and Quantization