Skip to content

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

ColourH minH maxS minV min
Red (low)010100100
Red (high)160180100100
Green40805050
Blue1001305050
Yellow2035100100

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'):
        break

TIP

Use the HSV trackbar to tune thresholds live before hardcoding them. See the OpenCV docs.

Released under the MIT License.