fix makefile
[imago.git] / src / gridf3.py
index 4f2a1e3..693b8ee 100644 (file)
@@ -9,6 +9,12 @@ from geometry import l2ad
 
 # TODO comments, refactoring, move methods to appropriate modules
 
+class GridFittingFailedError(Exception):
+    pass
+
+class BadGenError(Exception):
+    pass
+
 def plot_line(line, c, size):
     points = linef.line_from_angl_dist(line, size)
     pyplot.plot(*zip(*points), color=c)
@@ -29,12 +35,16 @@ class Diagonal_model:
                 if l1[i] and l2[j]:
                     yield (l1[i], l2[j])
 
+    def remove(self, data):
+        self.data = list(set(self.data) - set(data))
+
     def initial(self):
         try:
-            return self.gen.next()
+            nxt = self.gen.next()
         except StopIteration:
             self.gen = self.initial_g()
-            return self.gen.next()
+            nxt = self.gen.next()
+        return nxt
 
     def get(self, sample):
         if len(sample) == 2:
@@ -42,6 +52,25 @@ class Diagonal_model:
         else:
             return ransac.least_squares(sample)
 
+    def score(self, est, dist):
+        cons = []
+        score = 0
+        a, b, c = est
+        dst = lambda (x, y): abs(a * x + b * y + c) / sqrt(a*a+b*b)
+        l1 = None
+        l2 = None
+        for p in self.data:
+            d = dst(p)
+            if d <= dist:
+                cons.append(p)
+                if p.l1 == l1 or p.l2 == l2:
+                    return float("inf"), []
+                else:
+                    l1, l2 = p.l1, p.l2
+            score += min(d, dist)
+
+        return score, cons
+
 def intersection((a1, b1, c1), (a2, b2, c2)):
     delim = float(a1 * b2 - b1 * a2)
     x = (b1 * c2 - c1 * b2) / delim
@@ -110,7 +139,7 @@ def gen_corners(d1, d2):
             # TODO create an intersection?
         try:
             yield manual.lines(map(lambda p: p.to_tuple(), [c2, c1, c3, c4]))
-        except TypeError:
+        except (TypeError, ZeroDivisionError):
             pass
             # the square was too small to fit 17 lines inside
             # TODO define SquareTooSmallError or something
@@ -142,42 +171,50 @@ def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
 
     points = [l.points for l in new_lines1]
 
-    line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
-    points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
-    line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
-    center = intersection(line1, line2)
-    data = sum(points, [])
-    diag1 = Line(line1)
-    diag1.points = ransac.filter_near(data, diag1, 2)
-    diag2 = Line(line2)
-    diag2.points = ransac.filter_near(data, diag2, 2)
-
-    if show_all:
-        import matplotlib.pyplot as pyplot
-        import Image
-
-        def plot_line_g((a, b, c), max_x):
-            find_y = lambda x: - (c + a * x) / b
-            pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
-
-        fig = pyplot.figure(figsize=(8, 6))
-        plot_line_g(diag1, size[0])
-        plot_line_g(diag2, size[0])
-        pyplot.scatter(*zip(*sum(points, [])))
-        pyplot.scatter([center[0]], [center[1]], color='r')
-        pyplot.xlim(0, size[0])
-        pyplot.ylim(0, size[1])
-        fig.canvas.draw()
-        size_f = fig.canvas.get_width_height()
-        buff = fig.canvas.tostring_rgb()
-        image_p = Image.fromstring('RGB', size_f, buff, 'raw')
-        do_something(image_p, "finding diagonal")
-
-
-    grids = list(gen_corners(diag1, diag2))
-
-    sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
-    
+    for trial in xrange(3):
+        line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
+        points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
+        line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
+        center = intersection(line1, line2)
+        data = sum(points, [])
+        diag1 = Line(line1)
+        diag1.points = ransac.filter_near(data, diag1, 2)
+        diag2 = Line(line2)
+        diag2.points = ransac.filter_near(data, diag2, 2)
+
+        if show_all:
+            import matplotlib.pyplot as pyplot
+            import Image
+
+            def plot_line_g((a, b, c), max_x):
+                find_y = lambda x: - (c + a * x) / b
+                pyplot.plot([0, max_x], [find_y(0), find_y(max_x)], color='b')
+
+            fig = pyplot.figure(figsize=(8, 6))
+            plot_line_g(diag1, size[0])
+            plot_line_g(diag2, size[0])
+            pyplot.scatter(*zip(*sum(points, [])))
+            pyplot.scatter([center[0]], [center[1]], color='r')
+            pyplot.xlim(0, size[0])
+            pyplot.ylim(0, size[1])
+            pyplot.gca().invert_yaxis()
+            fig.canvas.draw()
+            size_f = fig.canvas.get_width_height()
+            buff = fig.canvas.tostring_rgb()
+            image_p = Image.fromstring('RGB', size_f, buff, 'raw')
+            do_something(image_p, "finding diagonal")
+
+
+        grids = list(gen_corners(diag1, diag2))
+        
+        try:
+            sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
+            break
+        except ValueError:
+            pass
+    else:
+        raise GridFittingFailedError
+        
     grid_lines = [[l2ad(l, size) for l in grid[0]], 
                   [l2ad(l, size) for l in grid[1]]]
     grid_lines[0].sort(key=lambda l: l[1])
@@ -187,52 +224,3 @@ def find(lines, size, l1, l2, bounds, hough, show_all, do_something, logger):
 
     return grid, grid_lines
 
-def test():
-    import pickle
-    import matplotlib.pyplot as pyplot
-
-    lines = pickle.load(open('lines.pickle'))
-
-    size = (520, 390)
-    new_lines1 = map(lambda l: Line.from_ad(l, size), lines[0])
-    new_lines2 = map(lambda l: Line.from_ad(l, size), lines[1])
-    for l1 in new_lines1:
-        for l2 in new_lines2:
-            p = Point(intersection(l1, l2))
-            p.l1 = l1
-            p.l2 = l2
-            l1.points.append(p)
-            l2.points.append(p)
-
-    points = [l.points for l in new_lines1]
-
-    line1, cons = ransac.estimate(points, 2, 800, Diagonal_model)
-    points2 = map(lambda l: [(p if not p in cons else None) for p in l], points)
-    line2, cons2 = ransac.estimate(points2, 2, 800, Diagonal_model)
-    center = intersection(line1, line2)
-    data = sum(points, [])
-    diag1 = Line(line1)
-    diag1.points = ransac.filter_near(data, diag1, 2)
-    diag2 = Line(line2)
-    diag2.points = ransac.filter_near(data, diag2, 2)
-
-    plot_line_g(diag1, 520)
-    plot_line_g(diag2, 520)
-    pyplot.scatter(*zip(*sum(points, [])))
-    pyplot.scatter([center[0]], [center[1]], color='r')
-    pyplot.xlim(0, 520)
-    pyplot.ylim(0, 390)
-    pyplot.show()
-
-    grids = map(manual.lines, list(gen_corners(diag1, diag2)))
-    plot_grid = lambda g: map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(g, []))
-    map(plot_grid, grids)
-    pyplot.show()
-
-    sc, grid = min(map(lambda g: (score(sum(g, []), data), g), grids))
-
-    map(lambda l: pyplot.plot(*zip(*l), color='g'), sum(grid, []))
-    pyplot.scatter(*zip(*sum(points, [])))
-    pyplot.xlim(0, 520)
-    pyplot.ylim(0, 390)
-    pyplot.show()