OpenCV

Masking in OpenCV

Masking is a common technique to extract the Region of Interest (ROI). In openCV, it is possible to construct arbitrary masking shape using draw function and bitwise operation.

In this example code below , we draw a circle and create a masked image using a bitwise AND operation as shown below:

import cv2 as cv
import numpy as np

img = cv.imread('./images/pokemon.jpg')
cv.imshow('Original image', img)

blank = np.zeros(img.shape[:2], dtype='uint8')
cv.imshow('Blank Image', blank)

circle = cv.circle(blank, (img.shape[1]//2,img.shape[0]//2),200,255, -1)
cv.imshow('Mask',circle)

masked = cv.bitwise_and(img,img,mask=circle)
cv.imshow('Masked Image', masked)

cv.waitKey(0)

Original image before masking:

Before OpenCV masking

Mask

mask

Output image after masking:

masked image

References:

Relevant Courses

April 14, 2021