preliminary work on generalized RANSAC
[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             score += min(d, dist)
71
72         return score, cons
73
74 def intersection((a1, b1, c1), (a2, b2, c2)):
75     delim = float(a1 * b2 - b1 * a2)
76     x = (b1 * c2 - c1 * b2) / delim
77     y = (c1 * a2 - a1 * c2) / delim
78     return x, y
79
80 class Point:
81     def __init__(self, (x, y)):
82         self.x = x
83         self.y = y
84
85     def __getitem__(self, key):
86         if key == 0:
87             return self.x
88         elif key == 1:
89             return self.y
90
91     def __iter__(self):
92         yield self.x
93         yield self.y
94
95     def __len__(self):
96         return 2
97
98     def to_tuple(self):
99         return (self.x, self.y)
100
101 class Line:
102     def __init__(self, (a, b, c)):
103         self.a, self.b, self.c = (a, b, c)
104         self.points = []
105
106     @classmethod
107     def from_ad(cls, (a, d), size):
108         p = linef.line_from_angl_dist((a, d), size)
109         return cls(ransac.points_to_line(*p))
110
111     def __iter__(self):
112         yield self.a
113         yield self.b
114         yield self.c
115
116     def __len__(self):
117         return 3
118
119     def __getitem__(self, key):
120         if key == 0:
121             return self.a
122         elif key == 1:
123             return self.b
124         elif key == 2:
125             return self.c
126
127 def gen_corners(d1, d2):
128     for c1 in d1.points:
129         if c1 in d2.points:
130             continue
131         pass
132         try:
133             c2 = [p for p in d2.points if p in c1.l1.points][0]
134             c3 = [p for p in d1.points if p in c2.l2.points][0]
135             c4 = [p for p in d2.points if p in c3.l1.points][0]
136         except IndexError:
137             continue
138             # there is not a corresponding intersection
139             # TODO create an intersection?
140         try:
141             yield manual.lines(map(lambda p: p.to_tuple(), [c2, c1, c3, c4]))
142         except (TypeError, ZeroDivisionError):
143             pass
144             # the square was too small to fit 17 lines inside
145             # TODO define SquareTooSmallError or something
146
147 def dst(p, l):
148     (x, y), (a, b, c) = p, ransac.points_to_line(*l)
149     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
150
151 def score(lines, points):
152     score = 0
153     for p in points:
154         s = min(map(lambda l: dst(p, l), lines))
155         s = min(s, 2)
156         score += s
157     return score
158
159
160 def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
161     logger("finding the grid")
162     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
163     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
164     for l1 in new_lines1:
165         for l2 in new_lines2:
166             p = Point(intersection(l1, l2))
167             p.l1 = l1
168             p.l2 = l2
169             l1.points.append(p)
170             l2.points.append(p)
171
172     points = [l.points for l in new_lines1]
173
174     for trial in xrange(3):
175         line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
176         points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
177         line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
178         center = intersection(line1, line2)
179         data = sum(points, [])
180         diag1 = Line(line1)
181         diag1.points = ransac.filter_near(data, diag1, 2)
182         diag2 = Line(line2)
183         diag2.points = ransac.filter_near(data, diag2, 2)
184
185         if show_all:
186             import matplotlib.pyplot as pyplot
187             import Image
188
189             def plot_line_g((a, b, c), max_x):
190                 find_y = lambda x: - (c + a * x) / b
191                 pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
192
193             fig = pyplot.figure(figsize=(8, 6))
194             plot_line_g(diag1, size[0])
195             plot_line_g(diag2, size[0])
196             pyplot.scatter(*zip(*sum(points, [])))
197             pyplot.scatter([center[0]], [center[1]], color='r')
198             pyplot.xlim(0, size[0])
199             pyplot.ylim(0, size[1])
200             pyplot.gca().invert_yaxis()
201             fig.canvas.draw()
202             size_f = fig.canvas.get_width_height()
203             buff = fig.canvas.tostring_rgb()
204             image_p = Image.fromstring('RGB', size_f, buff, 'raw')
205             do_something(image_p, "finding diagonal")
206
207
208         grids = list(gen_corners(diag1, diag2))
209         
210         try:
211             sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
212             break
213         except ValueError:
214             pass
215     else:
216         raise GridFittingFailedError
217         
218     grid_lines = [[l2ad(l, size) for l in grid[0]], 
219                   [l2ad(l, size) for l in grid[1]]]
220     grid_lines[0].sort(key=lambda l: l[1])
221     grid_lines[1].sort(key=lambda l: l[1])
222     if grid_lines[0][0][0] > grid_lines[1][0][0]:
223         grid_lines = grid_lines[1], grid_lines[0]
224
225     return grid, grid_lines
226