Skip to content

Instantly share code, notes, and snippets.

@rnbguy
Forked from CarloNicolini/ralign
Created February 14, 2018 14:43
Show Gist options
  • Save rnbguy/21f94a96a2e4436fc2d0bc7e627f976b to your computer and use it in GitHub Desktop.
Save rnbguy/21f94a96a2e4436fc2d0bc7e627f976b to your computer and use it in GitHub Desktop.
Umeyama algorithm for absolute orientation problem in Python
import numpy as np
"""
RALIGN - Rigid alignment of two sets of points in k-dimensional
Euclidean space. Given two sets of points in
correspondence, this function computes the scaling,
rotation, and translation that define the transform TR
that minimizes the sum of squared errors between TR(X)
and its corresponding points in Y. This routine takes
O(n k^3)-time.
Inputs:
X - a k x n matrix whose columns are points
Y - a k x n matrix whose columns are points that correspond to
the points in X
Outputs:
c, R, t - the scaling, rotation matrix, and translation vector
defining the linear map TR as
TR(x) = c * R * x + t
such that the average norm of TR(X(:, i)) - Y(:, i)
is minimized.
"""
"""
Copyright: Carlo Nicolini, 2013
Code adapted from the Mark Paskin Matlab version
from http://openslam.informatik.uni-freiburg.de/data/svn/tjtf/trunk/matlab/ralign.m
"""
def ralign(X, Y):
m, n = X.shape
mx = X.mean(1)
my = Y.mean(1)
Xc = X - mx[..., None]
Yc = Y - my[..., None]
sx = Xc.var(1).sum()
sy = Yc.var(1).sum()
Sxy = np.dot(Yc, Xc.T) / n
S = np.ones(m)
if np.linalg.det(Sxy) < 0:
S[m - 1] = -1
U, D, V = np.linalg.svd(Sxy)
r = np.linalg.matrix_rank(Sxy)
if r >= (m - 1):
if r == m - 1:
if np.linalg.det(U) * np.linalg.det(V) > 0:
R = np.dot(U, V)
else:
s_ = S[m - 1]
S[m - 1] = -1
R = np.dot(U, np.dot(np.diag(S), V))
S[m - 1] = s_
else:
R = np.dot(U, np.dot(np.diag(S), V))
else:
return (None, None, None, None)
DS = np.dot(D, S)
c = DS / sx
t = my - c * np.dot(R, mx)
e = sy - DS**2 / sx
return R, c, t, e
# Run an example test
# We have 3 points in 3D. Every point is a column vector of this matrix A
A = np.array([[0.57215, 0.37512, 0.37551],
[0.23318, 0.86846, 0.98642],
[0.79969, 0.96778, 0.27493]])
# Deep copy A to get B
B = A.copy()
# and sum a translation on z axis (3rd row) of 10 units
B[2, :] = B[2, :] + 10
# Reconstruct the transformation with ralign.ralign
R, c, t, e = ralign(A, B)
print("Rotation matrix=", R,
"Scaling coefficient=", c,
"Translation vector=", t,
sep="\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment