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