better grid-fitting
[imago.git] / gridf.py
1 """Imago grid-fitting module"""
2
3 import multiprocessing
4
5 import Image, ImageDraw, ImageFilter
6
7 from geometry import V, projection
8 from manual import lines as g_grid, l2ad
9 from intrsc import intersections_from_angl_dist
10 from linef import line_from_angl_dist
11 import pcf
12
13 class GridFittingFailedError(Exception):
14     pass
15
16 class MyGaussianBlur(ImageFilter.Filter):
17     name = "GaussianBlur"
18
19     def __init__(self, radius=2):
20         self.radius = radius
21     def filter(self, image):
22         return image.gaussian_blur(self.radius)
23
24 def job_br1(args):
25     im_l, v1, v2, h1, h2, x, y, dv, dh, size = args
26     v1 = (v1[0] + x * dv, v1[1] + x)
27     v2 = (v2[0] + y * dv, v2[1] + y)
28     return (distance(im_l, 
29                     get_grid([v1, v2], [h1, h2], size),
30                     size), x, y) 
31
32 def job_br2(args):
33     im_l, v1, v2, h1, h2, x, y, dv, dh, size = args
34     h1 = (h1[0] + x * dh, h1[1] + x)
35     h2 = (h2[0] + y * dh, h2[1] + y)
36     return (distance(im_l, 
37                     get_grid([v1, v2], [h1, h2], size),
38                     size), x, y) 
39
40 def job_4(args):
41     im_l, v1, v2, h1, h2, x, y, w, z, dv, dh, size = args
42     v1 = (v1[0] + x * dv, v1[1] + x)
43     v2 = (v2[0] + y * dv, v2[1] + y)
44     h1 = (h1[0] + w * dh, h1[1] + w)
45     h2 = (h2[0] + z * dh, h2[1] + z)
46     return (distance(im_l, 
47                     get_grid([v1, v2], [h1, h2], size),
48                     size), x, y, w, z) 
49
50 def find(lines, size, l1, l2, bounds, hough, do_something, im_h):
51     l1 = line_from_angl_dist(l1, size)
52     l2 = line_from_angl_dist(l2, size)
53     v1 = V(*l1[0]) - V(*l1[1])
54     v2 = V(*l2[0]) - V(*l2[1])
55     a, b, c, d = [V(*a) for a in bounds]
56     a = projection(a, l1, v1) 
57     b = projection(b, l1, v1) 
58     c = projection(c, l2, v2) 
59     d = projection(d, l2, v2) 
60     
61     v1, v2 = hough.lines_from_list([a, b])
62     h1, h2 = hough.lines_from_list([c, d])
63
64     delta_v = ((l1[1][1] - l1[0][1]) * hough.dt) / l1[1][0]
65     delta_h = ((l2[1][1] - l2[0][1]) * hough.dt) / l2[1][0]
66
67     im_l = Image.new('L', size)
68     dr_l = ImageDraw.Draw(im_l)
69     for line in sum(lines, []):
70         dr_l.line(line_from_angl_dist(line, size), width=1, fill=255)
71
72     im_l = im_l.filter(MyGaussianBlur(radius=5))
73     #GaussianBlur is undocumented class, may not work in future versions of PIL
74     im_l_s = im_l.tostring()
75
76     #let's try the ULTRA bruteforce aproach:
77     pool = multiprocessing.Pool(None)
78
79     #import time
80     #start = time.time()
81
82     k = 30 
83     tasks = [(im_l_s, v1, v2, h1, h2, x, y, w, z, delta_v, delta_h, size) 
84              for x in xrange(-k, k, 2)
85              for y in xrange(-k, k, 2)
86              for z in xrange(-k, k, 2)
87              for w in xrange(-k, k, 2)]
88
89     opt = pool.map(job_4, tasks)
90     _, x_v, y_v, x_h, y_h = max(opt)
91
92     v1 = (v1[0] + x_v * delta_v, v1[1] + x_v)
93     v2 = (v2[0] + y_v * delta_v, v2[1] + y_v)
94     h1 = (h1[0] + x_h * delta_h, h1[1] + x_h)
95     h2 = (h2[0] + y_h * delta_h, h2[1] + y_h)
96
97     k = 5 
98     tasks = [(im_l_s, v1, v2, h1, h2, x, y, w, z, delta_v, delta_h, size) 
99              for x in xrange(-k, k)
100              for y in xrange(-k, k)
101              for z in xrange(-k, k)
102              for w in xrange(-k, k)]
103
104     opt = pool.map(job_4, tasks)
105     _, x_v, y_v, x_h, y_h = max(opt)
106
107     v1 = (v1[0] + x_v * delta_v, v1[1] + x_v)
108     v2 = (v2[0] + y_v * delta_v, v2[1] + y_v)
109     h1 = (h1[0] + x_h * delta_h, h1[1] + x_h)
110     h2 = (h2[0] + y_h * delta_h, h2[1] + y_h)
111
112     grid = get_grid([v1, v2], [h1, h2], size) 
113     grid_lines = [[l2ad(l, size) for l in grid[0]], 
114                   [l2ad(l, size) for l in grid[1]]]
115
116     pool.terminate()
117     pool.join()
118     
119     #print time.time() - start
120     
121 ### Show error surface
122 #
123 #    from gridf_analyzer import error_surface
124 #    error_surface(k, im_l_s, v1_i, v2_i, h1_i, h2_i, 
125 #                  delta_v, delta_h, x_v, y_v, x_h, y_h, size)
126 ###
127
128 ### Show grid over lines
129 #
130 #    im_t = Image.new('RGB', im_l.size, None)
131 #    im_t_l = im_t.load()
132 #    im_l_l = im_l.load()
133 #    for x in xrange(im_t.size[0]):
134 #        for y in xrange(im_t.size[1]):
135 #            im_t_l[x, y] = (im_l_l[x, y], 0, 0)
136 #
137 #    im_t_d = ImageDraw.Draw(im_t)
138 #    for l in grid[0] + grid[1]:
139 #        im_t_d.line(l, width=1, fill=(0, 255, 0))
140 #
141 #    do_something(im_t, "lines and grid")
142 ###
143
144     return grid, grid_lines
145
146 def get_grid(l1, l2, size):
147     c = intersections_from_angl_dist([l1, l2], size, get_all=True)
148     #TODO do something when a corner is outside the image
149     corners = (c[0] + c[1])
150     if len(corners) < 4:
151         print l1, l2, c
152         raise GridFittingFailedError
153     grid = g_grid(corners)
154     return grid
155
156 def line_out(line, size):
157     for p in line:
158         if p[0] < 0 or p[0] > size[0] or p[1] < 0 or p[1] > size[1]:
159             return True
160     else:
161         return False
162
163 def distance(im_l, grid, size):
164     im_g = Image.new('L', size)
165     dr_g = ImageDraw.Draw(im_g)
166     for line in grid[0] + grid[1]:
167         dr_g.line(line, width=1, fill=255)
168 #        if line_out(line, size):
169 #            return 0
170     #im_g = im_g.filter(MyGaussianBlur(radius=3))
171     #GaussianBlur is undocumented class, may not work in future versions of PIL
172     #im_d, distance = combine(im_l, im_g)
173     distance_d = pcf.combine(im_l, im_g.tostring())
174     return distance_d