fix error in error-handling
[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 def plot_line(line, c, size):
13     points = linef.line_from_angl_dist(line, size)
14     pyplot.plot(*zip(*points), color=c)
15
16
17 class Diagonal_model:
18     def __init__(self, data):
19         self.data = [p for p in sum(data, []) if p]
20         self.lines = data
21         self.gen = self.initial_g()
22
23     def initial_g(self):
24         l1, l2 = random.sample(self.lines, 2)
25         for i in xrange(len(l1)):
26             for j in xrange(len(l2)):
27                 if i == j:
28                     continue
29                 if l1[i] and l2[j]:
30                     yield (l1[i], l2[j])
31
32     def initial(self):
33         try:
34             return self.gen.next()
35         except StopIteration:
36             self.gen = self.initial_g()
37             return self.gen.next()
38
39     def get(self, sample):
40         if len(sample) == 2:
41             return ransac.points_to_line(*sample)
42         else:
43             return ransac.least_squares(sample)
44
45 def intersection((a1, b1, c1), (a2, b2, c2)):
46     delim = float(a1 * b2 - b1 * a2)
47     x = (b1 * c2 - c1 * b2) / delim
48     y = (c1 * a2 - a1 * c2) / delim
49     return x, y
50
51 class Point:
52     def __init__(self, (x, y)):
53         self.x = x
54         self.y = y
55
56     def __getitem__(self, key):
57         if key == 0:
58             return self.x
59         elif key == 1:
60             return self.y
61
62     def __iter__(self):
63         yield self.x
64         yield self.y
65
66     def __len__(self):
67         return 2
68
69     def to_tuple(self):
70         return (self.x, self.y)
71
72 class Line:
73     def __init__(self, (a, b, c)):
74         self.a, self.b, self.c = (a, b, c)
75         self.points = []
76
77     @classmethod
78     def from_ad(cls, (a, d), size):
79         p = linef.line_from_angl_dist((a, d), size)
80         return cls(ransac.points_to_line(*p))
81
82     def __iter__(self):
83         yield self.a
84         yield self.b
85         yield self.c
86
87     def __len__(self):
88         return 3
89
90     def __getitem__(self, key):
91         if key == 0:
92             return self.a
93         elif key == 1:
94             return self.b
95         elif key == 2:
96             return self.c
97
98 def gen_corners(d1, d2):
99     for c1 in d1.points:
100         if c1 in d2.points:
101             continue
102         pass
103         try:
104             c2 = [p for p in d2.points if p in c1.l1.points][0]
105             c3 = [p for p in d1.points if p in c2.l2.points][0]
106             c4 = [p for p in d2.points if p in c3.l1.points][0]
107         except IndexError:
108             continue
109             # there is not a corresponding intersection
110             # TODO create an intersection?
111         try:
112             yield manual.lines(map(lambda p: p.to_tuple(), [c2, c1, c3, c4]))
113         except TypeError:
114             pass
115             # the square was too small to fit 17 lines inside
116             # TODO define SquareTooSmallError or something
117
118 def dst(p, l):
119     (x, y), (a, b, c) = p, ransac.points_to_line(*l)
120     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
121
122 def score(lines, points):
123     score = 0
124     for p in points:
125         s = min(map(lambda l: dst(p, l), lines))
126         s = min(s, 2)
127         score += s
128     return score
129
130
131 def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
132     logger("finding the grid")
133     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
134     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
135     for l1 in new_lines1:
136         for l2 in new_lines2:
137             p = Point(intersection(l1, l2))
138             p.l1 = l1
139             p.l2 = l2
140             l1.points.append(p)
141             l2.points.append(p)
142
143     points = [l.points for l in new_lines1]
144
145     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
146     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
147     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
148     center = intersection(line1, line2)
149     data = sum(points, [])
150     diag1 = Line(line1)
151     diag1.points = ransac.filter_near(data, diag1, 2)
152     diag2 = Line(line2)
153     diag2.points = ransac.filter_near(data, diag2, 2)
154
155     if show_all:
156         import matplotlib.pyplot as pyplot
157         import Image
158
159         def plot_line_g((a, b, c), max_x):
160             find_y = lambda x: - (c + a * x) / b
161             pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
162
163         fig = pyplot.figure(figsize=(8, 6))
164         plot_line_g(diag1, size[0])
165         plot_line_g(diag2, size[0])
166         pyplot.scatter(*zip(*sum(points, [])))
167         pyplot.scatter([center[0]], [center[1]], color='r')
168         pyplot.xlim(0, size[0])
169         pyplot.ylim(0, size[1])
170         fig.canvas.draw()
171         size_f = fig.canvas.get_width_height()
172         buff = fig.canvas.tostring_rgb()
173         image_p = Image.fromstring('RGB', size_f, buff, 'raw')
174         do_something(image_p, "finding diagonal")
175
176
177     grids = list(gen_corners(diag1, diag2))
178
179     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
180     
181     grid_lines = [[l2ad(l, size) for l in grid[0]], 
182                   [l2ad(l, size) for l in grid[1]]]
183     grid_lines[0].sort(key=lambda l: l[1])
184     grid_lines[1].sort(key=lambda l: l[1])
185     if grid_lines[0][0][0] > grid_lines[1][0][0]:
186         grid_lines = grid_lines[1], grid_lines[0]
187
188     return grid, grid_lines
189
190 def test():
191     import pickle
192     import matplotlib.pyplot as pyplot
193
194     lines = pickle.load(open('lines.pickle'))
195
196     size = (520, 390)
197     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
198     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
199     for l1 in new_lines1:
200         for l2 in new_lines2:
201             p = Point(intersection(l1, l2))
202             p.l1 = l1
203             p.l2 = l2
204             l1.points.append(p)
205             l2.points.append(p)
206
207     points = [l.points for l in new_lines1]
208
209     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
210     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
211     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
212     center = intersection(line1, line2)
213     data = sum(points, [])
214     diag1 = Line(line1)
215     diag1.points = ransac.filter_near(data, diag1, 2)
216     diag2 = Line(line2)
217     diag2.points = ransac.filter_near(data, diag2, 2)
218
219     plot_line_g(diag1, 520)
220     plot_line_g(diag2, 520)
221     pyplot.scatter(*zip(*sum(points, [])))
222     pyplot.scatter([center[0]], [center[1]], color='r')
223     pyplot.xlim(0, 520)
224     pyplot.ylim(0, 390)
225     pyplot.show()
226
227     grids = map(manual.lines, list(gen_corners(diag1, diag2)))
228     plot_grid = lambda g: map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(g, []))
229     map(plot_grid, grids)
230     pyplot.show()
231
232     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
233
234     map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(grid, []))
235     pyplot.scatter(*zip(*sum(points, [])))
236     pyplot.xlim(0, 520)
237     pyplot.ylim(0, 390)
238     pyplot.show()