Lower and Upper Mask Range for Color Detection

Sardor Abdirayimov
2 min readDec 3, 2022

--

Most of us have thought many times about color detection🔵🟢🔴. It sounds quite easy task to complete, isn`t it?

The built-in camera in my laptop is completely different from the web camera which I borrowed from the university. Lower and Upper mask ranges on the internet do not make sense to many cameras. Usually, lower and upper mask ranges for colors vary depending on camera quality and environmental conditions.

The most common algorithm for color detection is:

  1. Changing the COLOR format from BGR to HSV
  2. Putting the MASK to the HSV image with lower and upper boundaries
  3. Using `cv2.bitwise_and() ` to visualize only that particular color.

Big Issue | How to find Lower and Upper boundaries?

Here is a handy solution with a GUI interface to find that particular boundary for a particular color in several tries.

For example, Here is the boundaries for a blue color:

import cv2 as cv
import numpy as np

Winname = "Frame:"

def nothing(x):
pass

cv.namedWindow('Frame:')
# H, S,V are for Lower Boundaries
#H2,S2,V2 are for Upper Boundaries
cv.createTrackbar('H',Winname,0,255,nothing)
cv.createTrackbar('S',Winname,0,255,nothing)
cv.createTrackbar('V',Winname,0,255,nothing)
cv.createTrackbar('H2',Winname,0,255,nothing)
cv.createTrackbar('S2',Winname,0,255,nothing)
cv.createTrackbar('V2',Winname,0,255,nothing)


cap = cv.VideoCapture(0)

while cap.isOpened():
_, frame = cap.read()
H = cv.getTrackbarPos('H', 'Frame:')
S = cv.getTrackbarPos('S', 'Frame:')
V = cv.getTrackbarPos('V', 'Frame:')
H2 = cv.getTrackbarPos('H2', 'Frame:')
S2 = cv.getTrackbarPos('S2', 'Frame:')
V2 = cv.getTrackbarPos('V2', 'Frame:')
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
lower_boundary = np.array([H, S, V])
upper_boundary = np.array([H2,S2,V2])
mask = cv.inRange(hsv, lower_boundary, upper_boundary)
final = cv.bitwise_and(frame, frame, mask=mask)
cv.imshow("Frame:", final)

if cv.waitKey(1) == ord('q'): break

cap.release()
cv.destroyAllWindows()

This GUI program is super handy and saves tons of your time!

Feel free to write comments and share your thoughts. Sharing is Caring :)

--

--

Sardor Abdirayimov

Writer || Developer || Pythonist || Machine Learning Engineer || Runner || Learner out of distribution