Bitwise Operators

Learn about bitwise operators and their applications.

Instead of just stacking images, we might also want to combine images. In this lesson, we’ll use bitwise operators to combine images in OpenCV. We’ll work with black and white images to better understand these operators.

What are bitwise operators?

There are four basic bitwise operatorsAND, OR, XOR, and NOT. These operators are frequently used to edit images, especially while working with masking images.

To see them in action, we’ll first create a blank image. We’ll use that blank image to draw different shapes and learn how bitwise operators can be used with them.

To create a blank image, we use the Mat::zeros() function of the OpenCV library.

cv::Mat circleA = cv::Mat::zeros(cv::Size(600,600), CV_8UC3);

This function requires two parameters:

  • The size of the blank image
  • CV_8UC3, which is an unsigned integer of 8 bits with three channels

We can identify this second parameter using the identifier in the form CV_<bit-depth>{U|S|F}C(<number_of_channels>). Here, U is the unsigned integer type, S is the signed integer type, and F is the float type.

In the code below, we draw a rectangle and a circle on the blank image. We’ll use these two shapes to understand all the bitwise operators.

cv::rectangle(rectangleA, cv::Point(30, 30), cv::Point(570, 570), cv::Scalar(255,255,255), -1);
  • Point(30, 30) is the top left corner point of where we want to draw the rectangle.
  • Point(570, 570) is the bottom right corner point of where we want to draw the rectangle.
  • Scalar(255,255,255) adds the white color to the rectangle.
  • -1 is the thickness of the rectangle. It’ll fill the rectangle with the respective color.
cv::circle(circleA, cv::Point(300, 300), 300, cv::Scalar(255,255,255), -1);
  • Point(300, 300) is the center point around which the circle will be drawn.
  • 300 is the radius of the circle.
  • Scalar(255,255,255) adds white color to the circle.
  • -1 is the thickness of the circle. It’ll fill the rectangle with the respective color.

Get hands-on with 1400+ tech skills courses.