如何根据颜色范围检查RGB颜色?

时间:2017-04-04 20:09:21

标签: python rgb

我正在编写一个python脚本,我需要用这种方式检查3种颜色的颜色代码:红色,黄色和绿色:

if (255,255,255)  is in green range:
    print("green")
else if (255,255,255)  is in yellow range:
    print("yellow")
else if (255,255,255)  is in red range:
    print("red")
else:
    print("none")

我遇到的问题是如何查看is in yellow range

任何建议都将受到赞赏。

修改

以下图片代表我的黄色,绿色和红色感:

enter image description here

2 个答案:

答案 0 :(得分:3)

我刚刚在终端上破解了以下解决方案,不是很干净,但我希望你有这个想法。

TARGET_COLORS = {"Red": (255, 0, 0), "Yellow": (255, 255, 0), "Green": (0, 255, 0)}

def color_difference (color1, color2):
    return sum([abs(component1-component2) for component1, component2 in zip(color1, color2)])

my_color = (123, 234, 100)

differences = [[color_difference(my_color, target_value), target_name] for target_name, target_value in TARGET_COLORS.items()]
differences.sort()  # sorted by the first element of inner lists
my_color_name = differences[0][1]

print(my_color_name)

数字,my_color = (123, 234, 100)最接近的匹配是绿色:)

答案 1 :(得分:2)

将颜色转换为HSL并参考像this one这样的色轮来选择黄色,红色和绿色的定义,特别是H值。