Python - 从给出的颜色列表中找到最接近颜色的颜色

Python - Find the closest color to a color, from giving list of colors

我有一个包含 20 种颜色的列表,每种颜色都是这样的 (0,0,0)(rgb) 但具有不同的值,我需要找到最接近我给出的颜色,例如 (200 , 191, 231).问题是我不确定我应该如何检查收盘价是什么颜色,以及我应该如何在列表中设置所有这些颜色值?在数组中?

我一直在想也许可以为示例 (1,2,3) = 4 添加所有颜色,然后找到最接近的颜色,但我不确定这是否是个好主意..

这是颜色列表:

#(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)

如果您有好的解决方案或有任何问题请重播,谢谢您的帮助!

你想求出红、绿、蓝数的绝对差之和,选最小的一个。

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((r - cr)**2 + (g - cg)**2 + (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 而不是基本的差和。

快速、高效、干净的解决方案

假设我们有:

list_of_colors = [[255,0,0],[150,33,77],[75,99,23],[45,88,250],[250,0,255]]

为了快速处理,使用 numpy 并转换为 numpy 数组

import numpy as np

想要的颜色

color = [155,155,155]

完整代码

import numpy as np

list_of_colors = [[255,0,0],[150,33,77],[75,99,23],[45,88,250],[250,0,255]]
color = [155,155,155]

def closest(colors,color):
    colors = np.array(colors)
    color = np.array(color)
    distances = np.sqrt(np.sum((colors-color)**2,axis=1))
    index_of_smallest = np.where(distances==np.amin(distances))
    smallest_distance = colors[index_of_smallest]
    return smallest_distance 

closest_color = closest(list_of_colors,color)
print(closest_color )

这个算法没有循环,而且速度超快,因为它使用了 numpy