OpenCV Python ŌĆō How to perform bitwise NOT operation on an image?
In image processing, bitwise NOT operation is one of the fundamental operations that you may use frequently. This operation is used to invert the color of an image and it is pretty straightforward to perform this operation in OpenCV Python. In this tutorial, we will teach you how to perform bitwise NOT operation on an image in OpenCV Python.
Prerequisites
Before we get start, make sure you have installed the OpenCV package using pip installer in your Python environment. If you haven’t installed it yet, run the following command to install it from the terminal:
pip install opencv-python
Bitwise NOT operation
Bitwise NOT operation inverts the pixel intensity on each pixel across all color channels of an image. This will result in an inverted binary image with the same size as the input image. The bitwise NOT operation can be performed using the cv2.bitwise_not()
function in OpenCV Python.
Here’s the syntax of the cv2.bitwise_not()
function:
cv2.bitwise_not(src[, dst[, mask]])
src
: the input imagedst
: the output image of the same size and type as the input image. If it is not specified, the function creates onemask
: the optional operation mask
Example
Let’s take a look at an example. We will start by loading an image using OpenCV and displaying it on the screen.
import cv2
img = cv2.imread('input-image.jpg')
cv2.imshow('Original Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In the above code, we have loaded the input image ‘input-image.jpg’ using the cv2.imread()
function and displayed it on the screen using the cv2.imshow()
function. The cv2.waitKey(0)
function is used to wait indefinitely for a key event to occur, and the cv2.destroyAllWindows()
function is used to close all the windows.
Now, we will perform the bitwise NOT operation on the input image, and display the resulting image on the screen.
not_img = cv2.bitwise_not(img)
cv2.imshow('Bitwise NOT Image', not_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In the above code, we have performed the bitwise NOT operation on the input image using the cv2.bitwise_not()
function and stored the resulting image in the not_img
variable. Then, we have displayed the resulting image on the screen using the cv2.imshow()
function, waited for a key event using the cv2.waitKey(0)
function, and finally closed all the windows using the cv2.destroyAllWindows()
function.
Conclusion
In this tutorial, we have learned how to perform bitwise NOT operation on an image in OpenCV Python using the cv2.bitwise_not()
function. The bitwise NOT operation is a simple yet powerful operation in image processing, and it can be used for various applications such as object detection, image segmentation, and more.