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

Peter Otten __peter__ at web.de
Mon Dec 1 12:08:01 CET 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 >> 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



More information about the Python-list mailing list