Color-Based Segmentation
Colour-based segmentation isolates image regions by their colour. Combined with HSV masking from Module 4, it is a powerful technique for segmenting objects with distinctive colours.
10 min•By Priygop Team•Updated 2026
Colour Segmentation Pipeline
Colour Segmentation Pipeline
import cv2
import numpy as np
def segment_by_colour(image_path, lower_hsv, upper_hsv, output_path):
"""Segment and extract objects by colour range."""
image = cv2.imread(image_path)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Create colour mask
mask = cv2.inRange(hsv, np.array(lower_hsv), np.array(upper_hsv))
# Clean mask with morphological operations
kernel = np.ones((7, 7), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) # Remove noise
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # Fill gaps
mask = cv2.dilate(mask, kernel, iterations=1) # Slightly expand
# Extract colour region
segmented = cv2.bitwise_and(image, image, mask=mask)
# Create a result with white background for the non-masked area
background = np.ones_like(image) * 255 # White background
inverse_mask = cv2.bitwise_not(mask)
background_part = cv2.bitwise_and(background, background, mask=inverse_mask)
result = cv2.add(segmented, background_part)
cv2.imwrite(output_path, result)
print(f"Segmented coverage: {cv2.countNonZero(mask)/mask.size*100:.1f}%")
return result, mask
# Example: segment green plants from a garden image
segment_by_colour(
"garden.jpg",
lower_hsv=[35, 60, 60],
upper_hsv=[85, 255, 255],
output_path="plants_segmented.jpg"
)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment