Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Color Masking
Colour masking creates a binary mask that selects only the pixels matching a target colour. It is the core technique behind colour-based object isolation.
8 min•By Priygop Team•Updated 2026
Creating and Using Masks
Creating and Using Masks
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# cv2.inRange() creates a binary mask:
# Pixels WITHIN the range → 255 (white)
# Pixels OUTSIDE the range → 0 (black)
# Detect blue colour
lower_blue = np.array([100, 100, 100])
upper_blue = np.array([130, 255, 255])
blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Clean the mask: remove noise with morphological operations
kernel = np.ones((5, 5), np.uint8)
blue_mask = cv2.morphologyEx(blue_mask, cv2.MORPH_OPEN, kernel) # Remove small noise
blue_mask = cv2.morphologyEx(blue_mask, cv2.MORPH_CLOSE, kernel) # Fill small holes
# Apply mask to extract only blue pixels
blue_only = cv2.bitwise_and(image, image, mask=blue_mask)
# Create inverted mask (everything EXCEPT blue)
inverse_mask = cv2.bitwise_not(blue_mask)
non_blue = cv2.bitwise_and(image, image, mask=inverse_mask)
print(f"Mask shape: {blue_mask.shape}")
print(f"Blue pixels: {cv2.countNonZero(blue_mask):,}")
cv2.imwrite("blue_only.jpg", blue_only)
cv2.imwrite("non_blue.jpg", non_blue)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment