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