我正在编写一个 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")
我遇到的问题是如何查看它是否在黄色范围内?
如有任何建议,我们将不胜感激。
编辑
下图代表我对黄绿红的感觉:
请您参考如下方法:
这是一个简单的解决方案:
KNOWN_COLORS = {"Red": (255, 0, 0), "Yellow": (255, 255, 0), "Green": (0, 255, 0)}
def color_difference (color1, color2) -> int:
""" calculate the difference between two colors as sum of per-channel differences """
return sum([abs(component1-component2) for component1, component2 in zip(color1, color2)])
def get_color_name(color) -> str:
""" guess color name using the closest match from KNOWN_COLORS """
differences =[
[color_difference(color, known_color), known_name]
for known_name, known_color in KNOWN_COLORS.items()
]
differences.sort() # sorted by the first element of inner lists
return differences[0][1] # the second element is the name
my_color = (123, 234, 100)
print(get_color_name(my_color))
# zero copyrights / public domain
数字,my_color = (123, 234, 100) 最接近的匹配是绿色 :)
