Python - Find The Closest Color To A Color, From Giving List Of Colors
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
Solution 1:
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),
)
defclosest_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))
returnmin(color_diffs)[1]
closest_color((12, 34, 156))
# => (99, 23, 153)
closest_color((23, 145, 234))
# => (23, 186, 241)
EDIT: Improved code and used Euclidian distance calculation Sven mentioned above instead of basic diff sum.
Solution 2:
Fast, efficient and clean solution
Lets say we have:
list_of_colors = [[255,0,0],[150,33,77],[75,99,23],[45,88,250],[250,0,255]]
For fast processing use numpy and transform into numpy array
import numpy as np
desired color
color = [155,155,155]
Complete code
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 )
This algorithm is without loops and is super fast as it uses numpy
Solution 3:
Even faster using jit
from numba import jit
colors = np.array(colors)
color = np.array(color)
@jitdefclosest(colors,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
Post a Comment for "Python - Find The Closest Color To A Color, From Giving List Of Colors"