b0e798ce5c430c3606d8aa82ace9ac014f6c3d03
[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 b_intersects(image, lines, show_all, do_something, logger):
30     """Compute intersections."""
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     return intersections
51
52 def board(image, intersections, show_all, do_something, logger):
53     """Find stone colors and return board situation."""
54
55 #    image_c = filters.color_enhance(image)
56 #    if show_all:
57 #        do_something(image_c, "white balance")
58     image_c = image
59     
60     board_raw = []
61     
62     for line in intersections:
63         board_raw.append([stone_color_raw(image_c, intersection) for intersection in
64                       line])
65     board_raw = sum(board_raw, [])
66
67     ### Show color distribution
68
69     if show_all:
70         import matplotlib.pyplot as pyplot
71         import Image
72         fig = pyplot.figure(figsize=(8, 6))
73         luma = [s[0] for s in board_raw]
74         saturation = [s[1] for s in board_raw]
75         pyplot.scatter(luma, saturation, 
76                        color=[s[2] for s in board_raw])
77         pyplot.xlim(0,1)
78         pyplot.ylim(0,1)
79         fig.canvas.draw()
80         size = fig.canvas.get_width_height()
81         buff = fig.canvas.tostring_rgb()
82         image_p = Image.fromstring('RGB', size, buff, 'raw')
83         do_something(image_p, "color distribution")
84
85     #max_s0 = max(s[0] for s in board_raw)
86     #min_s0 = min(s[0] for s in board_raw)
87     #norm_s0 = lambda x: (x - min_s0) / (max_s0 - min_s0)
88     #max_s1 = max(s[1] for s in board_raw)
89     #min_s1 = min(s[1] for s in board_raw)
90     #norm_s1 = lambda x: (x - min_s1) / (max_s1 - min_s1)
91     #max_s1 = max(s[1] for s in board_raw)
92     #min_s1 = min(s[1] for s in board_raw)
93     #norm_s1 = lambda x: (x - min_s1) / (max_s1 - min_s1)
94     #color_data = [(norm_s0(s[0]), norm_s1(s[1])) for s in board_raw]
95     color_data = [(s[0], s[1]) for s in board_raw]
96
97     init_x = sum(c[0] for c in color_data) / float(len(color_data))
98
99     clusters, score = k_means.cluster(3, 2,zip(color_data, range(len(color_data))),
100                                [[0., 0.5], [init_x, 0.5], [1., 0.5]])
101 #    clusters1, score1 = k_means.cluster(1, 2,zip(color_data, range(len(color_data))),
102 #                               [[0.5, 0.5]])
103 #    clusters2, score2 = k_means.cluster(2, 2,zip(color_data, range(len(color_data))),
104 #                               [[0., 0.5], [0.75, 0.5]])
105 #    import sys
106 #    print >> sys.stderr, score1, score2, score
107 #
108     if show_all:
109         fig = pyplot.figure(figsize=(8, 6))
110         pyplot.scatter([d[0][0] for d in clusters[0]], [d[0][1] for d in clusters[0]],
111                                                  color=(1,0,0,1))
112         pyplot.scatter([d[0][0] for d in clusters[1]], [d[0][1] for d in clusters[1]],
113                                                  color=(0,1,0,1))
114         pyplot.scatter([d[0][0] for d in clusters[2]], [d[0][1] for d in clusters[2]],
115                                                  color=(0,0,1,1))
116         pyplot.xlim(0,1)
117         pyplot.ylim(0,1)
118         fig.canvas.draw()
119         size = fig.canvas.get_width_height()
120         buff = fig.canvas.tostring_rgb()
121         image_p = Image.fromstring('RGB', size, buff, 'raw')
122         do_something(image_p, "color clustering")
123
124     clusters[0] = [(p[1], 'B') for p in clusters[0]]
125     clusters[1] = [(p[1], '.') for p in clusters[1]]
126     clusters[2] = [(p[1], 'W') for p in clusters[2]]
127
128     board_rl = sum(clusters, [])
129     board_rl.sort()
130     board_rg = (p[1] for p in board_rl)
131     
132     board_r = []
133
134     #TODO 19 should be a size parameter
135     try:
136         for i in xrange(19):
137             for _ in xrange(19):
138                 board_r.append(board_rg.next())
139     except StopIteration:
140         pass
141     
142     return output.Board(19, board_r)
143
144 def mean_luma(cluster):
145     """Return mean luminanace of the *cluster* of points."""
146     return sum(c[0][0] for c in cluster) / float(len(cluster))
147
148 def to_general(line, size):
149     # TODO comment
150     (x1, y1), (x2, y2) = linef.line_from_angl_dist(line, size)
151     return (y2 - y1, x1 - x2, x2 * y1 - x1 * y2)
152
153 def intersection(l1, l2):
154     a1, b1, c1 = l1
155     a2, b2, c2 = l2
156     delim = float(a1 * b2 - b1 * a2)
157     x = (b1 * c2 - c1 * b2) / delim
158     y = (c1 * a2 - a1 * c2) / delim
159     return x, y
160
161 # TODO remove the parameter get_all
162 def intersections_from_angl_dist(lines, size, get_all=True):
163     """Take grid-lines and size of the image. Return intersections."""
164     lines0 = map(lambda l: to_general(l, size), lines[0])
165     lines1 = map(lambda l: to_general(l, size), lines[1])
166     intersections = []
167     for l1 in lines1:
168         line = []
169         for l2 in lines0:
170             line.append(intersection(l1, l2))
171         intersections.append(line)
172     return intersections
173    
174 def rgb2lumsat(color):
175     """Convert RGB to luminance and HSI model saturation."""
176     r, g, b = color
177     luma = (0.30 * r + 0.59 * g + 0.11 * b) / 255.0
178     max_diff = max(color) - min(color)
179     if max_diff == 0:
180         saturation = 0
181     else:
182         saturation = 1. - ((3. * min(color)) / sum(color)) 
183     return luma, saturation
184
185 def median(lst):
186     #TODO comment (or delete maybe?)
187     len_lst = len(lst)
188     if len_lst % 2 == 0:
189         return (lst[len_lst / 2] + lst[len_lst / 2 + 1]) / 2.0
190     else:
191         return lst[len_lst / 2]
192
193 def stone_color_raw(image, (x, y)):
194     """Given image and coordinates, return stone color."""
195     size = 3 
196     points = []
197     for i in range(-size, size + 1):
198         for j in range(-size, size + 1):
199             try:
200                 points.append(image.getpixel((x + i, y + j)))
201             except IndexError:
202                 pass
203     norm = float(len(points))
204     if norm == 0:
205         return 0, 0, (0, 0, 0) #TODO trow exception here
206     norm = float(norm*255)
207     color = (sum(p[0] for p in points) / norm,
208              sum(p[1] for p in points) / norm,
209              sum(p[2] for p in points) / norm)
210     hue, luma, saturation = colorsys.rgb_to_hls(*color)
211     color = colorsys.hls_to_rgb(hue, 0.5, 1.)
212     return luma, saturation, color, hue