Python – How to mask image with binary mask

imageimage processingnumpyopencvpython

Suppose I have a greyscale image here: enter image description here

And a binary masked image here:
enter image description here

With the same dimensions and shape. How do I generate something like this:
enter image description here

Where the values indicated by the 1 in the binary mask are the real values, and values that are 0 in the mask are null in the final image.

Best Answer

Use cv2.bitwise_and to mask an image with a binary mask. Any white pixels on the mask (values with 1) will be kept while black pixels (value with 0) will be ignored. Here's a example:

Input image (left), Mask (right)

Result after masking

Code

import cv2
import numpy as np

# Load image, create mask, and draw white circle on mask
image = cv2.imread('1.jpeg')
mask = np.zeros(image.shape, dtype=np.uint8)
mask = cv2.circle(mask, (260, 300), 225, (255,255,255), -1) 

# Mask input image with binary mask
result = cv2.bitwise_and(image, mask)
# Color background white
result[mask==0] = 255 # Optional

cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey()