In this lesson, we will analyze a basic but important tool for identifying colors through a mask. We’re going to see in this video how to detect colors through HSV Color space on Opencv with Python.

HSV corresponds to:
Hue is the color
Saturation is the greyness
Value is the brightness

Understanding the concepts of balancing these three elements, we can implement a basic object recognition based on colors. In this tutorial, I will explain in a few steps how to create a mask to balance the recognition of our object in real-time.

We import the libraries Opencv and Numpy, then load the cap to get the frames from the webcam. After that we start a while Loop where we get the frames and we do the detection.

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

Inside the while loop we define the HSV ranges (low_red, high_red), we create the mask and we show only the object with the red color.

    # Red color
    low_red = np.array([161, 155, 84])
    high_red = np.array([179, 255, 255])
    red_mask = cv2.inRange(hsv_frame, low_red, high_red)
    red = cv2.bitwise_and(frame, frame, mask=red_mask)

Same for the other colors:

    # Blue color
    low_blue = np.array([94, 80, 2])
    high_blue = np.array([126, 255, 255])
    blue_mask = cv2.inRange(hsv_frame, low_blue, high_blue)
    blue = cv2.bitwise_and(frame, frame, mask=blue_mask)

    # Green color
    low_green = np.array([25, 52, 72])
    high_green = np.array([102, 255, 255])
    green_mask = cv2.inRange(hsv_frame, low_green, high_green)
    green = cv2.bitwise_and(frame, frame, mask=green_mask)

    # Every color except white
    low = np.array([0, 42, 0])
    high = np.array([179, 255, 255])
    mask = cv2.inRange(hsv_frame, low, high)
    result = cv2.bitwise_and(frame, frame, mask=mask)

We finally show the result:

    cv2.imshow("Frame", frame)
    cv2.imshow("Red", red)
    cv2.imshow("Blue", blue)
    cv2.imshow("Green", green)
    cv2.imshow("Result", result)

    key = cv2.waitKey(1)
    if key == 27:
        break

Object recognition based on colors

In this article you have learned, I hope without too many worries, the important concept of OpenCV for basic object recognition in computer vision.
For a deeper understanding of the topic and to have a greater mastery of the subject, I suggest you evaluate the purchase of my Object Detection course.