Is there any library that can convert RGB colors to ANSI colors?

Z

ZelluX

Convert RGB colors to the closest ANSI colors. For example, given RGB
color FF0000, it should print [31m.
 
J

John Machin

Convert RGB colors to the closest ANSI colors. For example, given RGB
color FF0000, it should print [31m.

Maybe ... but you could write it yourself quickly enough; the code is
a trivial loop over a list of the RGB values of the 8 possible
colours, and would fit easily on a 24x80 terminal :) Why don't you
have a try at it and come back if you have any problems?

Cheers,
John
 
J

John Machin

Convert RGB colors to the closest ANSI colors. For example, given RGB
color FF0000, it should print [31m.

Maybe ... but you could write it yourself quickly enough; the code is
a trivial loop over a list of the RGB values of the 8 possible
colours, and would fit easily on a 24x80 terminal :) Why don't you
have a try at it and come back if you have any problems?

Ummm actually once you have got your rgb value as an integer (or a
tuple of 3 integers) -- in the example, 0xff0000 or (0xff, 0, 0) --
the answer can be obtained in one line with operations no more
complicated than shifting, masking, and addition.
 
P

Peter Otten

ZelluX said:
Convert RGB colors to the closest ANSI colors. For example, given RGB
color FF0000, it should print [31m.

from functools import partial

def to_rgb(color):
return (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF

target_colors = {
0x000000: "\33[30m",
0xFF0000: "\33[31m",
# ...
0xFFFFFF: "\33[37m",}

def euclidian(c1, c2):
r, g, b = to_rgb(c1)
s, h, c = to_rgb(c2)
r -= s
g -= h
b -= c
return r*r+g*g+b*b

def closest_color(color, target_colors=target_colors, dist=euclidian):
return min(target_colors, key=partial(dist, color))

if __name__ == "__main__":
black = target_colors[0]
for color in 0xff0000, 0x00ff00, 0x808080, 0x008000:
bestmatch = closest_color(color)
code = target_colors[bestmatch]
print "#%06x --> %sSAMPLE%s" % (color, code, black)

If the results are not good enough for your application you can convert to
another colorspace before calculating the distance.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top