# HG changeset patch # User Paul Boddie # Date 1441742953 -7200 # Node ID 23cf22b7cfbff3e15fac6b812132568c5339b9fc # Parent b5004853e37e97e2db4c58a4f8910ddefe30bd6a Experimenting with three tone values. Added automatic image height sizing. diff -r b5004853e37e -r 23cf22b7cfbf optimiser.py --- a/optimiser.py Tue Sep 08 21:29:00 2015 +0200 +++ b/optimiser.py Tue Sep 08 22:09:13 2015 +0200 @@ -2,7 +2,6 @@ from array import array from itertools import combinations -from random import randint import PIL.Image import sys @@ -35,25 +34,22 @@ def match_darker(b, bases): return downward[b] in bases and downward[b] -def neutral(bases, light): - l = ["W", "C", "Y", "M", "G", "R", "B", "_"] - if not light: - l.reverse() - for b in l: - if b in bases: +def fallback(bases): + for b in by_frequency(bases): + if b not in ["_", "W"]: return b - return bases[randint(0, 3)] + return by_frequency(bases)[0] tones = [ - "__", "_B", "BB", # 00x - "_G", "_C", "BC", # 01x - "GG", "GC", "CC", # 02x - "_R", "_M", "BM", # 10x - "_Y", "**", "WB", # 11x - "GY", "WG", "WC", # 12x - "RR", "RM", "MM", # 20x - "RY", "WR", "WM", # 21x - "YY", "WY", "WW", # 22x + "___", "_BB", "BBB", # 00x + "_GG", "_CC", "BCC", # 01x + "GGG", "GCC", "CCC", # 02x + "_RR", "_MM", "BMM", # 10x + "_YY", "_*W", "BBW", # 11x + "GYY", "GGW", "CCW", # 12x + "RRR", "RMM", "MMM", # 20x + "RYY", "RRW", "MMW", # 21x + "YYY", "YYW", "WWW", # 22x ] colours = ["_", "R", "G", "Y", "B", "M", "C", "W"] @@ -84,10 +80,11 @@ if __name__ == "__main__": width = 320 - height = 192 input_filename, output_filename = sys.argv[1:3] im = PIL.Image.open(input_filename) + w, h = im.size + height = (width * h) / w im = im.resize((width, height)) usage = [] @@ -111,6 +108,8 @@ add(bu, t[0]) if t[1] != "*": add(bu, t[1]) + if t[2] != "*": + add(bu, t[2]) tr.append(t) chosen = [] @@ -122,11 +121,12 @@ best_missing = None best_map = None for bases in combinations(bu, 4): + bases = dict([(base, bu[base]) for base in bases]) count = 0 missing = [] tone_map = {} for tone, freq in u.items(): - base = match(light and tone[1] or tone[0], bases) + base = match(tone[1], bases) or match(light and tone[2] or tone[0], bases) if base: tone_map[tone] = base count += freq @@ -142,11 +142,10 @@ output = [] for row, (tr, ch) in enumerate(zip(toned, chosen)): - light = row % 2 o = [] for column, t in enumerate(tr): best, bases, tone_map, missing = ch - base = tone_map.get(t) or neutral(bases, light) + base = tone_map.get(t) or fallback(bases) o.append(base) i = colours.index(base) im.putpixel((column, row), colour(i))