In this blog post, we will be discussing how to overlay mask on an image in Python programming language. We’ll be using the OpenCV (Python Imaging Library) module to read the image and mask in the numpy format. Next, we’ll overlay a mask into orignal image using Matplotlib library. Let’s start
Step 1: Import the Required Libraries
We will accomplish our task using OpenCV and Matplotlib library. The OpenCV library is used to read, write and manipulate the images. A specific sub-module pyplot of Matplotlib will be used to plot our image, mask and overlayed result.
import cv2
from matplotlib import pyplot as plt
Step 2: Read Image and Mask using OpenCV Library
In the second step, OpenCV library read the image and convert it into NumPy array. In the following code, NumPy array of image is saved in the image variable. The image is shown in the Fig. 1.
Code:
image = cv2.imread("train_images\\32741.png")
plt.imshow(image)
Output:

Note: The mask of the above image is read by cv2.imread() in grayscale format. You can use integer 0 to read the mask in grayscale format. Fig. 2 is showing the mask of respective image.
Code:
mask = cv2.imread("Mask_Images\\32741.png", 0)
plt.imshow(mask)
Output:

Step 3: Overlay Mask on Image using Matplotlib Library
In the final step, we will use image and mask variable in ax[].imshow() and set the value of alpha=0.6 to adjust the opacity level.
Code:
fig, ax = plt.subplots(1, 3, figsize=(12,8))
ax[0].imshow(image)
ax[0].set_title('Image')
ax[1].imshow(mask)
ax[1].set_title('Mask')
ax[2].imshow(image)
ax[2].imshow(mask, alpha=0.6)
ax[2].set_title('Overlay Mask on Image')
plt.show()
Output:

Complete Code:
# Libraries
import cv2
from matplotlib import pyplot as plt
import numpy as np
# Read Images and Masks
image = cv2.imread("train_images\\32741.tiff")
mask = cv2.imread("Mask_Images\\32741.png", 0)
# Overlay Mask on Image
fig, ax = plt.subplots(1, 3, figsize=(12,8))
ax[0].imshow(image)
ax[0].set_title('Image')
ax[1].imshow(mask)
ax[1].set_title('Mask')
ax[2].imshow(image)
ax[2].imshow(mask, alpha=0.6)
ax[2].set_title('Overlay Mask on Image')
plt.show()
Reference: