我有一个包含rgb颜色值元组的列表:
colors = [
(0, 0, 0),
(0, 0, 170),
(0, 170, 0),
(0, 170, 170),
(170, 0, 0),
(170, 0, 170),
(255, 170, 0),
(170, 170, 170),
(85, 85, 85),
(85, 85, 255),
(85, 255, 85),
(85, 255, 255),
(255, 85, 85),
(255, 85, 255),
(255, 255, 85),
(255, 255, 255)
]
现在我有一个像(255, 0, 0)
这样的rgb值,并希望在列表中找到最适合它的颜色(我想这里会是(170, 0, 0)
)。在Python 2.7中有没有办法做到这一点?
好的,我发现gnibbler的解决方案是最好的解决方案。这就是我所做的:
from functools import partial
def colorDifference(testColor, otherColor):
difference = 0
difference += abs(testColor[0]-otherColor[0])
difference += abs(testColor[1]-otherColor[1])
difference += abs(testColor[2]-otherColor[2])
return difference
closestColor = min(colors, key=partial(colorDifference, testColor))
答案 0 :(得分:4)
首先定义差异功能,然后使用
min(colors, key=difference_func)
如果您需要传递其他颜色,可以这样做
from functools import partial
def difference_func(test_color, other_color):
return ???
result = min(colors, key=partial(difference_func, test_color))
答案 1 :(得分:1)
为简单起见,您可以在“颜色立方体”中的两个点之间测量两种颜色之间的相似度euclidean distance,如下所示:
import math
def distance(color1, color2):
return math.sqrt(sum([(e1-e2)**2 for e1, e2 in zip(color1, color2)]))
然后,您可以使用该指标对颜色进行排序,并采用第一个元素 - 最相似的颜色:
def best_match(sample, colors):
by_distance = sorted(colors, key=lambda c: distance(c, sample))
return by_distance[0]
测试:
>>> best_match((255, 0, 0), colors)
(170, 0, 0)
答案 2 :(得分:0)
您可以尝试使用lambda进行排序吗?
#!/usr/bin/env python
colors = [
(0, 0, 0), (0, 0, 170), (0, 170, 0), (0, 170, 170),
(170, 0, 0), (170, 0, 170), (255, 170, 0), (170, 170, 170),
(85, 85, 85), (85, 85, 255), (85, 255, 85), (85, 255, 255),
(255, 85, 85), (255, 85, 255), (255, 255, 85), (255, 255, 255)
]
def getClosestMatch(c):
l = sorted(colors, key=lambda x:(\
0 < x[0] <= c[0],\
0 < x[1] <= c[1],\
0 < x[2] <= c[2]),\
reverse=True)
return l[0];
if __name__ == '__main__':
color = (255, 0, 0)
print getClosestMatch(color)