HSV trackbar Opencv Python
A basic yet very useful application of OpenCV is to track color.
One major challenge while doing color detection is to include all the shades of color.
To solve this problem of shades instead of using RGB color space we use HSV color space.
Don’t know “How to create trackbar in OpenCV Python’ Read ->”Trackbars in OpenCV python“

HSV trackbar code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
#import opencv and numpy import cv2 import numpy as np #trackbar callback fucntion to update HSV value def callback(x): global H_low,H_high,S_low,S_high,V_low,V_high #assign trackbar position value to H,S,V High and low variable H_low = cv2.getTrackbarPos('low H','controls') H_high = cv2.getTrackbarPos('high H','controls') S_low = cv2.getTrackbarPos('low S','controls') S_high = cv2.getTrackbarPos('high S','controls') V_low = cv2.getTrackbarPos('low V','controls') V_high = cv2.getTrackbarPos('high V','controls') #create a seperate window named 'controls' for trackbar cv2.namedWindow('controls',2) cv2.resizeWindow("controls", 550,10); #global variable H_low = 0 H_high = 179 S_low= 0 S_high = 255 V_low= 0 V_high = 255 #create trackbars for high,low H,S,V cv2.createTrackbar('low H','controls',0,179,callback) cv2.createTrackbar('high H','controls',179,179,callback) cv2.createTrackbar('low S','controls',0,255,callback) cv2.createTrackbar('high S','controls',255,255,callback) cv2.createTrackbar('low V','controls',0,255,callback) cv2.createTrackbar('high V','controls',255,255,callback) while(1): #read source image img=cv2.imread("ballimage.jpg") #convert sourece image to HSC color mode hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # hsv_low = np.array([H_low, S_low, V_low], np.uint8) hsv_high = np.array([H_high, S_high, V_high], np.uint8) #making mask for hsv range mask = cv2.inRange(hsv, hsv_low, hsv_high) print (mask) #masking HSV value selected color becomes black res = cv2.bitwise_and(img, img, mask=mask) #show image cv2.imshow('mask',mask) cv2.imshow('res',res) #waitfor the user to press escape and break the while loop k = cv2.waitKey(1) & 0xFF if k == 27: break #destroys all window cv2.destroyAllWindows() |
Read this great article on Colorspaces and know why convert RGB to HSV for color detection.
Read More about Anatomy of a digital Image
Stay updated with the latest advancements Explore event, webinars and conferences