Search⌘ K

Masking

Explore masking methods to isolate objects in images by applying thresholding on color channels. Learn to combine masks using intersection and union operations to target specific object areas, enhancing your skills in automated image inspection.

When we discussed the thresholding operations, we produced binary images, i.e., grayscale images that take only two values, typically 0 and 255. As their name implies, their purpose is to mask an image.

Masking is the operation of identifying the area of the objects of interest in an image and ignoring the irrelevant image areas for a given task.

Isolating objects

Let’s consider the image below. We have an inspection task for which we need to isolate the green anchor dowels. We need to create a mask that will be active (255) in the areas of the green anchor dowels and inactive (0) everywhere else.

Anchor dowels of various colors
Anchor dowels of various colors

Let’s use our thresholding skills. We can try various threshold values in line 10 in the code widget below and see if we can create a mask of the green anchor dowels.

C++
import cv2
# Load the image
original_img = cv2.imread('./images/hardware/anchor_dowels1.jpg')
# Convert to grayscale
grayscale_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
# Find a threshold to highlight only the green dowels
threshold = 150
retval, mask = cv2.threshold(grayscale_img, threshold, 255, cv2.THRESH_BINARY)
# Save the original image and the mask
cv2.imwrite('./output/0_original.png', original_img)
cv2.imwrite('./output/1_mask.png', mask)

In line 11, we create a ...