Python PIL - Finding Nearest Color (Rounding Colors)

GShocked picture GShocked · Dec 19, 2015 · Viewed 10.6k times · Source

There is a game called Roblox, in which the player makes the game, usually of lego-looking bricks.

In Roblox, for the Brick colors, you can use typical RGB values, but that'd require an additional element that is not very efficient when it comes to file size. Instead of using RGB values, BrickColor is much more economic in file size. It uses an integer to be interpreted as a certain color. Here is what I mean: Color Codes

Here is a snippet of my code:

import Image
f = raw_input('Image:\n')
im = Image.open(f)
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((x, y))

In my program, I need to find the color code closest to an RGB value.

How might this be accomplished?

Answer

mattsap picture mattsap · Dec 19, 2015

Create a list of colors in your table (I call it colors). Sort the list by the distance to the r, g, b point you are questioning The first element in the list is the closest color

def distance(c1, c2):
    (r1,g1,b1) = c1
    (r2,g2,b2) = c2
    return math.sqrt((r1 - r2)**2 + (g1 - g2) ** 2 + (b1 - b2) **2)

colors = list(rgb_code_dictionary.keys())
closest_colors = sorted(colors, key=lambda color: distance(color, point))
closest_color = closest_colors[0]
code = rgb_code_dictionary[closest_color]