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