Image Overlays using Bitwise Operations OpenCV-Python

In the previous blog, we learned how to overlay an image to another image using OpenCV cv2.addWeighted() function. But this approach is limited to rectangular ROI. In this blog, we will learn how to overlay non-rectangular ROI to another image.

Task:

Put the TheAILearner text image(shown in the left) above an image (Right one).

Because the TheAILearner text is non-rectangular, we will be using OpenCV cv2.bitwise_and(img1, img2, mask) where the mask is an 8-bit single channel array, that specifies elements of the output array to be changed.

For Bitwise_and you need to know the following two rules

  • Black + Any Color = Black
  • White + Any Color = That Color

Now, let’s see step by step how to do this

  • First load the two images
  • Select the region in the image where you want to put the logo. Here, I am putting this in the top left corner.
  • Now, we will create a mask. You can create a mask by a number of ways but here we will be using thresholding for this as shown in the code below. We will also create an inverse mask. Depending on the image you need to change the thresholding function parameters.

The mask and mask_inv looks like this

  • Now black out the area of logo in the roi created above using the bitwise_and as shown in the code below

This looks like this

  • Now, we will extract the logo region (with colors) from the logo image using the following code

The output looks like this

  • Now, we will simply add the above two images because black has intensity 0 so adding this doesn’t change anything and outputs the same color. This is done using the following code

The final output looks like this

So, using these simple bitwise operations we can overlay an image to another. Be careful while creating the mask as it entirely depends on the image. According to the image you need to make adjustments to the thresholding function parameters.

Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

3 thoughts on “Image Overlays using Bitwise Operations OpenCV-Python

  1. Csaba Marosi

    Hi, thanks for your post, it helped a lot!
    I created a customized function based on this, that also takes position as input, maybe it will be useful for someone:

    def occlusion(img: np.ndarray, occlusion_img: np.ndarray, pos: tuple[int, int]):
    result = img.copy()
    x, y = pos[1], pos[0]

    _, mask = cv2.threshold(occlusion_img, 254, 255, cv2.THRESH_BINARY)

    result[y:y + mask.shape[0],x: x + mask.shape[1]] &= mask

    occlusion_img_masked = occlusion_img & cv2.bitwise_not(mask)
    result[y:y + mask.shape[0],x: x + mask.shape[1]] += occlusion_img_masked

    return result

    Reply

Leave a Reply