ca8decba771fff4f3b4634f47f0d32469004fccc
[imago.git] / src / gridf3.py
1 import random
2 from math import sqrt
3
4 from intrsc import intersections_from_angl_dist
5 import linef as linef
6 import ransac as ransac
7 import manual as manual
8 from geometry import l2ad
9
10 # TODO comments, refactoring, move methods to appropriate modules
11
12 class GridFittingFailedError(Exception):
13     pass
14
15 class BadGenError(Exception):
16     pass
17
18 def plot_line(line, c, size):
19     points = linef.line_from_angl_dist(line, size)
20     pyplot.plot(*zip(*points), color=c)
21
22
23 class Diagonal_model:
24     def __init__(self, data):
25         self.data = [p for p in sum(data, []) if p]
26         self.lines = data
27         self.gen = self.initial_g()
28
29     def initial_g(self):
30         l1, l2 = random.sample(self.lines, 2)
31         for i in xrange(len(l1)):
32             for j in xrange(len(l2)):
33                 if i == j:
34                     continue
35                 if l1[i] and l2[j]:
36                     yield (l1[i], l2[j])
37
38     def remove(self, data):
39         self.data = list(set(self.data) - set(data))
40
41     def initial(self):
42         try:
43             nxt = self.gen.next()
44         except StopIteration:
45             self.gen = self.initial_g()
46             nxt = self.gen.next()
47         return nxt
48
49     def get(self, sample):
50         if len(sample) == 2:
51             return ransac.points_to_line(*sample)
52         else:
53             return ransac.least_squares(sample)
54
55     def score(self, est, dist):
56         cons = []
57         score = 0
58         a, b, c = est
59         dst = lambda (x, y): abs(a * x + b * y + c) / sqrt(a*a+b*b)
60         l1 = None
61         l2 = None
62         for p in self.data:
63             d = dst(p)
64             if d <= dist:
65                 cons.append(p)
66                 if p.l1 == l1 or p.l2 == l2:
67                     return float("inf"), []
68                 else:
69                     l1, l2 = p.l1, p.l2
70             else: # TODO delete this or refactor
71                 score += min(d, dist)
72
73         return score, cons
74
75 def intersection((a1, b1, c1), (a2, b2, c2)):
76     delim = float(a1 * b2 - b1 * a2)
77     if delim == 0:
78         return None
79     x = (b1 * c2 - c1 * b2) / delim
80     y = (c1 * a2 - a1 * c2) / delim
81     return x, y
82
83 class Point:
84     def __init__(self, (x, y)):
85         self.x = x
86         self.y = y
87
88     def __getitem__(self, key):
89         if key == 0:
90             return self.x
91         elif key == 1:
92             return self.y
93
94     def __iter__(self):
95         yield self.x
96         yield self.y
97
98     def __len__(self):
99         return 2
100
101     def to_tuple(self):
102         return (self.x, self.y)
103
104 class Line:
105     def __init__(self, (a, b, c)):
106         self.a, self.b, self.c = (a, b, c)
107         self.points = []
108
109     @classmethod
110     def from_ad(cls, (a, d), size):
111         p = linef.line_from_angl_dist((a, d), size)
112         return cls(ransac.points_to_line(*p))
113
114     def __iter__(self):
115         yield self.a
116         yield self.b
117         yield self.c
118
119     def __len__(self):
120         return 3
121
122     def __getitem__(self, key):
123         if key == 0:
124             return self.a
125         elif key == 1:
126             return self.b
127         elif key == 2:
128             return self.c
129
130 def gen_corners(d1, d2, min_size):
131     for c1 in d1.points:
132         if c1 in d2.points:
133             continue
134         pass
135         try:
136             c2 = [p for p in d2.points if p in c1.l1.points][0]
137             c3 = [p for p in d1.points if p in c2.l2.points][0]
138             c4 = [p for p in d2.points if p in c3.l1.points][0]
139             x_min = min([c1[0], c2[0], c3[0], c4[0]])
140             x_max = max([c1[0], c2[0], c3[0], c4[0]])
141             if x_max - x_min < min_size:
142                 continue
143             y_min = min([c1[1], c2[1], c3[1], c4[1]])
144             y_max = max([c1[1], c2[1], c3[1], c4[1]])
145             if y_max - y_min < min_size:
146                 continue
147
148         except IndexError:
149             continue
150             # there is not a corresponding intersection
151             # TODO create an intersection?
152         try:
153             yield manual.lines(map(lambda p: p.to_tuple(), [c2, c1, c3, c4]))
154         except (TypeError):
155             pass
156             # the square was too small to fit 17 lines inside
157             # TODO define SquareTooSmallError or something
158
159 def dst(p, l):
160     (x, y), (a, b, c) = p, ransac.points_to_line(*l)
161     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
162
163 def score(lines, points):
164     # TODO find whether the point actualy lies on the line or just in the same
165     # direction
166     score = 0
167     for p in points:
168         s = min(map(lambda l: dst(p, l), lines))
169         s = min(s, 2)
170         score += s
171     return score
172
173
174 def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
175     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
176     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
177     for l1 in new_lines1:
178         for l2 in new_lines2:
179             p = Point(intersection(l1, l2))
180             p.l1 = l1
181             p.l2 = l2
182             l1.points.append(p)
183             l2.points.append(p)
184
185     points = [l.points for l in new_lines1]
186
187     def dst_p(x, y):
188         x = x - size[0] / 2
189         y = y - size[1] / 2
190         return sqrt(x * x + y * y)
191
192     for n_tries in xrange(3):
193         logger("finding the diagonals")
194         model = Diagonal_model(points)
195         diag_lines = ransac.ransac_multi(6, points, 2, 400, model=model)
196         diag_lines = [l[0] for l in diag_lines]
197         centers = []
198         cen_lin = []
199         for i in xrange(len(diag_lines)):
200             line1 = diag_lines[i]
201             for line2 in diag_lines[i+1:]:
202                 c = intersection(line1, line2)
203                 if c and dst_p(*c) < min(size) / 2:
204                     cen_lin.append((line1, line2, c))
205                     centers.append(c)
206
207         if show_all:
208             import matplotlib.pyplot as pyplot
209             from PIL import Image
210
211             def plot_line_g((a, b, c), max_x):
212                 find_y = lambda x: - (c + a * x) / b
213                 pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
214
215             fig = pyplot.figure(figsize=(8, 6))
216             for l in diag_lines:
217                 plot_line_g(l, size[0])
218             pyplot.scatter(*zip(*sum(points, [])))
219             if len(centers) >= 1:
220                 pyplot.scatter([c[0] for c in centers], [c[1] for c in centers], color='r')
221             pyplot.xlim(0, size[0])
222             pyplot.ylim(0, size[1])
223             pyplot.gca().invert_yaxis()
224             fig.canvas.draw()
225             size_f = fig.canvas.get_width_height()
226             buff = fig.canvas.tostring_rgb()
227             image_p = Image.fromstring('RGB', size_f, buff, 'raw')
228             do_something(image_p, "finding diagonals")
229
230         logger("finding the grid")
231         data = sum(points, [])
232         # TODO what if lines are missing?
233         sc = float("inf")
234         grid = None
235         for (line1, line2, c) in cen_lin:
236             diag1 = Line(line1)
237             diag1.points = ransac.filter_near(data, diag1, 2)
238             diag2 = Line(line2)
239             diag2.points = ransac.filter_near(data, diag2, 2)
240
241
242             grids = list(gen_corners(diag1, diag2, min(size) / 3))
243             
244             try:
245                 new_sc, new_grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
246                 if new_sc < sc:
247                     sc, grid = new_sc, new_grid
248             except ValueError:
249                 pass
250         if grid:
251             break
252     else:
253         raise GridFittingFailedError
254         
255     grid_lines = [[l2ad(l, size) for l in grid[0]], 
256                   [l2ad(l, size) for l in grid[1]]]
257     grid_lines[0].sort(key=lambda l: l[1])
258     grid_lines[1].sort(key=lambda l: l[1])
259     if grid_lines[0][0][0] > grid_lines[1][0][0]:
260         grid_lines = grid_lines[1], grid_lines[0]
261
262     return grid, grid_lines
263