Object detection using HSV Color space – OpenCV 3.4 with python 3 Tutorial 9

What we will learn in this tutorial:

  • What is HSV
  • How to object recognition by color works

What is HSV

HSV (Hue Saturation Value) is a color format that describes colors in terms of their shade (saturation) and brightness (value). 

How to object recognition by color works

In this tutorial I explained how to create an HSV mask with opencv and python for identifying objects simply by color.

If this is one of your first opencv projects you will be surprised by the simplicity and effectiveness of the result. Follow me and I guarantee you will immediately become a master.

In my case I used two highlighters, one green and one blue and we will be able to detach them from the screen with Opencv and an HSV mask.

As always, to start with our Object detection project using HSV Color space we need to call the Opencv library, then we create a mask HSV.

cv2.createTrackbar("L - H", "Trackbars", 0, 179, nothing)
cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("L - V", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("U - H", "Trackbars", 179, 179, nothing)
cv2.createTrackbar("U - S", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U - V", "Trackbars", 255, 255, nothing)

With these bars we can choose which color to hide and which to leave enabled.

If you simply want to use it in real-time it will be enough to put everything in a loop. Like the piece of code in the example.

while True:
    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    l_h = cv2.getTrackbarPos("L - H", "Trackbars")
    l_s = cv2.getTrackbarPos("L - S", "Trackbars")
    l_v = cv2.getTrackbarPos("L - V", "Trackbars")
    u_h = cv2.getTrackbarPos("U - H", "Trackbars")
    u_s = cv2.getTrackbarPos("U - S", "Trackbars")
    u_v = cv2.getTrackbarPos("U - V", "Trackbars")
    
    lower_blue = np.array([l_h, l_s, l_v])
    upper_blue = np.array([u_h, u_s, u_v])
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    
    result = cv2.bitwise_and(frame, frame, mask=mask)
    
    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    cv2.imshow("result", result)

Object detection project

I hope the project has been helpful to you and I recommend that you download the complete to have a fully functional example.

If you need to create a real object detection project, I suggest you evaluate the purchase of my Object detection with OpenCV & deep learning course.

Blueprint

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE