measuring performance
[imago.git] / src / intrsc.py
1 """Imago intersections module."""
2
3 from math import cos, tan, pi
4 from operator import itemgetter
5 import colorsys
6
7 import ImageDraw
8
9 import filters
10 import k_means
11 import output
12 import linef
13
14 def dst(line):
15     """Return normalized line."""
16     if line[0] < pi / 2:
17         line = line[0] + pi, - line[1]
18     return line
19
20 def dst_sort(lines):
21     """Return lines sorted by distance."""
22     l_max = max(l[0] for l in lines)
23     l_min = min(l[0] for l in lines)
24     if l_max - l_min > (3. / 4) * pi:
25         lines = [dst(l) for l in lines]
26     lines.sort(key=itemgetter(1))
27     return lines
28
29 def board(image, lines, show_all, do_something, logger):
30     """Compute intersections, find stone colors and return board situation."""
31     # TODO refactor show_all, do_something
32     # TODO refactor this into smaller functions
33     logger("finding the stones")
34     lines = [dst_sort(l) for l in lines]
35     an0 = (sum([l[0] for l in lines[0]]) / len(lines[0]) - pi / 2)
36     an1 = (sum([l[0] for l in lines[1]]) / len(lines[1]) - pi / 2)
37     if an0 > an1:
38         lines = [lines[1], lines[0]]
39
40     intersections = intersections_from_angl_dist(lines, image.size)
41
42     if show_all:
43         image_g = image.copy()
44         draw = ImageDraw.Draw(image_g)
45         for line in intersections:
46             for (x, y) in line:
47                 draw.point((x , y), fill=(120, 255, 120))
48         do_something(image_g, "intersections")
49
50     image_c = filters.color_enhance(image)
51     if show_all:
52         do_something(image_c, "white balance")
53     
54     board_raw = []
55     
56     for line in intersections:
57         board_raw.append([stone_color_raw(image_c, intersection) for intersection in
58                       line])
59     board_raw = sum(board_raw, [])
60
61     ### Show color distribution
62
63     if show_all:
64         import matplotlib.pyplot as pyplot
65         import Image
66         fig = pyplot.figure(figsize=(8, 6))
67         luma = [s[0] for s in board_raw]
68         saturation = [s[1] for s in board_raw]
69         pyplot.scatter(luma, saturation, 
70                        color=[s[2] for s in board_raw])
71         pyplot.xlim(0,1)
72         pyplot.ylim(0,1)
73         fig.canvas.draw()
74         size = fig.canvas.get_width_height()
75         buff = fig.canvas.tostring_rgb()
76         image_p = Image.fromstring('RGB', size, buff, 'raw')
77         do_something(image_p, "color distribution")
78
79     #max_s0 = max(s[0] for s in board_raw)
80     #min_s0 = min(s[0] for s in board_raw)
81     #norm_s0 = lambda x: (x - min_s0) / (max_s0 - min_s0)
82     #max_s1 = max(s[1] for s in board_raw)
83     #min_s1 = min(s[1] for s in board_raw)
84     #norm_s1 = lambda x: (x - min_s1) / (max_s1 - min_s1)
85     #max_s1 = max(s[1] for s in board_raw)
86     #min_s1 = min(s[1] for s in board_raw)
87     #norm_s1 = lambda x: (x - min_s1) / (max_s1 - min_s1)
88     #color_data = [(norm_s0(s[0]), norm_s1(s[1])) for s in board_raw]
89     color_data = [(s[0], s[1]) for s in board_raw]
90
91     clusters = k_means.cluster(3, 2,zip(color_data, range(len(color_data))),
92                                [[0., 0.5], [0.5, 0.5], [1., 0.5]])
93
94     if show_all:
95         fig = pyplot.figure(figsize=(8, 6))
96         pyplot.scatter([d[0][0] for d in clusters[0]], [d[0][1] for d in clusters[0]],
97                                                  color=(1,0,0,1))
98         pyplot.scatter([d[0][0] for d in clusters[1]], [d[0][1] for d in clusters[1]],
99                                                  color=(0,1,0,1))
100         pyplot.scatter([d[0][0] for d in clusters[2]], [d[0][1] for d in clusters[2]],
101                                                  color=(0,0,1,1))
102         pyplot.xlim(0,1)
103         pyplot.ylim(0,1)
104         fig.canvas.draw()
105         size = fig.canvas.get_width_height()
106         buff = fig.canvas.tostring_rgb()
107         image_p = Image.fromstring('RGB', size, buff, 'raw')
108         do_something(image_p, "color clustering")
109
110     clusters[0] = [(p[1], 'B') for p in clusters[0]]
111     clusters[1] = [(p[1], '.') for p in clusters[1]]
112     clusters[2] = [(p[1], 'W') for p in clusters[2]]
113
114     board_rl = sum(clusters, [])
115     board_rl.sort()
116     board_rg = (p[1] for p in board_rl)
117     
118     board_r = []
119
120     #TODO 19 should be a size parameter
121     try:
122         for i in xrange(19):
123             for _ in xrange(19):
124                 board_r.append(board_rg.next())
125     except StopIteration:
126         pass
127     
128
129     return output.Board(19, board_r)
130
131 def mean_luma(cluster):
132     """Return mean luminanace of the *cluster* of points."""
133     return sum(c[0][0] for c in cluster) / float(len(cluster))
134
135 def to_general(line, size):
136     # TODO comment
137     (x1, y1), (x2, y2) = linef.line_from_angl_dist(line, size)
138     return (y2 - y1, x1 - x2, x2 * y1 - x1 * y2)
139
140 def intersection(l1, l2):
141     a1, b1, c1 = l1
142     a2, b2, c2 = l2
143     delim = float(a1 * b2 - b1 * a2)
144     x = (b1 * c2 - c1 * b2) / delim
145     y = (c1 * a2 - a1 * c2) / delim
146     return x, y
147
148 # TODO remove the parameter get_all
149 def intersections_from_angl_dist(lines, size, get_all=True):
150     """Take grid-lines and size of the image. Return intersections."""
151     lines0 = map(lambda l: to_general(l, size), lines[0])
152     lines1 = map(lambda l: to_general(l, size), lines[1])
153     intersections = []
154     for l1 in lines1:
155         line = []
156         for l2 in lines0:
157             line.append(intersection(l1, l2))
158         intersections.append(line)
159     return intersections
160    
161 def rgb2lumsat(color):
162     """Convert RGB to luminance and HSI model saturation."""
163     r, g, b = color
164     luma = (0.30 * r + 0.59 * g + 0.11 * b) / 255.0
165     max_diff = max(color) - min(color)
166     if max_diff == 0:
167         saturation = 0
168     else:
169         saturation = 1. - ((3. * min(color)) / sum(color)) 
170     return luma, saturation
171
172 def median(lst):
173     #TODO comment (or delete maybe?)
174     len_lst = len(lst)
175     if len_lst % 2 == 0:
176         return (lst[len_lst / 2] + lst[len_lst / 2 + 1]) / 2.0
177     else:
178         return lst[len_lst / 2]
179
180 def stone_color_raw(image, (x, y)):
181     """Given image and coordinates, return stone color."""
182     size = 3 
183     points = []
184     for i in range(-size, size + 1):
185         for j in range(-size, size + 1):
186             try:
187                 points.append(image.getpixel((x + i, y + j)))
188             except IndexError:
189                 pass
190     norm = float(len(points))
191     if norm == 0:
192         return 0, 0, (0, 0, 0) #TODO trow exception here
193     norm = float(norm*255)
194     color = (sum(p[0] for p in points) / norm,
195              sum(p[1] for p in points) / norm,
196              sum(p[2] for p in points) / norm)
197     hue, luma, saturation = colorsys.rgb_to_hls(*color)
198     color = colorsys.hls_to_rgb(hue, 0.5, 1.)
199     return luma, saturation, color, hue