# HG changeset patch # User Paul Boddie # Date 1443995736 -7200 # Node ID 4b9192e71fb852f0ada19a32fccb43bbfec76dad # Parent 2e2722f377b05cbf3a7de07d86000f256036f1d2 Introduced a distance-based approach to obtain suitable alternative colours. diff -r 2e2722f377b0 -r 4b9192e71fb8 optimiser.py --- a/optimiser.py Sun Oct 04 21:47:16 2015 +0200 +++ b/optimiser.py Sun Oct 04 23:55:36 2015 +0200 @@ -1,6 +1,6 @@ #!/usr/bin/env python -from random import random, randrange +from random import choice, random, randrange from os.path import splitext import EXIF import PIL.Image @@ -20,8 +20,14 @@ def nearest(rgb, values): l = [(distance(rgb, value), value) for value in values] - l.sort() - return l[0][1] + total = sum([d for d, value in l]) + l = [(d / total, value) for d, value in l] + l.sort(reverse=True) + lc = [(d, value) for d, value in l if common(rgb, value)] + return get_from_distribution(rgb, lc or l) + +def common(rgb1, rgb2): + return sum(map(lambda x: x[0] * x[1], zip(rgb1, rgb2))) != 0 def restore(srgb): return tuple(map(lambda x: int(x * 255.0), srgb)) @@ -72,15 +78,18 @@ l.sort(reverse=True) return l -def get_value(rgb): +def get_from_distribution(rgb, dist): choose = random() threshold = 0 - for f, c in pattern(rgb): + for f, c in dist: threshold += f if choose < threshold: return c return c +def get_value(rgb): + return get_from_distribution(rgb, pattern(rgb)) + def sign(x): return x >= 0 and 1 or -1 @@ -212,7 +221,7 @@ value = get_value(rgb) if value in least: - value = nearest(value, most) + value = nearest(rgb, most) im.putpixel((x, y), value)