PaletteOptimiser

optimiser.py

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