Masking
Masking is the technique of using a binary image (the mask) to control which pixels are visible in the output. It is the core mechanism behind all object extraction.
8 min•By Priygop Team•Updated 2026
Advanced Masking Techniques
Advanced Masking Techniques
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
h, w = image.shape[:2]
# --- RECTANGULAR MASK ---
rect_mask = np.zeros((h, w), dtype=np.uint8)
cv2.rectangle(rect_mask, (100, 100), (400, 300), 255, -1) # Filled rectangle
rect_region = cv2.bitwise_and(image, image, mask=rect_mask)
# --- CIRCULAR MASK ---
circle_mask = np.zeros((h, w), dtype=np.uint8)
cv2.circle(circle_mask, (w//2, h//2), min(w, h)//3, 255, -1)
circle_region = cv2.bitwise_and(image, image, mask=circle_mask)
# --- POLYGON MASK ---
polygon_mask = np.zeros((h, w), dtype=np.uint8)
points = np.array([[100, 200], [300, 50], [500, 200], [400, 400], [200, 400]])
cv2.fillPoly(polygon_mask, [points], 255)
polygon_region = cv2.bitwise_and(image, image, mask=polygon_mask)
# --- COMBINE MASKS ---
combined = cv2.bitwise_or(rect_mask, circle_mask)
combined_region = cv2.bitwise_and(image, image, mask=combined)
# --- INVERT MASK (extract everything outside the mask) ---
inverted = cv2.bitwise_not(rect_mask)
outside_rect = cv2.bitwise_and(image, image, mask=inverted)
cv2.imwrite("circle_mask.jpg", circle_region)
cv2.imwrite("polygon_mask.jpg", polygon_region)
print("Masking examples complete")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment