1.1 --- a/optimiserlib.py Sat Oct 10 16:04:09 2015 +0200
1.2 +++ b/optimiserlib.py Sat Oct 10 16:13:09 2015 +0200
1.3 @@ -175,6 +175,27 @@
1.4
1.5 # Image operations.
1.6
1.7 +def get_colours(im, y):
1.8 +
1.9 + "Get a colour distribution from image 'im' for the row 'y'."
1.10 +
1.11 + width, height = im.size
1.12 + c = {}
1.13 + for x in range(0, width):
1.14 + rgb = im.getpixel((x, y))
1.15 +
1.16 + # Sum the colour probabilities.
1.17 +
1.18 + for f, value in combination(rgb):
1.19 + if not c.has_key(value):
1.20 + c[value] = f
1.21 + else:
1.22 + c[value] += f
1.23 +
1.24 + d = [(n/width, value) for value, n in c.items()]
1.25 + d.sort(reverse=True)
1.26 + return d
1.27 +
1.28 def get_combinations(c, n):
1.29
1.30 """
1.31 @@ -191,6 +212,24 @@
1.32 all.sort(reverse=True)
1.33 return [l for total, l in all]
1.34
1.35 +def count_colours(im, colours):
1.36 +
1.37 + """
1.38 + Count colours on each row of image 'im', returning a tuple indicating the
1.39 + first row with more than the given number of 'colours' together with the
1.40 + found colours; otherwise returning None.
1.41 + """
1.42 +
1.43 + width, height = im.size
1.44 +
1.45 + for y in range(0, height):
1.46 + l = set()
1.47 + for x in range(0, width):
1.48 + l.add(im.getpixel((x, y)))
1.49 + if len(l) > colours:
1.50 + return (y, l)
1.51 + return None
1.52 +
1.53 class SimpleImage:
1.54
1.55 "An image behaving like PIL.Image."
1.56 @@ -232,4 +271,7 @@
1.57 im2.putpixel((0, 0), (255, 255, 255))
1.58 im2.getdata() == [(255, 255, 255), (0, 0, 0)]
1.59
1.60 + get_colours(im, 0) == [(1.0, (0, 0, 0))]
1.61 + count_colours(im, 4)
1.62 +
1.63 # vim: tabstop=4 expandtab shiftwidth=4