fix bug in color conversion
[imago.git] / imago_pack / 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 k_means
9 import output
10
11 def dst(line):
12     """Return normalized line."""
13     if line[0] < pi / 2:
14         line = line[0] + pi, - line[1]
15     return line
16
17 def dst_sort(lines):
18     """Return lines sorted by distance."""
19     l_max = max(l[0] for l in lines)
20     l_min = min(l[0] for l in lines)
21     if l_max - l_min > (3. / 4) * pi:
22         lines = [dst(l) for l in lines]
23     lines.sort(key=itemgetter(1))
24     return lines
25
26 def board(image, lines, show_all, do_something):
27     """Compute intersections, find stone colors and return board situation."""
28     lines = [dst_sort(l) for l in lines]
29     intersections = intersections_from_angl_dist(lines, image.size)
30
31     if show_all:
32         image_g = image.copy()
33         draw = ImageDraw.Draw(image_g)
34         for line in intersections:
35             for (x, y) in line:
36                 draw.point((x , y), fill=(120, 255, 120))
37         do_something(image_g, "intersections")
38
39     board_raw = []
40     
41     for line in intersections:
42         board_raw.append([stone_color_raw(image, intersection) for intersection in
43                       line])
44     board_raw = sum(board_raw, [])
45
46     ### Show color distribution
47     luma = [s[0] for s in board_raw]
48     saturation = [s[1] for s in board_raw]
49
50     if show_all:
51         import matplotlib.pyplot as pyplot
52         pyplot.scatter(luma, saturation, 
53                        color=[(s[2][0]/255., s[2][1]/255., s[2][2]/255., 1.) 
54                               for s in board_raw])
55         pyplot.show()
56
57     clusters = k_means.cluster(3, 2,zip(zip(luma, saturation), range(len(luma))),
58                                [[0., 0.], [0.5, 0.5], [1., 1.]])
59    #clusters.sort(key=mean_luma)
60
61     if show_all:
62         pyplot.scatter([d[0][0] for d in clusters[0]], [d[0][1] for d in clusters[0]],
63                                                  color=(1,0,0,1))
64         pyplot.scatter([d[0][0] for d in clusters[1]], [d[0][1] for d in clusters[1]],
65                                                  color=(0,1,0,1))
66         pyplot.scatter([d[0][0] for d in clusters[2]], [d[0][1] for d in clusters[2]],
67                                                  color=(0,0,1,1))
68         pyplot.show()
69
70     clusters[0] = [(p[1], 'B') for p in clusters[0]]
71     clusters[1] = [(p[1], '.') for p in clusters[1]]
72     clusters[2] = [(p[1], 'W') for p in clusters[2]]
73
74     board_rl = sum(clusters, [])
75     board_rl.sort()
76     board_rg = (p[1] for p in board_rl)
77     
78     board_r = []
79
80     #TODO 19 should be a size parameter
81     try:
82         for i in xrange(19):
83             for _ in xrange(19):
84                 board_r.append(board_rg.next())
85     except StopIteration:
86         pass
87     
88
89     return output.Board(19, board_r)
90
91 def mean_luma(cluster):
92     return sum(c[0][0] for c in cluster) / float(len(cluster))
93
94 def intersections_from_angl_dist(lines, size, get_all=True):
95     """Take grid-lines and size of the image. Return intersections."""
96     intersections = []
97     for (angl1, dist1) in lines[1]:
98         line = []
99         for (angl2, dist2) in lines[0]:
100             if abs(angl1 - angl2) > 0.4:
101                 i_x =  (- ((dist2 / cos(angl2)) - (dist1 / cos(angl1))) 
102                         / (tan(angl1) - tan(angl2)))
103                 i_y = (tan(angl1) * i_x) - (dist1 / cos(angl1))
104                 if get_all or (-size[0] / 2 < i_x < size[0] / 2 and 
105                     -size[1] / 2 < i_y < size[1] / 2):
106                     line.append((int(i_x + size[0] / 2),
107                                  int(i_y + size[1] / 2)))
108         intersections.append(line)
109     return intersections
110    
111 def RGBtoSat(c):
112     max_diff = max(c) - min(c)
113     if max_diff == 0:
114         return 0
115     else:
116         #TODO simplify this
117         return max_diff / float(255. - abs(max(c) + min(c) - 255))
118
119 def stone_color_raw(image, (x, y)):
120     """Given image and coordinates, return stone color."""
121     suma = []
122     for i in range(-2, 3):
123         for j in range(-2, 3):
124             try:
125                 suma.append(image.getpixel((x + i, y + j)))
126             except IndexError:
127                 pass
128     luma = sum([0.30 * sum(s[0] for s in suma) / 25., 0.59 * sum(s[1] for s in suma) / 25., 
129             0.11 * sum(s[2] for s in suma) / 25.]) / 255.
130     saturation = sum(RGBtoSat(s) for s in suma) / (25. * 255.)
131     color = [sum(s[0] for s in suma) / 25., sum(s[1] for s in suma) / 25.,
132              sum(s[2] for s in suma) / 25.]
133     return luma, saturation, color