Bitwise operations

Bitwise operation is one very important image processing tools especially when we want to do masking. We will review four bitwise operations that are needed for bitwise operation in image which are AND,OR, XOR and NOT.

Bitwise operations are performed in binary way. It is represented as grayscale image. The main concept behind bitwise operation is a pixel is turned off if it has zero value and a pixel is turned on if a pixel has greater than zero value. To perform and understand the bitwise operations, first we will make one rectangle and one circle images. We will then run bitwise operations on the images. Let’s go into some code and examine what happens

import cv2
import numpy as np
rectangle = np.zeros((350, 350), dtype = "uint8")
cv2.rectangle(rectangle, (35, 35), (300, 300), 255, -1)
cv2.imshow("Rectangle", rectangle)
circle = np.zeros((350, 350), dtype = "uint8")
cv2.circle(circle, (175, 175), 150, 255, -1)
cv2.imshow("Circle", circle)
And = cv2.bitwise_and(rectangle, circle)
cv2.imshow("AND", And)
Or = cv2.bitwise_or(rectangle, circle)
cv2.imshow("OR", Or)
Xor = cv2.bitwise_xor(rectangle, circle)
cv2.imshow("XOR", Xor)
Not = cv2.bitwise_not(circle)
cv2.imshow("NOT", Not)
cv2.waitKey(0)

First we drawn one image of 350X350 pixels and put a white rectangle of 265X265 onto that. We also drawn another image of 350X350 and drawn a white circle in it.

After than we run four bitwise operations on the two images. As we said earlier, a given pixel is turned on if it has a value greater than zero. It turns off when the value is zero. So for and operation, it’s true only when both the pixel has value more than zero. See the result of “And” operation below, it will help you understand.

Then we performed the OR operation. This operations makes the pixel true if either of the two pixels is true. It will not be turned on if one is more than zero and other is not. The XOR operation is true for the region where both the pixels have value greater than zero but not simultaneously. See the image below and you understand better. The areas are turned on when the circle and rectangle doesn’t fall into on another.

A bitwise NOT operation will turn off the places which are Turned ON region. NOT operation is done on single image. Here we have done it for the circle.