# HG changeset patch # User Paul Boddie # Date 1443696655 -7200 # Node ID c768f24e5233faecb78a5fa97f1759bed9c2baac # Parent aabad380ed5941da6bfa64f40abb2d671613aa18 Choose the nearest alternative colours to the original colour. diff -r aabad380ed59 -r c768f24e5233 optimiser.py --- a/optimiser.py Thu Oct 01 02:37:54 2015 +0200 +++ b/optimiser.py Thu Oct 01 12:50:55 2015 +0200 @@ -40,8 +40,8 @@ l.sort() return l -def pattern(rgb): - l = nearest(rgb) +def pattern(rgb, values=None): + l = nearest(rgb, values) start, end = l[0][1], l[1][1] f = factor(start, end, rgb) #if f > 0.5: @@ -54,9 +54,9 @@ current = int((seq + 1) * math.sqrt(f)) return last != current -def get_value(xy, rgb, width, height): +def get_value(xy, rgb, width, height, values=None): x, y = xy - rgb1, rgb2, f = pattern(rgb) + rgb1, rgb2, f = pattern(rgb, values) if choose(x + randint(0, width), f) and choose(y + randint(0, height), f): return rgb2 else: @@ -72,7 +72,7 @@ return tuple([saturate_value(x, exp) for x in rgb]) def saturate_value(x, exp): - return 127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp) + return int(127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp)) def test(): size = 512 @@ -132,29 +132,39 @@ c = {} for x in range(0, width): rgb = im.getpixel((x, y)) + + # Saturate if requested. + if saturate or desaturate: rgb = saturate_rgb(rgb, saturate and math.pow(0.5, saturate) or math.pow(2, desaturate)) + im.putpixel((x, y), rgb) + + # Count the number of requested colours. + value = get_value((x, y), rgb, width, height) - im.putpixel((x, y), value) if not c.has_key(value): c[value] = 1 else: c[value] += 1 + c = [(n, value) for value, n in c.items()] c.sort(reverse=True) colours.append(c) for y, c in enumerate(colours): - if len(c) <= 4: - continue most = [value for n, value in c[:4]] least = [value for n, value in c[4:]] for x in range(0, width): rgb = im.getpixel((x, y)) - if rgb in least: - value = get_best(rgb, most) - im.putpixel((x, y), value) + + # Get the requested colours and choose the closest alternative for + # less common colours. + + value = get_value((x, y), rgb, width, height) + if value in least: + value = get_value((x, y), rgb, width, height, most) + im.putpixel((x, y), value) im.save(output_filename)