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 Detection
Colour detection identifies pixels of a specific colour in an image. It is a fundamental technique used in object tracking, quality inspection, and robotics.
10 min•By Priygop Team•Updated 2026
Detecting a Colour with HSV Masking
Detecting a Colour with HSV Masking
import cv2
import numpy as np
def detect_colour(image_path, colour_name):
"""Detect a specific colour in an image using HSV masking."""
image = cv2.imread(image_path)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define HSV ranges for different colours
ranges = {
"red": [
(np.array([0, 100, 100]), np.array([10, 255, 255])),
(np.array([160, 100, 100]), np.array([179, 255, 255])),
],
"green": [(np.array([35, 100, 100]), np.array([85, 255, 255]))],
"blue": [(np.array([100, 100, 100]), np.array([130, 255, 255]))],
"yellow":[(np.array([20, 100, 100]), np.array([35, 255, 255]))],
}
colour = colour_name.lower()
if colour not in ranges:
print(f"Colour '{colour}' not in database")
return
# Create mask by combining all ranges for this colour
mask = np.zeros(hsv.shape[:2], dtype=np.uint8)
for lower, upper in ranges[colour]:
mask |= cv2.inRange(hsv, lower, upper)
# Count detected pixels
detected_pixels = cv2.countNonZero(mask)
total_pixels = mask.shape[0] * mask.shape[1]
percentage = detected_pixels / total_pixels * 100
print(f"Colour '{colour}' detected:")
print(f" Pixels: {detected_pixels:,} / {total_pixels:,}")
print(f" Coverage: {percentage:.2f}% of image")
# Apply mask to original image
result = cv2.bitwise_and(image, image, mask=mask)
cv2.imwrite(f"detected_{colour}.jpg", result)
cv2.imwrite(f"mask_{colour}.jpg", mask)
detect_colour("photo.jpg", "blue")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment