Python - 从提供颜色列表中找到最接近颜色的颜色 [英] Python - Find the closest color to a color, from giving list of colors
问题描述
我有一个包含 20 种颜色的列表,每种颜色都是这样的 (0,0,0)(rgb) 但具有不同的值,我需要找到最接近我给出的颜色,例如 (200, 191, 231).问题是我不确定我应该如何检查收盘价是什么颜色,以及我应该如何在列表中设置所有这些颜色值?在数组中?
I have a list of 20 colors, each is like this (0,0,0)(rgb) but with different values, and i need to find the closest to the color i am giving, for example (200, 191, 231). problem is i am not sure how i should check what color is the closes, and how am i suppose to set all these color values, in a list? in an array?
我一直在想也许可以添加所有颜色,例如 (1,2,3) = 4 然后找到最接近的,但我不确定这是否是个好主意..
I've been thinking maybe add all the color for exmaple (1,2,3) = 4 an then find the closest but i am not sure if its a good idea..
以下是颜色列表:
#(0, 0, 0) - Black
#(127, 127, 127) - Gray
#(136, 0, 21) - Bordeaux
#(237, 28, 36) - red
#(255, 127, 39) - orange
#(255, 242, 0) - yellow
#(34, 177, 76) - green
#(203, 228, 253) - blue
#(0, 162, 232) - dark blue
#(63, 72, 204) - purple
#(255, 255, 255) - white
#(195, 195, 195) - light gray
#(185, 122, 87) - light brown
#(255, 174, 201) - light pink
#(255, 201, 14) - dark yellow
#(239, 228, 176) - light yellow
#(181, 230, 29) - light green
#(153, 217, 234) - light blue
#(112, 146, 190) - dark blue
#(200, 191, 231) - light purple
这是函数:
def paint(pixel):
r,g,b,a = pix[x,y]
print(str(r) + ' '+ str(g) + ' ' + str(b))
sleep(0.20)
如果您想出了一个好的解决方案或有任何问题,请重播谢谢您的帮助!
If you come up with a good solution or have any question please replay thank you for your help!
推荐答案
你想求红、绿、蓝三个数的绝对差之和,并选择最小的一个.
You want to find the sum of the absolute difference between the red, green and blue numbers and choose the smallest one.
from math import sqrt
COLORS = (
(181, 230, 99),
(23, 186, 241),
(99, 23, 153),
(231, 99, 29),
)
def closest_color(rgb):
r, g, b = rgb
color_diffs = []
for color in COLORS:
cr, cg, cb = color
color_diff = sqrt(abs(r - cr)**2 + abs(g - cg)**2 + abs(b - cb)**2)
color_diffs.append((color_diff, color))
return min(color_diffs)[1]
closest_color((12, 34, 156))
# => (99, 23, 153)
closest_color((23, 145, 234))
# => (23, 186, 241)
改进代码并使用上面提到的欧几里得距离计算 Sven 而不是基本的差异总和.
Improved code and used Euclidian distance calculation Sven mentioned above instead of basic diff sum.
这篇关于Python - 从提供颜色列表中找到最接近颜色的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!