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!
HSV Color Space
HSV (Hue, Saturation, Value) is the most useful colour space for colour-based object detection. It separates the colour type (hue) from brightness (value), making detection robust to lighting changes.
What is HSV?
HSV stands for Hue, Saturation, Value:
Hue: the colour type (0–179 in OpenCV)
- 0 and 179: Red
- 30: Yellow
- 60: Green
- 90: Cyan
- 120: Blue
- 150: Magenta
Saturation: how vivid the colour is (0–255)
- 0: grey (no colour)
- 255: fully saturated (pure colour)
Value: the brightness (0–255)
- 0: black
- 255: fully bright
Why HSV is useful: in BGR, changing the lighting changes all three channel values for the same colour. In HSV, only the Value channel changes — the Hue stays the same. This makes HSV ideal for detecting colours regardless of lighting.
Machine Learning follows a structured pipeline from data to deployment
Converting to HSV
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
# Convert to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Split HSV channels
h, s, v = cv2.split(hsv)
print(f"Hue range: {h.min()} to {h.max()}")
print(f"Saturation range: {s.min()} to {s.max()}")
print(f"Value range: {v.min()} to {v.max()}")
# Check the HSV value of a specific pixel
row, col = 100, 150
bgr_pixel = image[row, col]
hsv_pixel = hsv[row, col]
print(f"Pixel at ({row},{col}):")
print(f" BGR: B={bgr_pixel[0]} G={bgr_pixel[1]} R={bgr_pixel[2]}")
print(f" HSV: H={hsv_pixel[0]} S={hsv_pixel[1]} V={hsv_pixel[2]}")
# HSV values for common colours (OpenCV ranges: H=0-179, S=0-255, V=0-255)
colour_ranges = {
"Red (lower)": ([0, 100, 100], [10, 255, 255]),
"Red (upper)": ([160, 100, 100], [179, 255, 255]),
"Green": ([35, 100, 100], [85, 255, 255]),
"Blue": ([100, 100, 100], [130, 255, 255]),
"Yellow": ([20, 100, 100], [35, 255, 255]),
}
print("\nColour detection ranges (HSV):")
for colour, (lower, upper) in colour_ranges.items():
print(f" {colour:15s}: H={lower[0]}-{upper[0]}, S={lower[1]}-{upper[1]}")