1 import Image, ImageDraw, ImageFilter
3 from manual import lines as g_grid, l2ad
4 from intrsc import intersections_from_angl_dist
5 from linef import line_from_angl_dist
7 class GridFittingFailedError(Exception):
10 class MyGaussianBlur(ImageFilter.Filter):
13 def __init__(self, radius=2):
15 def filter(self, image):
16 return image.gaussian_blur(self.radius)
19 def __init__(self, x, y):
23 def __add__(self, other):
24 return V(self.x + other.x, self.y + other.y)
26 def __sub__(self, other):
27 return V(self.x - other.x, self.y - other.y)
29 def __rmul__(self, other):
30 return V(other * self.x, other * self.y)
33 return (self.x, self.y)
35 def find(lines, size, l1, l2, bounds, hough, do_something):
36 a, b, c, d = [V(*a) for a in bounds]
37 l1 = line_from_angl_dist(l1, size)
38 l2 = line_from_angl_dist(l2, size)
39 v1 = V(*l1[0]) - V(*l1[1])
40 v2 = V(*l2[0]) - V(*l2[1])
41 grid = get_grid(a, b, c, d, hough, size)
42 dist = distance(lines, grid, size)
47 ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s), (0, -s)]
48 grids = [(get_grid(a + t[0] * v1, b + t[1] * v1,
49 c, d, hough, size), t) for t in ts1]
50 distances = [(distance(lines, grid, size),
51 grid, t) for grid, t in grids]
52 distances.sort(reverse=True)
53 if distances[0][0] > dist:
54 dist = distances[0][0]
55 grid = distances[0][1]
57 a, b = a + t[0] * v1, b + t[1] * v1
67 ts1 = [(s, 0), (-s, 0), (s, s), (-s, -s), (-s, s), (s, -s), (0, s), (0, -s)]
68 grids = [(get_grid(a, b,
69 c + t[0] * v2, d + t[1] * v2, hough, size), t) for t in ts1]
70 distances = [(distance(lines, grid, size),
71 grid, t) for grid, t in grids]
72 distances.sort(reverse=True)
73 if distances[0][0] > dist:
74 dist = distances[0][0]
75 grid = distances[0][1]
77 c, d = c + t[0] * v2, d + t[1] * v2
83 grid_lines = [[l2ad(l, size) for l in grid[0]], [l2ad(l, size) for l in grid[1]]]
84 return grid, grid_lines
86 def get_grid(a, b, c, d, hough, size):
87 l1 = hough.lines_from_list([a.t(), b.t()])
88 l2 = hough.lines_from_list([c.t(), d.t()])
89 c = intersections_from_angl_dist([l1, l2], size, get_all=True)
90 corners = (c[0] + c[1])
93 raise GridFittingFailedError
94 grid = g_grid(corners)
97 def distance(lines, grid, size):
98 im_l = Image.new('L', size)
99 dr_l = ImageDraw.Draw(im_l)
100 for line in sum(lines, []):
101 dr_l.line(line_from_angl_dist(line, size), width=1, fill=255)
102 im_l = im_l.filter(MyGaussianBlur(radius=3))
103 # GaussianBlur is undocumented class, may not work in future versions of PIL
104 im_g = Image.new('L', size)
105 dr_g = ImageDraw.Draw(im_g)
106 for line in grid[0] + grid[1]:
107 dr_g.line(line, width=1, fill=255)
108 im_d, distance = combine(im_l, im_g)
114 res = Image.new('L', fg.size)
120 for x in xrange(fg.size[0]):
121 for y in xrange(fg.size[1]):
123 res_l[x, y] = bg_l[x, y]
127 return res, float(score)/area