1 #!/usr/bin/env python 2 3 from array import array 4 from itertools import combinations 5 import PIL.Image 6 import sys 7 8 def scale(v): 9 return (v + 64) / 128 10 11 def point(rgb): 12 return tuple(map(scale, rgb)) 13 14 def index(p): 15 return p[0] * 9 + p[1] * 3 + p[2] 16 17 def colour(i): 18 return (255 * (i % 2), 255 * ((i / 2) % 2), 255 * ((i / 4) % 2)) 19 20 def add(d, v): 21 d[v] = (d.has_key(v) and d[v] or 0) + 1 22 23 def by_frequency(d): 24 l = [(f, t) for (t, f) in d.items()] 25 l.sort(reverse=True) 26 return [i[1] for i in l] 27 28 def match(b, bases): 29 return b in bases and b 30 31 def fallback(bases): 32 for b in by_frequency(bases): 33 if b not in ["_", "W"]: 34 return b 35 return by_frequency(bases)[0] 36 37 tones = [ 38 "___", "_BB", "BBB", # 00x 39 "_GG", "_CC", "BCC", # 01x 40 "GGG", "GCC", "CCC", # 02x 41 "_RR", "_MM", "BMM", # 10x 42 "_YY", "_*W", "BBW", # 11x 43 "GYY", "GGW", "CCW", # 12x 44 "RRR", "RMM", "MMM", # 20x 45 "RYY", "RRW", "MMW", # 21x 46 "YYY", "YYW", "WWW", # 22x 47 ] 48 49 colours = ["_", "R", "G", "Y", "B", "M", "C", "W"] 50 51 if __name__ == "__main__": 52 width = 320 53 input_filename, output_filename = sys.argv[1:3] 54 55 im = PIL.Image.open(input_filename) 56 w, h = im.size 57 height = (width * h) / w 58 im = im.resize((width, height)) 59 60 usage = [] 61 base_usage = [] 62 toned = [] 63 64 for row in range(0, height): 65 u = {} 66 usage.append(u) 67 bu = {} 68 base_usage.append(bu) 69 tr = [] 70 toned.append(tr) 71 for column in range(0, width): 72 rgb = im.getpixel((column, row)) 73 p = point(rgb) 74 i = index(p) 75 t = tones[i] 76 add(u, t) 77 if t[0] != "*": 78 add(bu, t[0]) 79 if t[1] != "*": 80 add(bu, t[1]) 81 if t[2] != "*": 82 add(bu, t[2]) 83 tr.append(t) 84 85 chosen = [] 86 87 for row, (u, bu) in enumerate(zip(usage, base_usage)): 88 light = row % 2 89 best = 0 90 best_bases = None 91 best_missing = None 92 best_map = None 93 for bases in combinations(bu, 4): 94 bases = dict([(base, bu[base]) for base in bases]) 95 count = 0 96 missing = [] 97 tone_map = {} 98 for tone, freq in u.items(): 99 base = match(tone[1], bases) or match(light and tone[2] or tone[0], bases) 100 if base: 101 tone_map[tone] = base 102 count += freq 103 else: 104 missing.append(tone) 105 if count > best: 106 best_bases = bases 107 best_missing = missing 108 best_map = tone_map 109 best = count 110 chosen.append((best, best_bases or bases, best_map or tone_map, best_missing or missing)) 111 112 output = [] 113 114 for row, (tr, ch) in enumerate(zip(toned, chosen)): 115 o = [] 116 for column, t in enumerate(tr): 117 best, bases, tone_map, missing = ch 118 base = tone_map.get(t) or fallback(bases) 119 o.append(base) 120 i = colours.index(base) 121 im.putpixel((column, row), colour(i)) 122 123 output.append("".join(o)) 124 125 im.save(output_filename) 126 127 # vim: tabstop=4 expandtab shiftwidth=4