Masking

From Lofaro Lab Wiki
Jump to: navigation, search

Since we are familiar with bitwise operations, we can do masking now. Masking is a very powerful techniques of image processing. Masking allows us to focus on the important portion of the image that we need.

Let’s think, we are building an image processing system that will recognize face in a picture. So the only part of the image we are interested in the image is the faces of people in there. We can construct a mask to show only the faces in the image. We have an image of the robot HUBO. Let’s say we are only interested in the face of HUBO. By using a rectangular mask we can take only the area that has the face of HUBO. Let’s explore some code to understand more deeply


import cv2
import numpy as np
image = cv2.imread('hubo.jpg',0)
cv2.imshow("Original", image)
mask1 = np.zeros(image.shape[:2], dtype = "uint8")
(cx, cy) = (image.shape[1] / 2, image.shape[0] / 2)
cv2.rectangle(mask1, (cx - 75, cy - 120), (cx + 75 , cy + 20), 255, -1)
cv2.imshow("Mask", mask1)
masked1 = cv2.bitwise_and(image, image, mask = mask1)
cv2.imshow("Rectangular Mask Applied", masked1)


We first imported our package and loaded the image. Then we constructed a Numpy array filled with zeros, with the same width and height as the image has. We then found out the center of the image by dividing the width and height by 2. Then we draw a white rectangle. We apply our mask using the cv2.bitwise_and function. The “AND” function will be true for all pixel in the image, but the important part of the function is the mask keyword. When we supply a mask in the bitwise and function it turns on the pixels that are within the mask, which is in our case the rectangle.

We can do the masking using circle also, a sample code only for the circle portion is given below,


mask = np.zeros(image.shape[:2], dtype = "uint8")
cv2.circle(mask, (cx, cy), 100, 255, -1)
masked = cv2.bitwise_and(image, image, mask = mask)
cv2.imshow("Mask", mask)
cv2.imshow("Mask Applied to Image", masked)


Mask.jpg


Maskc.jpg