def identify_color(pixel_color, hsv_color_ranges, debug=False):
"""
This method compares colors to red, green, blue and white
using the HSV color model to be able to detect colors more or
less reliable, even for various light situations from a photo
parameters: triple of rgb values
returns: string of color ('blue', 'green', 'red', 'white') or None
"""
hsv = rgb2hsv(pixel_color)
couldbe = {}
for color, color_range in hsv_color_ranges.items(): # for every hsv color range in hsv_color_ranges
couldbe[color] = 0
for i in range(0,3): # for every channel
if i is 0 and color_range[0][i] > color_range[1][i]: # if it is h and min and max are reversed
# its red, so from 0 to max or min to 1
if (0. <= hsv[i] <= color_range[1][i]) or (color_range[0][i] <= hsv[i] <= 1.): couldbe[color] += 1
else:
## if hsv channel between hsv color range_min and range_max
if color_range[0][i] <= hsv[i] <= color_range[1][i]: couldbe[color] +=1
# save all colors where score in couldbe is 3, so all channels have matched
# should not happen, but this is good for debugging the hsv color ranges
possible_colors = []
for color, weight in couldbe.items():
if weight == 3: # matches all three channels
possible_colors.append(color)
if len(possible_colors) == 0:
if debug: print('COLOR: matches no color\t\t',pixel_color, ' (rgb)\t\t',hsv,'(hsv)')
return None
elif len(possible_colors) == 1:
if debug: print('COLOR: should be', possible_colors[0], '\t\t',pixel_color, ' (rgb)')
return possible_colors[0]
elif len(possible_colors) > 1:
print('COLOR: CONFLICT! matches multiple colors (',possible_colors,')\t\t',pixel_color,' (rgb)\t',hsv,'(hsv)')
return None
cv.py 文件源码
python
阅读 17
收藏 0
点赞 0
评论 0
评论列表
文章目录