In this OpenCV Python article we are going to create an example of Bitwise Operations On Images,
this includes bitwise AND, OR, NOT and XOR operations. They will be highly useful while
extracting any part of the image , defining and working with non rectangular ROI etc. below we
will see an example on how to change a particular region of an image.
You can check my previous articles on Python OpenCV
1: OpenCV Python Introduction And Reading Images
2: OpenCV Python Writing o An Image
3: OpenCV Python Reading Image In Matplotlib Graph
4: OpenCV Python Drawing Shapes
5: OpenCV Python Arithmetic Operations
6: OpenCV Python Image Blending
So this is the complete source code for OpenCV Python Bitwise Operations On Images
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import cv2 import numpy as np img1 = np.zeros((300, 300), dtype="uint8") cv2.rectangle(img1, (100, 100), (250, 250), 255, -1) cv2.imshow("Image 1", img1) img2 = np.zeros((300, 300), dtype="uint8") cv2.circle(img2, (150, 150), 90, 255, -1) cv2.imshow("Image 2", img2) rect_and_circle = cv2.bitwise_and(img1,img2) cv2.imshow("AND operation",rect_and_circle) rect_or_circle = cv2.bitwise_or(img1,img2) cv2.imshow("OR operation",rect_or_circle) rect_xor_circle = cv2.bitwise_xor(img1,img2) cv2.imshow("XOR Operation",rect_xor_circle) rect_xor_circle2 = cv2.bitwise_xor(img1,img2) cv2.imshow("XOR Operation",rect_xor_circle2) cv2.waitKey(0) cv2.destroyAllWindows() |
These line of code are for drawing of our images shapes in OpenCV, basically first we have created
an empty image using Numpy and after that we have created one rectangle and one circle, because
we want to do our OpenCV Bitwise Operations.
1 2 3 4 5 6 7 |
img1 = np.zeros((300, 300), dtype="uint8") cv2.rectangle(img1, (100, 100), (250, 250), 255, -1) cv2.imshow("Image 1", img1) img2 = np.zeros((300, 300), dtype="uint8") cv2.circle(img2, (150, 150), 90, 255, -1) cv2.imshow("Image 2", img2) |
In here we are going to do our OpenCV Bitwise Operations, there are different operations
that we want to perform like AND,OR and XOR operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
rect_and_circle = cv2.bitwise_and(img1,img2) cv2.imshow("AND operation",rect_and_circle) rect_or_circle = cv2.bitwise_or(img1,img2) cv2.imshow("OR operation",rect_or_circle) rect_xor_circle = cv2.bitwise_xor(img1,img2) cv2.imshow("XOR Operation",rect_xor_circle) rect_xor_circle2 = cv2.bitwise_xor(img1,img2) cv2.imshow("XOR Operation",rect_xor_circle2) |
Run the complete code and this will be the result
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email