Skip to content

Tutorials

Detecting colors (Hsv Color Space) – Opencv with Python

Access community, courses and source codes
Logo

AI Vision Academy

Access the code of this tutorial, computer vision courses and an exclusive community on AI Vision Academy

  • Access to over 50+ source codes from Pysource.com/blog
  • Dedicated video courses about computer vision
  • Access to an exclusive community of professionals
  • Real-World AI Projects – Get hands-on experience building practical AI Computer Vision solutions with a structured path.
  • Monthly Coaching Calls – get support and any of your questions answered

Subscribe to our newsletter to learn more

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.

18 comments

  1. Hi Sergio,
    Great job, I want to use this to detect green parrot bird, only the green bird. Can you let me know how to get a trigger when 30% of the picture is green ?

    1. Hi Patrick,

      You can first calculate the area of the entire frame. You can do that by multiply height and width of the frame.
      Then you should get the area of the contours with the following code:
      area = cv2.contourArea(cnt)

      And then you can put the condition if the area of the contour is 30% of the area of the entire frame to do something.

      1. Hi sergio
        how do you figure the range of different colors. and how did you decide the range of all colors except white. for example if I am looking to detect all colors except blue. how will that work

          1. Right. so I have made two masks and combined them.
            one mask ranges from 0-75 in hue {s(0-255), v(0-255)}
            the other ranges from 129-180 in hue {s(0-255), v(0-255)}
            it seems to work. it detects almost all colors except the blue color.
            Much appreciated

  2. Nice work.
    How can we get HSV ranges for all VIBGYOR colors ?
    I tried converting RGB to HSV, but not getting proper results using those ranges.
    Any idea ?

  3. hello,
    How can we get HSV ranges for all colors ?
    I tried converting RGB to HSV, but not getting proper results using those ranges.
    Any idea to do that? and how you got this range ?

  4. OMG again. It is impossible to locate an rectangle of some RGB color with this tutorial. I need to pray for answer how to find lower and higer ranges of HSV. i got SIMPLE RGB color and ALL BOX is in this color. Inside is text. FFS i cant fing anything usefull for such a trival thing! You all guys are repeat urself!

Join the discussion