有没有办法从该颜色的色调/阴影开始找到基色或将颜色的变体组合在一起?
例如:#9c2b2b / RGB (156,43,43) 是红色阴影 #2354c4 / RGB (132,162,232) 是蓝色
但是例如给出两种颜色,有没有一种方法可以在Python中确定这是红色(#FF0000 rgb(255,0,0))或蓝色(#0000FF rgb(0,0,255))的变体
我知道如何做,并且在网上找到了很多关于如何通过采用基色并相乘或相减来进行渐变的教程和答案。
谢谢你
我可以想出几种方法来做到这一点。下面的代码片段使用库colorir
>>> from colorir import *
# These are the categories we want to fit the colors in
# You can use anything here, I just sampled a few CSS colors
>>> tints_dict = {
'red': '#ff0000',
'yellow': '#ffff00',
'green': '#00ff00',
'blue': '#0000ff',
'black': '#000000',
'white': '#ffffff'
}
>>> tints = Palette('tints', **tints_dict)
# Now to get the tint of a given color:
>>> tints.most_similar('#9c2b2b')
HexRGB('#ff0000') # Pure red
# If you want its name:
>>> tints.get_names(tints.most_similar('#9c2b2b'))[0]
'red'
这种方法的问题在于,我认为“色调”的定义与颜色距离的定义不同(这本身就很有争议,请参阅this)。
这意味着,如果我们将紫色(例如“#800080”)添加到“tints”数据集中,
palette.most_similar('#9c2b2b')
将返回“#800080”。
这是因为“#9c2b2b”的感知亮度比红色更接近紫色。一个可能的解决方法是仅具有相似亮度的参考“色调”。
但是,这个解决方案可能更合适。
在这里,我们不根据整体相似性对颜色进行分组,而是只关注它们的色调成分。色调是颜色的“颜料”,是 HSL 和 HSV 颜色系统的组成部分之一。
>>> def closest_hue(target, tints):
# Interprets input target as hex string, convert to HSL and get hue component
target_hue = HexRGB(target).hsl()[0]
closest = (None, 180)
for color in tints:
hue = color.hsl()[0]
hue_dist = (min(target_hue, hue) - max(target_hue, hue)) % 360
if hue_dist < closest[1]:
closest = (color, hue_dist)
return closest[0]
>>> closest_hue('#9c2b2b', tints) # 'tints' is the same palette defined previously
HexRGB('ff0000') # Pure red
正如原帖评论中提到的,这种方法的缺点是它无法识别接近黑色、白色或灰色的颜色。
您还可以组合这些方法,例如,应该将非常接近黑色或白色的颜色归为一组,否则应按色调排序。由于这个问题没有单一的答案,因此您确实必须尝试我描述的方法,看看哪种方法最适合您。