89c24a9a2e6f9880338bd0ca6355ab8bd8ba8186
[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     def to_tuple(self):
73         return (self.x, self.y)
74
75 class Line:
76     def __init__(self, (a, b, c)):
77         self.a, self.b, self.c = (a, b, c)
78         self.points = []
79
80     @classmethod
81     def from_ad(cls, (a, d), size):
82         p = linef.line_from_angl_dist((a, d), size)
83         return cls(ransac.points_to_line(*p))
84
85     def __iter__(self):
86         yield self.a
87         yield self.b
88         yield self.c
89
90     def __len__(self):
91         return 3
92
93     def __getitem__(self, key):
94         if key == 0:
95             return self.a
96         elif key == 1:
97             return self.b
98         elif key == 2:
99             return self.c
100
101 def gen_corners(d1, d2):
102     for c1 in d1.points:
103         if c1 in d2.points:
104             continue
105         pass
106         c2 = [p for p in d2.points if p in c1.l1.points][0]
107         c3 = [p for p in d1.points if p in c2.l2.points][0]
108         c4 = [p for p in d2.points if p in c3.l1.points][0]
109         yield map(lambda p: p.to_tuple(), [c1, c2, c3, c4])
110
111 def dst(p, l):
112     (x, y), (a, b, c) = p, ransac.points_to_line(*l)
113     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
114
115 def score(lines, points):
116     score = 0
117     for p in points:
118         s = min(map(lambda l: dst(p, l), lines))
119         s = min(s, 2)
120         score += s
121     return score
122
123
124 def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
125     logger("finding the grid")
126     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
127     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
128     for l1 in new_lines1:
129         for l2 in new_lines2:
130             p = Point(intersection(l1, l2))
131             p.l1 = l1
132             p.l2 = l2
133             l1.points.append(p)
134             l2.points.append(p)
135
136     points = [l.points for l in new_lines1]
137
138     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
139     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
140     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
141     center = intersection(line1, line2)
142     data = sum(points, [])
143     diag1 = Line(line1)
144     diag1.points = ransac.filter_near(data, diag1, 2)
145     diag2 = Line(line2)
146     diag2.points = ransac.filter_near(data, diag2, 2)
147
148     grids = map(manual.lines, list(gen_corners(diag1, diag2)))
149
150     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
151     
152     grid_lines = [[l2ad(l, size) for l in grid[0]], 
153                   [l2ad(l, size) for l in grid[1]]]
154
155     return grid, grid_lines
156
157 def test():
158     import pickle
159     import matplotlib.pyplot as pyplot
160
161     lines = pickle.load(open('lines.pickle'))
162
163     size = (520, 390)
164     new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
165     new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
166     for l1 in new_lines1:
167         for l2 in new_lines2:
168             p = Point(intersection(l1, l2))
169             p.l1 = l1
170             p.l2 = l2
171             l1.points.append(p)
172             l2.points.append(p)
173
174     points = [l.points for l in new_lines1]
175
176     line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
177     points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
178     line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
179     center = intersection(line1, line2)
180     data = sum(points, [])
181     diag1 = Line(line1)
182     diag1.points = ransac.filter_near(data, diag1, 2)
183     diag2 = Line(line2)
184     diag2.points = ransac.filter_near(data, diag2, 2)
185
186     plot_line_g(diag1, 520)
187     plot_line_g(diag2, 520)
188     pyplot.scatter(*zip(*sum(points, [])))
189     pyplot.scatter([center[0]], [center[1]], color='r')
190     pyplot.xlim(0, 520)
191     pyplot.ylim(0, 390)
192     pyplot.show()
193
194     grids = map(manual.lines, list(gen_corners(diag1, diag2)))
195     plot_grid = lambda g: map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(g, []))
196     map(plot_grid, grids)
197     pyplot.show()
198
199     sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
200
201     map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(grid, []))
202     pyplot.scatter(*zip(*sum(points, [])))
203     pyplot.xlim(0, 520)
204     pyplot.ylim(0, 390)
205     pyplot.show()