find closest color python

Solutions on MaxInterview for find closest color python by the best coders in the world

showing results for - "find closest color python"
Eris
09 Jan 2021
1from math import sqrt
2
3COLORS = (
4    (181, 230, 99),
5    (23, 186, 241),
6    (99, 23, 153),
7    (231, 99, 29),
8)
9
10def closest_color(rgb):
11    r, g, b = rgb
12    color_diffs = []
13    for color in COLORS:
14        cr, cg, cb = color
15        color_diff = sqrt(abs(r - cr)**2 + abs(g - cg)**2 + abs(b - cb)**2)
16        color_diffs.append((color_diff, color))
17    return min(color_diffs)[1]
18
19closest_color((12, 34, 156))
20# => (99, 23, 153)
21
22closest_color((23, 145, 234))
23# => (23, 186, 241)
24