HSV Colour Segmentation
HSV (Hue–Saturation–Value) colour space makes it easier to isolate objects by colour under varying lighting conditions.
HSV Ranges for Common Colours
| Colour | H min | H max | S min | V min |
|---|---|---|---|---|
| Red (low) | 0 | 10 | 100 | 100 |
| Red (high) | 160 | 180 | 100 | 100 |
| Green | 40 | 80 | 50 | 50 |
| Blue | 100 | 130 | 50 | 50 |
| Yellow | 20 | 35 | 100 | 100 |
Code
python
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Detect green
lower = np.array([40, 50, 50])
upper = np.array([80, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) > 500:
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Mask", mask)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) == ord('q'):
breakTIP
Use the HSV trackbar to tune thresholds live before hardcoding them. See the OpenCV docs.