PaletteOptimiser

Annotated optimiser.py

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