1.1 --- a/optimiserlib.py Sun Oct 11 20:10:50 2015 +0200
1.2 +++ b/optimiserlib.py Sun Oct 11 23:23:26 2015 +0200
1.3 @@ -22,6 +22,7 @@
1.4
1.5 from random import random, randrange
1.6 import itertools
1.7 +import math
1.8
1.9 corners = [
1.10 (0, 0, 0), (255, 0, 0), (0, 255, 0), (255, 255, 0),
1.11 @@ -36,6 +37,9 @@
1.12 def clip(v):
1.13 return int(within(v, 0, 255))
1.14
1.15 +def distance(rgb1, rgb2):
1.16 + return math.sqrt(pow(abs(rgb1[0] - rgb2[0]), 2) + pow(abs(rgb1[1] - rgb2[1]), 2) + pow(abs(rgb1[2] - rgb2[2]), 2))
1.17 +
1.18 def restore(srgb):
1.19 r, g, b = srgb
1.20 return int(r * 255.0), int(g * 255.0), int(b * 255.0)
1.21 @@ -257,7 +261,7 @@
1.22 x += 1
1.23 y += 1
1.24
1.25 -def convert_image(im, colours):
1.26 +def convert_image(im, colours, least_error=False):
1.27
1.28 "Convert image 'im' to an appropriate output representation."
1.29
1.30 @@ -271,19 +275,22 @@
1.31
1.32 for l in get_combinations(c, colours):
1.33 most = [value for f, value in l]
1.34 - missing = 0
1.35 + error = 0
1.36
1.37 x = 0
1.38 while x < width:
1.39 rgb = im.getpixel((x, y))
1.40 - value = get_value(rgb, most, True)
1.41 - if value is None:
1.42 - missing += 1
1.43 + value = get_value(rgb, most)
1.44 + if least_error:
1.45 + error += distance(value, rgb)
1.46 + elif value is None:
1.47 + error += 1
1.48 x += 1
1.49
1.50 - if not missing:
1.51 + if not least_error and not error:
1.52 break # use this combination
1.53 - suggestions.append((missing, l))
1.54 +
1.55 + suggestions.append((error, l))
1.56
1.57 # Find the most accurate suggestion.
1.58