1.1 --- a/optimiser.py Thu Oct 01 02:37:54 2015 +0200
1.2 +++ b/optimiser.py Thu Oct 01 12:50:55 2015 +0200
1.3 @@ -40,8 +40,8 @@
1.4 l.sort()
1.5 return l
1.6
1.7 -def pattern(rgb):
1.8 - l = nearest(rgb)
1.9 +def pattern(rgb, values=None):
1.10 + l = nearest(rgb, values)
1.11 start, end = l[0][1], l[1][1]
1.12 f = factor(start, end, rgb)
1.13 #if f > 0.5:
1.14 @@ -54,9 +54,9 @@
1.15 current = int((seq + 1) * math.sqrt(f))
1.16 return last != current
1.17
1.18 -def get_value(xy, rgb, width, height):
1.19 +def get_value(xy, rgb, width, height, values=None):
1.20 x, y = xy
1.21 - rgb1, rgb2, f = pattern(rgb)
1.22 + rgb1, rgb2, f = pattern(rgb, values)
1.23 if choose(x + randint(0, width), f) and choose(y + randint(0, height), f):
1.24 return rgb2
1.25 else:
1.26 @@ -72,7 +72,7 @@
1.27 return tuple([saturate_value(x, exp) for x in rgb])
1.28
1.29 def saturate_value(x, exp):
1.30 - return 127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp)
1.31 + return int(127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp))
1.32
1.33 def test():
1.34 size = 512
1.35 @@ -132,29 +132,39 @@
1.36 c = {}
1.37 for x in range(0, width):
1.38 rgb = im.getpixel((x, y))
1.39 +
1.40 + # Saturate if requested.
1.41 +
1.42 if saturate or desaturate:
1.43 rgb = saturate_rgb(rgb, saturate and math.pow(0.5, saturate) or math.pow(2, desaturate))
1.44 + im.putpixel((x, y), rgb)
1.45 +
1.46 + # Count the number of requested colours.
1.47 +
1.48 value = get_value((x, y), rgb, width, height)
1.49 - im.putpixel((x, y), value)
1.50 if not c.has_key(value):
1.51 c[value] = 1
1.52 else:
1.53 c[value] += 1
1.54 +
1.55 c = [(n, value) for value, n in c.items()]
1.56 c.sort(reverse=True)
1.57 colours.append(c)
1.58
1.59 for y, c in enumerate(colours):
1.60 - if len(c) <= 4:
1.61 - continue
1.62 most = [value for n, value in c[:4]]
1.63 least = [value for n, value in c[4:]]
1.64
1.65 for x in range(0, width):
1.66 rgb = im.getpixel((x, y))
1.67 - if rgb in least:
1.68 - value = get_best(rgb, most)
1.69 - im.putpixel((x, y), value)
1.70 +
1.71 + # Get the requested colours and choose the closest alternative for
1.72 + # less common colours.
1.73 +
1.74 + value = get_value((x, y), rgb, width, height)
1.75 + if value in least:
1.76 + value = get_value((x, y), rgb, width, height, most)
1.77 + im.putpixel((x, y), value)
1.78
1.79 im.save(output_filename)
1.80