Subroutinize the main parts of the auto-alignment routine
[stop_motion.git] / perspective.py
index 9128fb7..951d960 100755 (executable)
@@ -2,6 +2,8 @@
 
 import numpy
 import numpy.linalg
+import scipy
+import scipy.ndimage
 
 # call with 2x4 vector (4 points of x, y)
 def calc_basis(p):
@@ -47,6 +49,23 @@ def apply_transform_multi(A, p):
 def apply_transform(A, p):
   return apply_transform_multi(A, p[:, numpy.newaxis])[:, 0]
 
+def remap_image(A, image):
+  ys, xs, cs = image.shape
+  coords = numpy.zeros((2, ys, xs), numpy.double)
+  coords[0, :, :] = numpy.arange(ys, dtype = numpy.double)[:, numpy.newaxis]
+  coords[1, :, :] = numpy.arange(xs, dtype = numpy.double)[numpy.newaxis, :]
+  mapped_coords = apply_transform_multi(
+    A,
+    coords[::-1, :, :].reshape((2, ys * xs))
+  ).reshape(2, ys, xs)[::-1, :, :]
+  return numpy.stack(
+    [
+      scipy.ndimage.map_coordinates(image[:, :, j], mapped_coords)
+      for j in range(cs)
+    ],
+    2
+  )
+
 if __name__ == '__main__':
   x = numpy.array([[11., 52., 23., 74.], [15., 36., 27., 58.]], numpy.double)
   y = numpy.array([[31., 92., 73., 24.], [65., 26., 87., 18.]], numpy.double)