PaletteOptimiser

optimiser.py

14:9369980667e7
2015-09-09 Paul Boddie Switched to the more advanced colour model. Added automatic height sizing and rotation support.
     1 #!/usr/bin/env python     2      3 from array import array     4 import PIL.Image     5 import sys     6      7 def scale(v):     8     return (v + 43) / 85     9     10 def point(rgb):    11     return tuple(map(scale, rgb))    12     13 def index(p):    14     return p[0] * 16 + p[1] * 4 + p[2]    15     16 def colour(i):    17     return (255 * (i % 2), 255 * ((i / 2) % 2), 255 * ((i / 4) % 2))    18     19 tones = [    20     "___", "_BB", "_BB", "BBB", # 00x    21     "_GG", "__C", "_BC", "BCC", # 01x    22     "_GG", "GGC", "BCC", "CCC", # 02x    23     "GGG", "GCC", "CCC", "CCC", # 03x    24     "_RR", "_MM", "MMB", "MBB", # 10x    25     "_YY", "_**", "_*B", "BBW", # 11x    26     "_GY", "GGC", "*CC", "CCW", # 12x    27     "GGY", "GGG", "GCC", "CCW", # 13x    28     "RRR", "RRM", "RMM", "MMM", # 20x    29     "RYY", "RRW", "RMW", "MMW", # 21x    30     "YYY", "YYW", "**W", "WWW", # 22x    31     "YYY", "YYW", "YWW", "WWW", # 23x    32     "RRR", "RMM", "RMM", "MMW", # 30x    33     "RRY", "RRY", "RMW", "MMW", # 31x    34     "YYY", "YYW", "YYW", "WWW", # 32x    35     "YYY", "YYW", "YYW", "WWW", # 33x    36     ]    37     38 colours = ["_", "R", "G", "Y", "B", "M", "C", "W"]    39     40 if __name__ == "__main__":    41     width = 320    42     input_filename, output_filename = sys.argv[1:3]    43     scaled_filename = (sys.argv[3:] + [None])[0]    44     rotate = "-r" in sys.argv[3:]    45     46     im = PIL.Image.open(input_filename)    47     if rotate:    48         im = im.rotate(270)    49     w, h = im.size    50     height = (width * h) / w    51     im = im.resize((width, height))    52     53     for row in range(0, height):    54         for column in range(0, width):    55             rgb = im.getpixel((column, row))    56             p = point(rgb)    57             i = index(p)    58             t = tones[i]    59             c = t[1] != "*" and t[1] or (row % 2) and t[2] != "*" and t[2] or t[0] != "*" and t[0] or t[2]    60             i = colours.index(c)    61             im.putpixel((column, row), colour(i))    62     63     im.save(output_filename)    64     65     if scaled_filename:    66         im = im.resize((width / 2, height), PIL.Image.NEAREST)    67         im = im.resize((width, height), PIL.Image.NEAREST)    68         im.save(scaled_filename)    69     70 # vim: tabstop=4 expandtab shiftwidth=4