Life2Coding
Find the HSV Color Value for Detecting any Color using Trackbar in OpenCV Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to make you understand how to find the HSV value for detecting any color in OpenCV using trackbar

Documentation:

VideoCapture()

“VideoCapture object”=cv.VideoCapture()
“VideoCapture object”=cv.VideoCapture(filename[, apiPreference])
“VideoCapture object”=cv.VideoCapture(index[, apiPreference])
“VideoCapture object”=cv.VideoCapture()
“VideoCapture object”=cv.VideoCapture(filename[, apiPreference])
“VideoCapture object”=cv.VideoCapture(index[, apiPreference])
“VideoCapture object”=cv.VideoCapture()
“VideoCapture object”=cv.VideoCapture(filename[, apiPreference])
“VideoCapture object”=cv.VideoCapture(index[, apiPreference])

Default constructor.

Opens a video file or a capturing device or an IP video stream for video capturing with API Preference.

Opens a camera for video capturing.

Parameters
filename it can be:

  • name of video file (eg. video.avi)
  • or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, ...)
  • or URL of video stream (eg. protocol://host:port/script_name?script_params|auth). Note that each video stream or IP camera feed has its own URL scheme. Please refer to the documentation of source stream to know the right URL.
apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW.
Parameters
index id of the video capturing device to open. To open default camera using default backend just pass 0. (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY)
apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L.

namedWindow()

None=cv.namedWindow(winname[, flags])

Creates a window.

Parameters
winname Name of the window in the window caption that may be used as a window identifier.
flags Flags of the window. The supported flags are: (cv::WindowFlags)

cvtColor()

dst=cv.cvtColor(src, code[, dst[, dstCn]])

Converts an image from one color space to another.

Parameters
src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
dst output image of the same size and depth as src.
code color space conversion code (see ColorConversionCodes).
dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.

getTrackbarPos()

retval=cv.getTrackbarPos(trackbarname, winname)

Returns the trackbar position.

Parameters
trackbarname Name of the trackbar.
winname Name of the window that is the parent of the trackbar.

inRange()

dst=cv.inRange(src, lowerb, upperb[, dst])

Checks if array elements lie between the elements of two other arrays.

Parameters
src first input array.
lowerb inclusive lower boundary array or a scalar.
upperb inclusive upper boundary array or a scalar.
dst output array of the same size as src and CV_8U type.

bitwise_and()

dst=cv.bitwise_and(src1, src2[, dst[, mask]])

computes bitwise conjunction of the two arrays (dst = src1 & src2) Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.

Parameters
src1 first input array or a scalar.
src2 second input array or a scalar.
dst output array that has the same size and type as the input arrays.
mask optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

putText()

img=cv.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])

Draws a text string.

Parameters
img Image.
text Text string to be drawn.
org Bottom-left corner of the text string in the image.
fontFace Font type, see HersheyFonts.
fontScale Font scale factor that is multiplied by the font-specific base size.
color Text color.
thickness Thickness of the lines used to draw a text.
lineType Line type. See LineTypes
bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

Parameters
delay Delay in milliseconds. 0 is the special value that means “forever”.

destroyAllWindows()

None=cv.destroyAllWindows()

Destroys all of the HighGUI windows.

Steps:

  • Start the webcam feed using the cv2.VideoCapture()
  • Create the trackbars for adjusting the HSV min and max values using cv2.createTrackbar()
  • In the main while loop get the trackbar values using cv2.getTrackbarPos()
  • Create the HSV mask using cv2.inRange()
  • Print the HSV values on the image window using cv2.putText()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np

def nothing(x):
    pass


if __name__ == '__main__':

    cap = cv2.VideoCapture(1)

    cv2.namedWindow("HSV Value")
    cv2.createTrackbar("H MIN", "HSV Value", 0, 179, nothing)
    cv2.createTrackbar("S MIN", "HSV Value", 0, 255, nothing)
    cv2.createTrackbar("V MIN", "HSV Value", 0, 255, nothing)
    cv2.createTrackbar("H MAX", "HSV Value", 179, 179, nothing)
    cv2.createTrackbar("S MAX", "HSV Value", 255, 255, nothing)
    cv2.createTrackbar("V MAX", "HSV Value", 255, 255, nothing)

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

        h_min = cv2.getTrackbarPos("H MIN", "HSV Value")
        s_min = cv2.getTrackbarPos("S MIN", "HSV Value")
        v_min = cv2.getTrackbarPos("V MIN", "HSV Value")
        h_max = cv2.getTrackbarPos("H MAX", "HSV Value")
        s_max = cv2.getTrackbarPos("S MAX", "HSV Value")
        v_max = cv2.getTrackbarPos("V MAX", "HSV Value")

        lower_blue = np.array([h_min, s_min, v_min])
        upper_blue = np.array([h_max, s_max, v_max])

        hsv_min="MIN H:{} S:{} V:{}".format(h_min,s_min,v_min)
        hsv_max = "MAX H:{} S:{} V:{}".format(h_max, s_max, v_max)

        mask = cv2.inRange(hsv, lower_blue, upper_blue)

        result = cv2.bitwise_and(frame, frame, mask=mask)

        cv2.putText(frame, hsv_min, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        cv2.putText(frame, hsv_max, (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

        cv2.imshow("HSV Value", frame)
        cv2.imshow("Mask", mask)
        cv2.imshow("Frame Mask", result)

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

    cap.release()
    cv2.destroyAllWindows()

Output:

5cc02d0e04f9e Find the HSV Color Value for Detecting any Color using Trackbar in OpenCV Python
life2coding_icon [] Find the HSV Color Value for Detecting any Color using Trackbar in OpenCV Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.