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