35bbc80c042182d6929b0233c5f9c83934467c98
[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 job(args):
58     X, Y, im_l, a, b, c, d, s, v1, k, hough, size = args
59     return [distance(im_l, 
60                      get_grid(a + X[y] * s * v1, 
61                               b + Y[y] * s * v1, 
62                               c, d, hough, size),
63                      size) for y in range(0,2 * k)]
64     
65 def error_surface(im_l, a, b, c, d, hough, size, v1):
66     import matplotlib.pyplot as plt
67     from matplotlib import cm
68     import multiprocessing
69     import time
70     import sys
71     import pickle
72
73     X = []
74     Y = []
75     Z = []
76     s = 0.001
77     k = 250
78     for i in range(-k, k):
79         X.append(range(-k, k))
80         Y.append(2*k*[i])
81
82     tasks = [(X[x], Y[x], im_l, a, b, c, d, s, v1, k, hough, size) for x in xrange(0, 2 * k)]
83     #everything is passed by value here; can it somehow be passed by reference?
84
85     pool = multiprocessing.Pool(None)
86     
87     start = time.time()
88     Z = pool.map(job, tasks, 1)
89     print time.time() - start
90
91     s_file = open('surface' + str(k), 'w')
92     pickle.dump((X, Y, Z), s_file)
93     s_file.close()
94     plt.imshow(Z, cmap=cm.jet, interpolation='bicubic', 
95                origin='upper', extent=(-k, k, -k, k), aspect='equal')
96     plt.colorbar()
97
98     plt.show()
99
100     sys.exit()
101
102 def find(lines, size, l1, l2, bounds, hough, do_something):
103     a, b, c, d = [V(*a) for a in bounds]
104     l1 = line_from_angl_dist(l1, size)
105     l2 = line_from_angl_dist(l2, size)
106     v1 = V(*l1[0]) - V(*l1[1])
107     v2 = V(*l2[0]) - V(*l2[1])
108     a = projection(a, l1, v1) 
109     b = projection(b, l1, v1) 
110     c = projection(c, l2, v2) 
111     d = projection(d, l2, v2) 
112
113     im_l = Image.new('L', size)
114     dr_l = ImageDraw.Draw(im_l)
115     for line in sum(lines, []):
116         dr_l.line(line_from_angl_dist(line, size), width=1, fill=255)
117     im_l = im_l.filter(MyGaussianBlur(radius=50))
118     #GaussianBlur is undocumented class, may not work in future versions of PIL
119     im_l = im_l.tostring()
120
121     #error_surface(im_l, a, b, c, d, hough, size, v1)
122
123     grid = get_grid(a, b, c, d, hough, size)
124     dist = distance(im_l, grid, size)
125     print dist
126    
127     s = 0.02
128     while True:
129         ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s),  (0, -s)]
130         grids = [(get_grid(a + t[0] * v1, b + t[1] * v1, 
131                            c, d, hough, size), t) for t in ts1]
132         distances = [(distance(im_l, grid, size), 
133                       grid, t) for grid, t in grids]
134         distances.sort(reverse=True)
135         if distances[0][0] > dist:
136             dist = distances[0][0]
137             grid = distances[0][1]
138             t = distances[0][2]
139             a, b = a + t[0] * v1, b + t[1] * v1
140             print dist
141             s *= 0.75
142         else: 
143            break
144
145     print "---"
146
147     s = 0.02
148     while True:
149         ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s),  (0, -s)]
150         grids = [(get_grid(a, b, 
151                            c + t[0] * v2, d + t[1] * v2, hough, size), t) for t in ts1]
152         distances = [(distance(im_l, grid, size), 
153                       grid, t) for grid, t in grids]
154         distances.sort(reverse=True)
155         if distances[0][0] > dist:
156             dist = distances[0][0]
157             grid = distances[0][1]
158             t = distances[0][2]
159             c, d = c + t[0] * v2, d + t[1] * v2
160             print dist
161             s *= 0.75
162         else:
163             break
164
165     grid_lines = [[l2ad(l, size) for l in grid[0]], [l2ad(l, size) for l in grid[1]]]
166     return grid, grid_lines
167
168 def get_grid(a, b, c, d, hough, size):
169     l1 = hough.lines_from_list([a, b])
170     l2 = hough.lines_from_list([c, d])
171     c = intersections_from_angl_dist([l1, l2], size, get_all=True)
172     #TODO do something when a corner is outside the image
173     corners = (c[0] + c[1])
174     if len(corners) < 4:
175         print l1, l2, c
176         raise GridFittingFailedError
177     grid = g_grid(corners)
178     return grid
179
180 def distance(im_l, grid, size):
181     im_g = Image.new('L', size)
182     dr_g = ImageDraw.Draw(im_g)
183     for line in grid[0] + grid[1]:
184         dr_g.line(line, width=1, fill=255)
185     #im_g = im_g.filter(MyGaussianBlur(radius=3))
186     #GaussianBlur is undocumented class, may not work in future versions of PIL
187     #im_d, distance = combine(im_l, im_g)
188     distance = pcf.combine(im_l, im_g.tostring())
189     return distance
190
191 def combine(bg, fg):
192     bg_l = bg.load()
193     fg_l = fg.load()
194     #res = Image.new('L', fg.size)
195     #res_l = res.load()
196
197     score = 0
198     area = 0
199
200     for x in xrange(fg.size[0]):
201         for y in xrange(fg.size[1]):
202             if fg_l[x, y]:
203                 #res_l[x, y] = bg_l[x, y] * fg_l[x, y]
204                 score +=  bg_l[x, y]
205                 area += 1
206
207     #return res, float(score)/area
208     return None, float(score)/area