# HG changeset patch # User Paul Boddie # Date 1444134714 -7200 # Node ID 9a8c24425be97b0590dc60d95b90f88166ffae31 # Parent 2e2722f377b05cbf3a7de07d86000f256036f1d2 Introduced compensation to complementary colours for those removed. diff -r 2e2722f377b0 -r 9a8c24425be9 optimiser.py --- a/optimiser.py Sun Oct 04 21:47:16 2015 +0200 +++ b/optimiser.py Tue Oct 06 14:31:54 2015 +0200 @@ -59,6 +59,16 @@ d[(255, 255, 255)] += common return [(f, value) for value, f in d.items()] +def compensate(d, chosen): + dd = dict([(value, f) for f, value in d]) + for f, value in d: + if value not in chosen: + _value, complement = complements(value) + if complement in chosen: + f = max(0, f - dd[complement]) + dd[value] = f + return [(f, value) for value, f in dd.items() if value in chosen] + def combine(d): out = [0, 0, 0] for v, rgb in d: @@ -67,15 +77,19 @@ out[2] += v * rgb[2] return out -def pattern(rgb): +def pattern(rgb, chosen=None): l = combination(rgb) + if chosen: + l = compensate(l, chosen) l.sort(reverse=True) return l -def get_value(rgb): - choose = random() +def get_value(rgb, chosen=None): + l = pattern(rgb, chosen) + limit = sum([f for f, c in l]) + choose = random() * limit threshold = 0 - for f, c in pattern(rgb): + for f, c in l: threshold += f if choose < threshold: return c @@ -147,6 +161,7 @@ desaturate = sys.argv[3:].count("-d") preview = "-p" in sys.argv[3:] square = "-2" in sys.argv[3:] and square or (lambda x: x) + randomise = "-R" in sys.argv[3:] x = EXIF.process_file(open(input_filename)) im = PIL.Image.open(input_filename).convert("RGB") @@ -192,7 +207,7 @@ most = [value for n, value in c[:4]] least = [value for n, value in c[4:]] - if least: + if least and randomise: switched = [] for j in 1, 2: i = randrange(0, 4) @@ -206,14 +221,7 @@ for x in range(0, width): rgb = im.getpixel((x, y)) - - # Get the requested colours and choose the closest alternative for - # less common colours. - - value = get_value(rgb) - if value in least: - value = nearest(value, most) - + value = get_value(rgb, most) im.putpixel((x, y), value) im.save(output_filename)