df83b7f5ad3389116f3576c84fd7a5266eb1284d
[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 def nearest2(lines, point):
31     return min(map(lambda l: dst(point, points_to_line(*l)), lines))
32
33 size = (520, 390)
34
35 def generate_models(sample, middle):
36     sgrid = map(lambda l:linef.line_from_angl_dist(l, size), sample) 
37     lh = (gm.intersection(sgrid[0], middle), gm.intersection(sgrid[1], middle))
38     for f in [0, 1, 2, 3, 5]:
39         grid = gm.fill(sgrid[0], sgrid[1], lh , f)
40         grid = [sgrid[0]] + grid + [sgrid[1]]
41         for s in xrange(17 - f):
42             grid = [gm.expand_left(grid, middle)] + grid
43         yield grid
44         for i in xrange(17 - f):
45             grid = grid[1:]
46             grid.append(gm.expand_right(grid, middle))
47             yield grid
48
49
50 points = pickle.load(open('edges.pickle'))
51
52 lines = pickle.load(open('lines.pickle'))
53
54 r_lines = pickle.load(open('r_lines.pickle'))
55
56 #pyplot.scatter(*zip(*sum(r_lines, [])))
57 #pyplot.show()
58
59 l1, l2 = lines
60
61 lines_general = map(to_general, sum(lines, []))
62 near_points = [p for p in points if nearest(lines_general, p) <= 2]
63 score = lambda grid: len([p for p in points if nearest2(grid, p) <= 2])
64
65 while True:
66     l1s = random.sample(l2, 2)
67     l1s.sort(key=lambda l: l[1])
68     middle = ((0, 195),(520, 195))
69     # TODO! can I assume anything to be perspectively disorted square? No.
70     # TODO! take lower and middle and construct top
71     # TODO iterate that ^^^?
72     
73     sc, grid = max(map(lambda g: (score(g), g), generate_models(l1s, middle)))
74     pyplot.scatter(*zip(*near_points))
75     map(lambda l: pyplot.plot(*zip(*l), color='b'), grid)
76
77     plot_line(l1s[0], 'r')
78     plot_line(l1s[1], 'r')
79     pyplot.xlim(0, 520)
80     pyplot.ylim(0, 390)
81     pyplot.show()
82
83 sys.exit()
84
85
86
87
88 for l in lines[0]:
89     plot_line(l, 'g')
90
91 for l in lines[1]:
92     plot_line(l, 'g')
93
94 pyplot.xlim(0, 520)
95 pyplot.ylim(0, 390)
96 pyplot.show()