Reputation: 757
I am developing an app which detects major colour in the frame. I used python code and HSV colour ranges to do this. My sample code for detecting blue is as below.
import cv2
def detectBlue(frame):
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of green color in HSV
lower_blue = np.array([101, 39, 64])
upper_blue = np.array([140, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
kernel = np.ones((5,5),'int')
dilated = cv2.dilate(mask,kernel)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask=mask)
ret,thrshed = cv2.threshold(cv2.cvtColor(res,cv2.COLOR_BGR2GRAY),3,255,cv2.THRESH_BINARY)
#img,contours,hier = cv2.findContours(thrshed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours,hier = cv2.findContours(thrshed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
area = [0]
for cnt in contours:
#Contour area is taken
area.append(cv2.contourArea(cnt))
return max(area)
I created similar functions for Red and Green with HSV color ranges as below.
Green:
lower_green = [65,60,60])
upper_green = [80,255,255]
Red:
lower_red = [170,120,70]
upper_red = [180,255,255]
Now I am trying to do the same for all VIBGYOR colors, but I am not getting proper color ranges for all these. I tried converting RGB code to HSV using this python code.
import colorsys
def rgb_hsv_converter(rgb):
(r,g,b) = rgb_normalizer(rgb)
hsv = colorsys.rgb_to_hsv(r,g,b)
(h,s,v) = hsv_normalizer(hsv)
upper_band = [h+10, s+40, v+40]
lower_band = [h-10, s-40, v-40]
return {
'upper_band': upper_band,
'lower_band': lower_band
}
def rgb_normalizer(rgb):
(r,g,b) = rgb
return (r/255, g/255, b/255)
def hsv_normalizer(hsv):
(h,s,v) = hsv
return (h*360, s*255, v*255)
rgb_hsv_converter((255,255,255))
But, these ranges did not work properly when tested. I searched a lot to find out best HSV ranges for all these colors, but no use. Can anybody suggest any approach to find best and more accurate color ranges for many colors.?
Upvotes: 0
Views: 897
Reputation: 23528
You may take a pure red color, RGB( 255, 0, 0 ), convert it to HSV and the resulting hue (something around 0 -- zero) will be the center value for red. Do the same for the rest of the colors you want to define in HSV space. Green would be somewhere around 55, blue -- 120 and so on...
Upvotes: 1