gridf3
[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):
13     points = linef.line_from_angl_dist(line, (520, 390))
14     pyplot.plot(*zip(*points), color=c)
15
16 def plot_line_g((a, b, c), max_x):
17     find_y = lambda x: - (c + a * x) / b
18     pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
19
20 class Diagonal_model:
21     def __init__(self, data):
22         self.data = [p for p in sum(data, []) if p]
23         self.lines = data
24         self.gen = self.initial_g()
25
26     def initial_g(self):
27         l1, l2 = random.sample(self.lines, 2)
28         for i in xrange(len(l1)):
29             for j in xrange(len(l2)):
30                 if i == j:
31                     continue
32                 if l1[i] and l2[j]:
33                     yield (l1[i], l2[j])
34
35     def initial(self):
36         try:
37             return self.gen.next()
38         except StopIteration:
39             self.gen = self.initial_g()
40             return self.gen.next()
41
42     def get(self, sample):
43         if len(sample) == 2:
44             return ransac.points_to_line(*sample)
45         else:
46             return ransac.least_squares(sample)
47
48 def intersection((a1, b1, c1), (a2, b2, c2)):
49     delim = float(a1 * b2 - b1 * a2)
50     x = (b1 * c2 - c1 * b2) / delim
51     y = (c1 * a2 - a1 * c2) / delim
52     return x, y
53
54 class Point:
55     def __init__(self, (x, y)):
56         self.x = x
57         self.y = y
58
59     def __getitem__(self, key):
60         if key == 0:
61             return self.x
62         elif key == 1:
63             return self.y
64
65     def __iter__(self):
66         yield self.x
67         yield self.y
68
69     def __len__(self):
70         return 2
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         c2 = [p for p in d2.points if p in c1.l1.points][0]
104         c3 = [p for p in d1.points if p in c2.l2.points][0]
105         c4 = [p for p in d2.points if p in c3.l1.points][0]
106         yield [c1, c2, c3, c4]
107
108 def dst(p, l):
109     (x, y), (a, b, c) = p, ransac.points_to_line(*l)
110     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
111
112 def score(lines, points):
113     score = 0
114     for p in points:
115         s = min(map(lambda l: dst(p, l), lines))
116         s = min(s, 2)
117         score += s
118     print score
119     return score
120
121
122 def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
123     logger("finding the grid")
124     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
125     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
126     for l1 in new_lines1:
127         for l2 in new_lines2:
128             p = Point(intersection(l1, l2))
129             p.l1 = l1
130             p.l2 = l2
131             l1.points.append(p)
132             l2.points.append(p)
133
134     points = [l.points for l in new_lines1]
135
136     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
137     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
138     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
139     center = intersection(line1, line2)
140     data = sum(points, [])
141     diag1 = Line(line1)
142     diag1.points = ransac.filter_near(data, diag1, 2)
143     diag2 = Line(line2)
144     diag2.points = ransac.filter_near(data, diag2, 2)
145
146     grids = map(manual.lines, list(gen_corners(diag1, diag2)))
147
148     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
149     
150     grid_lines = [[l2ad(l, size) for l in grid[0]], 
151                   [l2ad(l, size) for l in grid[1]]]
152
153     return grid, grid_lines
154
155 def test():
156     import pickle
157     import matplotlib.pyplot as pyplot
158
159     lines = pickle.load(open('lines.pickle'))
160
161     size = (520, 390)
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     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
175     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
176     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
177     center = intersection(line1, line2)
178     data = sum(points, [])
179     diag1 = Line(line1)
180     diag1.points = ransac.filter_near(data, diag1, 2)
181     diag2 = Line(line2)
182     diag2.points = ransac.filter_near(data, diag2, 2)
183
184     plot_line_g(diag1, 520)
185     plot_line_g(diag2, 520)
186     pyplot.scatter(*zip(*sum(points, [])))
187     pyplot.scatter([center[0]], [center[1]], color='r')
188     pyplot.xlim(0, 520)
189     pyplot.ylim(0, 390)
190     pyplot.show()
191
192     grids = map(manual.lines, list(gen_corners(diag1, diag2)))
193     plot_grid = lambda g: map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(g, []))
194     map(plot_grid, grids)
195     pyplot.show()
196
197     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
198
199     map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(grid, []))
200     pyplot.scatter(*zip(*sum(points, [])))
201     pyplot.xlim(0, 520)
202     pyplot.ylim(0, 390)
203     pyplot.show()