Title: OpenCV Bitwise AND, OR, XOR, and NOT - PyImageSearch

URL Source: https://pyimagesearch.com/2021/01/19/opencv-bitwise-and-or-xor-and-not/

Published Time: 2021-01-20T04:42:00+00:00

Markdown Content:
In this tutorial, you will learn how to apply bitwise AND, OR, XOR, and NOT with OpenCV.

![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20450'%3E%3C/svg%3E)

In our previous tutorial on [_Cropping with OpenCV_](https://pyimagesearch.com/2021/01/19/crop-image-with-opencv/), you learned how to crop and extract a Region of Interest (ROI) from an image.

In that particular example, our ROI had to be _rectangular_ . . . but what if you wanted to crop a _non-rectangular_ region?

What would you do then?

The answer is to apply both bitwise operations and masking (we’ll discuss how to do that in our guide on [image masking with OpenCV](https://pyimagesearch.com/2021/01/19/image-masking-with-opencv/)).

For now, we’ll cover the basic bitwise operations — and in the next blog post, we’ll learn how to utilize these bitwise operations to construct masks.

**To learn how to apply bitwise operators with OpenCV, _just keep reading._**

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

Before we get too far into this tutorial, I’m going to assume that you understand the four basic bitwise operators:

1.  AND
2.  OR
3.  XOR (exclusive OR)
4.  NOT

If you’ve never worked with bitwise operators before, I suggest you read [this excellent (and highly detailed) guide from RealPython](https://realpython.com/python-bitwise-operators/).

While you don’t _have_ to review that guide, I find that readers who understand the basics of applying bitwise operators to digits can quickly grasp bitwise operators applied to images.

**Regardless, computer vision and image processing are highly visual, and I’ve crafted the examples in this tutorial to ensure you understand how bitwise operators are applied to images with OpenCV.**

We’ll start this guide by configuring our development environment and then reviewing our project directory structure.

From there, we’ll implement a Python script to perform the AND, OR, XOR, and NOT bitwise operators with OpenCV.

We’ll conclude this guide with a discussion of our results.

### **Configuring your development environment**

To follow this guide, you need to have the OpenCV library installed on your system.

Luckily, OpenCV is pip-installable:

$ pip install opencv-contrib-python

**If you need help configuring your development environment for OpenCV, I _highly recommend_ that you read my** [**_pip install OpenCV_ guide**](https://pyimagesearch.com/2018/09/19/pip-install-opencv/) — it will have you up and running in a matter of minutes.

### **Having problems configuring your development environment?**

[![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20251'%3E%3C/svg%3E)](https://pyimagesearch.com/pyimagesearch-plus/)

**Figure 1:** Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) — you will be up and running with this tutorial in a matter of minutes.

All that said, are you:

*   Short on time?
*   Learning on your employer’s administratively locked system?
*   Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?
*   **Ready to run the code _right now_ on your Windows, macOS, or Linux systems?**

Then join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) today!

**Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides that are _pre-configured_ to run on Google Colab’s ecosystem right in your web browser!** No installation required.

And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!

### **Project structure**

Ready to learn how to apply bitwise operators using OpenCV?

Great, let’s get started.

Be sure to use the **_“Downloads”_** section of this guide to access the source code, and from there, take a look at our project directory structure:

$ tree . --dirsfirst
.
└── opencv\_bitwise.py

0 directories, 1 file

We have just a single script to review today, `opencv_bitwise.py`, which will apply the AND, OR, XOR, and NOR operators to example images.

By the end of this guide, you’ll have a good understanding of how to apply bitwise operators with OpenCV.

### **Implementing OpenCV AND, OR, XOR, and NOT bitwise operators**

In this section, we will review four bitwise operations: AND, OR, XOR, and NOT. While very basic and low level, these four operations are paramount to image processing — especially when working with masks later in this series.

Bitwise operations function in a binary manner and are represented as grayscale images. A given pixel is turned “off” if it has a value of zero, and it is turned “on” if the pixel has a value greater than zero.

Let’s proceed and jump into some code:

\# import the necessary packages
import numpy as np
import cv2

# draw a rectangle
rectangle = np.zeros((300, 300), dtype="uint8")
cv2.rectangle(rectangle, (25, 25), (275, 275), 255, -1)
cv2.imshow("Rectangle", rectangle)

# draw a circle
circle = np.zeros((300, 300), dtype = "uint8")
cv2.circle(circle, (150, 150), 150, 255, -1)
cv2.imshow("Circle", circle)

For the first few lines of code import, the packages we will need include: NumPy and our OpenCV bindings.

We initialize our rectangle image as a _300 x 300_ NumPy array on **Line 6**. We then draw a _250 x 250_ white rectangle at the center of the image.

Similarly, on **Line 11,** we initialize another image to contain our circle, which we draw on **Line 12** again centered in the middle of the image, with a radius of 150 pixels.

**Figure 2** displays our two shapes:

![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20388'%3E%3C/svg%3E)

**Figure 2:** Our initial input images onto which we’ll perform bitwise operations.

If we consider these input images, we’ll see that they only have two pixel intensity values — either the pixel is `0` (black) or the pixel is greater than zero (white). **We call images that only have two pixel intensity values binary images.**

Another way to think of binary images is like an on/off switch in our living room. Imagine each pixel in the _300 x 300_ image is a light switch. If the switch is **_off_**, then the pixel has a value of zero. But if the pixel is **_on_**, it has a value greater than zero.

In **Figure 2**, we can see the white pixels that comprise the rectangle and circle, respectively, all have pixel values that are _on_, whereas the surrounding pixels have a value of _off_.

Keep this notion of on/off as we demonstrate bitwise operations:

\# a bitwise 'AND' is only 'True' when both inputs have a value that
# is 'ON' -- in this case, the cv2.bitwise\_and function examines
# every pixel in the rectangle and circle; if \*BOTH\* pixels have a
# value greater than zero then the pixel is turned 'ON' (i.e., 255)
# in the output image; otherwise, the output value is set to
# 'OFF' (i.e., 0)
bitwiseAnd = cv2.bitwise\_and(rectangle, circle)
cv2.imshow("AND", bitwiseAnd)
cv2.waitKey(0)

As I mentioned above, a given pixel is turned “on” if it has a value greater than zero, and it is turned “off” if it has a value of zero. Bitwise functions operate on these binary conditions.

To utilize bitwise functions, we assume (in most cases) that we are comparing two pixels (the only exception is the NOT function). We’ll compare each of the pixels and then construct our bitwise representation.

Let’s quickly review our binary operations:

*   **AND:** A bitwise AND is true _if and only if_ both pixels are greater than zero.
*   **OR:** A bitwise OR is true _if either_ of the two pixels is greater than zero.
*   **XOR:** A bitwise XOR is true _if and only if_ one of the two pixels is greater than zero, _but not both._
*   **NOT:** A bitwise NOT inverts the “on” and “off” pixels in an image.

On **Line 21,** we apply a bitwise AND to our rectangle and circle images using the `cv2.bitwise_and` function. As the list above mentions, a bitwise AND is true if and only if both pixels are greater than zero. The output of our bitwise AND can be seen in **Figure 3**:

![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20525%20554'%3E%3C/svg%3E)

**Figure 3:** Applying a bitwise AND with OpenCV.

We can see that edges of our square are lost — this makes sense because our rectangle does not cover as large of an area as the circle, and thus both pixels are not “on.”

Let’s now apply a bitwise OR:

\# a bitwise 'OR' examines every pixel in the two inputs, and if
# \*EITHER\* pixel in the rectangle or circle is greater than 0,
# then the output pixel has a value of 255, otherwise it is 0
bitwiseOr = cv2.bitwise\_or(rectangle, circle)
cv2.imshow("OR", bitwiseOr)
cv2.waitKey(0)

We apply a bitwise OR on **Line 28** using the `cv2.bitwise_or` function. A bitwise OR is true if either of the two pixels is greater than zero. Take a look at the output of the bitwise OR in **Figure 4**:

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20467%20500'%3E%3C/svg%3E)

**Figure 4:** Applying a bitwise OR with OpenCV.

In this case, our square and rectangle have been combined.

Next is the bitwise XOR:

\# the bitwise 'XOR' is identical to the 'OR' function, with one
# exception: the rectangle and circle are not allowed to \*BOTH\*
# have values greater than 0 (only one can be 0)
bitwiseXor = cv2.bitwise\_xor(rectangle, circle)
cv2.imshow("XOR", bitwiseXor)
cv2.waitKey(0)

We apply the bitwise XOR on **Line 35** using the `cv2.bitwise_xor` function.

An XOR operation is true if and only if one of the two pixels is greater than zero, but both pixels cannot be greater than zero.

The output of the XOR operation is displayed in **Figure 5:**

![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20465%20500'%3E%3C/svg%3E)

**Figure 5:** Applying a bitwise XOR with OpenCV.

Here, we see that the center of the square has been removed. Again, this makes sense because an XOR operation cannot have both pixels greater than zero.

Finally, we arrive at the bitwise NOT function:

\# finally, the bitwise 'NOT' inverts the values of the pixels;
# pixels with a value of 255 become 0, and pixels with a value of 0
# become 255
bitwiseNot = cv2.bitwise\_not(circle)
cv2.imshow("NOT", bitwiseNot)
cv2.waitKey(0)

We apply a bitwise NOT on **Line 42** using the `cv2.bitwise_not` function. Essentially, the bitwise NOT function flips pixel values. All pixels that are greater than zero are set to zero, and all pixels that are equal to zero are set to `255`:

![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20680%20370'%3E%3C/svg%3E)

**Figure 6:** Applying a bitwise NOT with OpenCV.

Notice how our circle has been _inverted_ — initially, the circle was white on a black background, and now the circle is black on a white background.

### **OpenCV bitwise AND, OR, XOR, and NOT results**

To perform bitwise operations with OpenCV, be sure to access the **_“Downloads”_** section of this tutorial to download the source code.

From there, open a shell and execute the following command:

$ python opencv\_bitwise.py

Your output should match mine from the previous section.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

**Summary**
-----------

In this tutorial, you learned how to perform bitwise AND, OR, XOR, and NOT using OpenCV.

While bitwise operators may not seem useful by themselves, they’re _necessary_ when you start working with alpha blending and masking, a concept that we’ll begin to discuss in another blog post.

Take the time to practice and become familiar with bitwise operations now before proceeding.

**To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), _simply enter your email address in the form below!_**

![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!