如何根据颜色范围检查 RGB 颜色?
How to check RGB colors against a color range?
我正在编写一个 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
?
如有任何建议,我们将不胜感激。
编辑
下图代表我对黄绿红的感觉:
这是一个简单的解决方案:
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)
最接近的匹配是绿色:)
将颜色转换为 HSL 并参考像 this one 这样的色轮来选择您对黄色、红色和绿色的定义,特别是 H 值。
我正在编写一个 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
?
如有任何建议,我们将不胜感激。
编辑
下图代表我对黄绿红的感觉:
这是一个简单的解决方案:
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)
最接近的匹配是绿色:)
将颜色转换为 HSL 并参考像 this one 这样的色轮来选择您对黄色、红色和绿色的定义,特别是 H 值。