Return to category the RGB difference is smaller

Asked

Viewed 59 times

2

I’m having a doubt, that I’m probably trying to "reinvent the wheel", but I couldn’t come up with a result.

I have a color matrix (in RGB):

{
    "muito-clara": [248,299,218],
    "clara": [243,209,180],
    "clara-media": [221,175,134],
    "escura-media": [203,126,85],
    "escura": [154,73,33],
    "muito-escuro": [73,30,12]
}

And I need to compare them with another RGB that I get. Ex: RGB[234, 222, 213]

I need to "return" the color that has the closest approximation.

I’ve reached the code below:

json_data = json.loads(matriz_uau)

cor = []
aux1 = 0

for i in json_data:
  for k in json_data[i]:
    cor.append(k)
  color1_rgb = sRGBColor(int(rgb1), int(rgb2), int(rgb3))
  color2_rgb = sRGBColor(int(cor[0]), int(cor[1]), int(cor[2]))
  color1_lab = convert_color(color1_rgb, LabColor);
  color2_lab = convert_color(color2_rgb, LabColor);
  delta_e = delta_e_cie2000(color1_lab, color2_lab);
  if (aux1 < delta_e):
    aux1 = delta_e
  cor = []

print(aux1)

But the result is always a number, but I can’t relate it to the category.

Could you help me?

1 answer

1


You can try making the sum of the absolute difference between each color in the list and the color you want to check which has the lowest difference of the reference color:

from math import sqrt

def closest_color(color, colors):
        r, g, b = color
        color_diffs = []
        for cr, cg, cb in colors:
                color_diff = sqrt(abs(r - cr)**2 + abs(g - cg)**2 + abs(b - cb)**2)
                color_diffs.append((color_diff, (cr, cg, cb)))
        return min(color_diffs)[1]

colors = {
    "muito-clara": [248,299,218],
    "clara": [243,209,180],
    "clara-media": [221,175,134],
    "escura-media": [203,126,85],
    "escura": [154,73,33],
    "muito-escuro": [73,30,12]
}

print(closest_color((234, 222, 213), colors.values())) # (243, 209, 180)

DEMONSTRATION

Browser other questions tagged

You are not signed in. Login or sign up in order to post.