2 from sklearn.neighbors
import NearestNeighbors
6 Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions 8 A: Nxm numpy array of corresponding points 9 B: Nxm numpy array of corresponding points 11 T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B 12 R: mxm rotation matrix 13 t: mx1 translation vector 16 assert A.shape == B.shape
22 centroid_A = np.mean(A, axis=0)
23 centroid_B = np.mean(B, axis=0)
29 U, S, Vt = np.linalg.svd(H)
33 if np.linalg.det(R) < 0:
38 t = centroid_B.T - np.dot(R,centroid_A.T)
50 Find the nearest (Euclidean) neighbor in dst for each point in src 52 src: Nxm array of points 53 dst: Nxm array of points 55 distances: Euclidean distances of the nearest neighbor 56 indices: dst indices of the nearest neighbor 59 assert src.shape == dst.shape
61 neigh = NearestNeighbors(n_neighbors=1)
63 distances, indices = neigh.kneighbors(src, return_distance=
True)
64 return distances.ravel(), indices.ravel()
67 def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001):
69 The Iterative Closest Point method: finds best-fit transform that maps points A on to points B 71 A: Nxm numpy array of source mD points 72 B: Nxm numpy array of destination mD point 73 init_pose: (m+1)x(m+1) homogeneous transformation 74 max_iterations: exit algorithm after max_iterations 75 tolerance: convergence criteria 77 T: final homogeneous transformation that maps A on to B 78 distances: Euclidean distances (errors) of the nearest neighbor 79 i: number of iterations to converge 82 assert A.shape == B.shape
88 src = np.ones((m+1,A.shape[0]))
89 dst = np.ones((m+1,B.shape[0]))
90 src[:m,:] = np.copy(A.T)
91 dst[:m,:] = np.copy(B.T)
94 if init_pose
is not None:
95 src = np.dot(init_pose, src)
99 for i
in range(max_iterations):
110 mean_error = np.mean(distances)
111 if np.abs(prev_error - mean_error) < tolerance:
113 prev_error = mean_error
118 return T, distances, i
def nearest_neighbor(src, dst)
def best_fit_transform(A, B)
def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001)