error surface plots
[imago.git] / gridf.py
1 import Image, ImageDraw, ImageFilter
2
3 from manual import lines as g_grid, l2ad, intersection, line as g_line
4 from intrsc import intersections_from_angl_dist
5 from linef import line_from_angl_dist
6
7 class GridFittingFailedError(Exception):
8     pass
9
10 class MyGaussianBlur(ImageFilter.Filter):
11     name = "GaussianBlur"
12
13     def __init__(self, radius=2):
14         self.radius = radius
15     def filter(self, image):
16         return image.gaussian_blur(self.radius)
17
18 class V():
19     def __init__(self, x, y):
20         self.x = x
21         self.y = y
22     
23     def __add__(self, other):
24         return V(self.x + other.x, self.y + other.y)
25
26     def __sub__(self, other):
27         return V(self.x - other.x, self.y - other.y)
28
29     def __rmul__(self, other):
30         return V(other * self.x, other * self.y)
31
32     def t(self):
33         return (self.x, self.y)
34
35     def normal(self):
36         return V(-self.y, self.x)
37
38 def projection(point, line, vector):
39     n = vector.normal()
40     l2 = g_line(point.t(), (point + n).t())
41     return V(*intersection(l2, g_line(*line)))
42     
43 def error_surface(lines, a, b, c, d, hough, size, v1):
44     import matplotlib.pyplot as plt
45     from matplotlib import cm
46     import time
47     import pickle
48     X = []
49     Y = []
50     Z = []
51     s = 0.001
52     k = 5
53     for i in range(-k, k):
54         X.append(range(-k, k))
55         Y.append(2*k*[i])
56         
57     start = time.clock()
58     for x in range(0, 2*k):
59         try:
60             Z.append([distance(lines, get_grid(a + X[x][y] * s * v1, b + Y[x][y] * s * v1, 
61                                            c, d, hough, size),
62                               size) for y in range(0, 2* k)])
63         except Exception:
64             Z.append(Z[-1])
65         o = ((time.clock() - start) * (2 * k - (x + 1))) / (60 * (x + 1))
66         print x + 1, "{0} h {1:2.2f} m".format(int(o) / 60, o % 60)
67     s_file = open('surface' + str(k), 'w')
68     pickle.dump((X, Y, Z), s_file)
69     s_file.close()
70     plt.imshow(Z, cmap=cm.gnuplot2, interpolation='bicubic', 
71                origin='upper', extent=(-k, k, -k, k), aspect='equal')
72     plt.colorbar()
73
74     plt.show()
75
76 def find(lines, size, l1, l2, bounds, hough, do_something):
77     a, b, c, d = [V(*a) for a in bounds]
78     l1 = line_from_angl_dist(l1, size)
79     l2 = line_from_angl_dist(l2, size)
80     v1 = V(*l1[0]) - V(*l1[1])
81     v2 = V(*l2[0]) - V(*l2[1])
82     a = projection(a, l1, v1) 
83     b = projection(b, l1, v1) 
84     c = projection(c, l2, v2) 
85     d = projection(d, l2, v2) 
86     grid = get_grid(a, b, c, d, hough, size)
87     dist = distance(lines, grid, size)
88     print dist
89
90     #error_surface(lines, a, b, c, d, hough, size, v1)
91     
92     s = 0.02
93     while True:
94         ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s),  (0, -s)]
95         grids = [(get_grid(a + t[0] * v1, b + t[1] * v1, 
96                            c, d, hough, size), t) for t in ts1]
97         distances = [(distance(lines, grid, size), 
98                       grid, t) for grid, t in grids]
99         distances.sort(reverse=True)
100         if distances[0][0] > dist:
101             dist = distances[0][0]
102             grid = distances[0][1]
103             t = distances[0][2]
104             a, b = a + t[0] * v1, b + t[1] * v1
105             print dist
106             s *= 0.75
107         else: 
108            break
109
110     print "---"
111
112     s = 0.02
113     while True:
114         ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s),  (0, -s)]
115         grids = [(get_grid(a, b, 
116                            c + t[0] * v2, d + t[1] * v2, hough, size), t) for t in ts1]
117         distances = [(distance(lines, grid, size), 
118                       grid, t) for grid, t in grids]
119         distances.sort(reverse=True)
120         if distances[0][0] > dist:
121             dist = distances[0][0]
122             grid = distances[0][1]
123             t = distances[0][2]
124             c, d = c + t[0] * v2, d + t[1] * v2
125             print dist
126             s *= 0.75
127         else:
128             break
129
130     grid_lines = [[l2ad(l, size) for l in grid[0]], [l2ad(l, size) for l in grid[1]]]
131     return grid, grid_lines
132
133 def get_grid(a, b, c, d, hough, size):
134     l1 = hough.lines_from_list([a.t(), b.t()])
135     l2 = hough.lines_from_list([c.t(), d.t()])
136     c = intersections_from_angl_dist([l1, l2], size, get_all=True)
137     #TODO do something when a corner is outside the image
138     corners = (c[0] + c[1])
139     if len(corners) < 4:
140         print l1, l2, c
141         raise GridFittingFailedError
142     grid = g_grid(corners)
143     return grid
144
145 def distance(lines, grid, size):
146     im_l = Image.new('L', size)
147     dr_l = ImageDraw.Draw(im_l)
148     for line in sum(lines, []):
149         dr_l.line(line_from_angl_dist(line, size), width=1, fill=255)
150     im_l = im_l.filter(MyGaussianBlur(radius=3))
151     #GaussianBlur is undocumented class, may not work in future versions of PIL
152     im_g = Image.new('L', size)
153     dr_g = ImageDraw.Draw(im_g)
154     for line in grid[0] + grid[1]:
155         dr_g.line(line, width=1, fill=255)
156     #im_g = im_g.filter(MyGaussianBlur(radius=3))
157     im_d, distance = combine(im_l, im_g)
158     return distance
159
160 def combine(bg, fg):
161     bg_l = bg.load()
162     fg_l = fg.load()
163     #res = Image.new('L', fg.size)
164     #res_l = res.load()
165
166     score = 0
167     area = 0
168
169     for x in xrange(fg.size[0]):
170         for y in xrange(fg.size[1]):
171             if fg_l[x, y]:
172                 #res_l[x, y] = bg_l[x, y] * fg_l[x, y]
173                 score +=  bg_l[x, y]
174                 area += 1
175
176     #return res, float(score)/area
177     return None, float(score)/area