preliminary work on new grid-finding
[imago.git] / ransac_grid.py
1 import pickle
2 import matplotlib.pyplot as pyplot
3 from math import sqrt
4 import random
5 import sys
6
7 import src.linef as linef
8 import src.gridf as gridf
9 from src.manual import lines as g_grid
10
11 import new_geometry as gm
12
13 def plot_line(line, c):
14     points = linef.line_from_angl_dist(line, (520, 390))
15     pyplot.plot(*zip(*points), color=c)
16
17 def dst((x, y), (a, b, c)):
18     return abs(a * x + b * y + c) / sqrt(a*a+b*b)
19
20 def points_to_line((x1, y1), (x2, y2)):
21     return (y2 - y1, x1 - x2, x2 * y1 - x1 * y2)
22
23 def to_general(line):
24     points = linef.line_from_angl_dist(line, (520, 390))
25     return points_to_line(*points)
26
27 def nearest(lines, point):
28     return min(map(lambda l: dst(point, l), lines))
29
30 size = (520, 390)
31
32 points = pickle.load(open('edges.pickle'))
33
34 lines = pickle.load(open('lines.pickle'))
35
36 r_lines = pickle.load(open('r_lines.pickle'))
37
38 #pyplot.scatter(*zip(*sum(r_lines, [])))
39 #pyplot.show()
40
41 l1, l2 = lines
42
43 while True:
44     l1s = random.sample(l2, 2)
45     l1s.sort(key=lambda l: l[1])
46     corners = map(lambda l:linef.line_from_angl_dist(l, size), l1s) 
47     middle = ((0, 195),(520, 195))
48     # TODO! can I assume anything to be perspectively disorted square?
49     # TODO! take lower and middle and construct top
50     lh = (gm.intersection(corners[0], middle), gm.intersection(corners[1], middle))
51     grid = gm.fill(corners[0], corners[1], lh , 3)
52     grid = [corners[0]] + grid + [corners[1]]
53     grid.append(gm.expand(grid[-2], grid[-1], ((gm.intersection(middle, grid[-2]),
54                                          (gm.intersection(middle, grid[-1]))))))
55     grid.append(gm.expand(grid[-2], grid[-1], ((gm.intersection(middle, grid[-2]),
56                                          (gm.intersection(middle, grid[-1]))))))
57     map(lambda l: pyplot.plot(*zip(*l), color='b'), grid)
58
59     plot_line(l1s[0], 'g')
60     plot_line(l1s[1], 'r')
61     
62     pyplot.xlim(0, 520)
63     pyplot.ylim(0, 390)
64     pyplot.show()
65
66 sys.exit()
67
68 lines_general = map(to_general, sum(lines, []))
69
70 near_points = [p for p in points if nearest(lines_general, p) <= 2]
71
72 pyplot.scatter(*zip(*near_points))
73
74
75 for l in lines[0]:
76     plot_line(l, 'g')
77
78 for l in lines[1]:
79     plot_line(l, 'g')
80
81 pyplot.xlim(0, 520)
82 pyplot.ylim(0, 390)
83 pyplot.show()