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