我碰巧也需要一个 value->name 函数,并且发现这里的帖子很有帮助。然而,这就是我想出的:
from bs4 import BeautifulSoup
import requests
import sys
def squ_diff(c1, c2):
return ((c1 & 0x0000FF) - (c2 & 0x0000FF))**2 +\
(((c1 & 0x00FF00)>>8) - ((c2 & 0x00FF00)>>8))**2 +\
(((c1 & 0xFF0000)>>16) - ((c2 & 0xFF0000)>>16))**2
def best_match(c, ref):
"""Find the best match for color c.
Uses least square to determine fitness.
"""
diff = squ_diff(0xFFFFFF, 0x000000)
best = "None"
for ref_color in ref:
curr_diff = squ_diff(c, ref_color[1])
#if curr_diff < 1000:
# print curr_diff, ref_color[0], hex(ref_color[1])
if curr_diff < diff:
diff = curr_diff
best = ref_color[0]
return best
def get_ref():
"""Retreives some reference colors.
Format:
[("red", 0xFF0000), ("green", 0x00FF00), ("blue", 0x0000FF)]
"""
html = requests.get("http://jadecat.com/tuts/colorsplus.html").content
soup = BeautifulSoup(html)
return [(e.text[:-6].strip(), int(e.text[-6:], 16)) for e in soup.find_all("td")[2:]]
if __name__ == "__main__":
"""For testing, just provide a hex value as the argument.
"""
r = get_ref()
print best_match(int(sys.argv[1], 16), r)
它计算给定参考表上的最小二乘差(我刚刚从互联网上下载了一个),以将名称与给定的颜色值配对。就调整人类的颜色感知而言,我并没有真正做太多的科学工作,但我得到的效果相当不错。希望这对某人有用,因为您可以随意修改评分功能。
不过,Shai 引用的工作确实很有趣,这意味着我的算法应该在某些颜色上失败。然而,这种方法背后的想法是为尽可能多的颜色命名,以尽量减少这种影响。例如,您甚至可以将多个颜色值映射到“红色”。