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

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

ZelluX
Guest
Posts: n/a

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

John Machin
Guest
Posts: n/a

 11-30-2008
On Nov 30, 4:39*pm, ZelluX <(E-Mail Removed)> wrote:
> 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

John Machin
Guest
Posts: n/a

 11-30-2008
On Nov 30, 8:04*pm, John Machin <(E-Mail Removed)> wrote:
> On Nov 30, 4:39*pm, ZelluX <(E-Mail Removed)> wrote:
>
> > 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

Peter Otten
Guest
Posts: n/a

 12-01-2008
ZelluX wrote:

> 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 >> & 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