且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python - 从提供颜色列表中找到最接近颜色的颜色

更新时间:2022-06-17 23:51:47

你想求红、绿、蓝三个数的绝对差之和,并选择最小的一个.

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.