-
Notifications
You must be signed in to change notification settings - Fork 14
/
nricp_landmarks.m
428 lines (365 loc) · 13.8 KB
/
nricp_landmarks.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
function [ vertsTransformed, X ] = nricp_landmarks( Source, Target, Options, ls_source, ls_target)
% nricp performs an adaptive stiffness variant of non rigid ICP.
%
% This function deforms takes a dense set of landmarks points from a template
% template model and finds a deformation which matches a target shape.
% The deformations are encouraged to be natural and smooth by means of a
% stiffness constraint, which is relaxed in increments.
%
% For details on the stiffness constraint and optimization procedure see:
% 'Optimal Step Nonrigid ICP Algorithms for Surface Registration',
% Amberg, Romandhani and Vetter, CVPR, 2007.
%
% Inputs:
% Source: structured object with fields -
% Source.vertices: V x 3 vertices of template model
% Source.faces: F x 3 list of connected vertices.
% Source.normals: (Optional) FV x 3 list of surface normals. Make
% sure to set Options.normals = 1 if using normals.
%
% Target : stuctured object as above for target model.
%
% Options : structured object with fields:
% gamm : real valued, weights differences in the rotational and skew
% part of the deformation against the translational part.
% epsilon : real values, tolerence for change in transformation.
% lambda : If using the bi-directional distance metric this weights
% the contribution of the target -> source term.
% alphaSet : decreasing vector of real-valued stiffness parameters.
% High stiffness parameters force global transformations whereas
% low values allow for local deformations.
% biDirectional : logical, specifies that a bi-directional distance
% is used.
% useNormals : logical, specifies that surface normals are to be used
% to project the source onto the target surface. If this term is
% used then the Source input should contain a normals field.
% plot : logical, specifies that the transformations should be
% plotted.
% rigidInit : logical, specifies that rigid ICP should be performed
% first before allowing non-rigid and non-global deformations.
%
% Outputs:
% vertsTransformed : N X 3 vertices of transformed source mesh,
% X : (4N) X 3 stacked matrix of transformations.
% Set default parameters
if ~isfield(Options, 'gamm')
Options.gamm = 1;
end
if ~isfield(Options, 'epsilon')
Options.epsilon = 1e-4;
end
if ~isfield(Options, 'lambda')
Options.lambda = 1;
end
if ~isfield(Options, 'alphaSet')
Options.alphaSet = linspace(100, 10, 20);
% Options.alphaSet = [50, 20, 5, 2, 0.8, 0.5, 0.35, 0.3, 0.2];
end
if ~isfield(Options, 'biDirectional')
Options.biDirectional = 0;
end
if ~isfield(Options, 'useNormals')
Options.useNormals = 0;
end
if ~isfield(Options, 'plot')
Options.plot = 0;
end
if ~isfield(Options, 'rigidInit')
Options.rigidInit = 1;
end
if ~isfield(Options, 'ignoreBoundary')
Options.ignoreBoundary = 0;
end
if ~isfield(Options, 'normalWeighting')
Options.normalWeighting = 1;
end
if ~isfield(Options, 'landmarks')
Options.landmarks = 0;
end
if ~isfield(Options, 'betaSet')
Options.betaSet = linspace(3, 0, 20);
% Options.betaSet = [5, 2, .5, 0, 0, 0, 0, 0, 0];
end
% Optionally plot source and target surfaces
if Options.plot == 1
clf;
PlotTarget = rmfield(Target, 'normals');
p = patch(PlotTarget, 'facecolor', 'b', 'EdgeColor', 'none', ...
'FaceAlpha', 0.5);
hold on;
PlotSource = rmfield(Source, 'normals');
h = patch(PlotSource, 'facecolor', 'r', 'EdgeColor', 'none', ...
'FaceAlpha', 0.5);
material dull; light; grid on; xlabel('x'); ylabel('y'); zlabel('z');
view([60,30]); axis equal; axis manual;
legend('Target', 'Source', 'Location', 'best')
drawnow;
end
% Get source vertices
vertsSource = Source.vertices;
nVertsSource = size(vertsSource, 1);
% Get target vertices
vertsTarget = Target.vertices;
% Optionally get source / target normals
if Options.normalWeighting == 1
normalsSource = Source.normals;
normalsTarget = Target.normals;
end
% Get subset of target vertices if Options.biDirectional == 1
if Options.biDirectional == 1
samplesTarget = sampleVerts(Target, 15);
nSamplesTarget = size(samplesTarget, 1);
end
% Set matrix G (equation (3) in Amberg et al.)
G = diag([1 1 1 Options.gamm]);
% Set incidence matrix M
A = triangulation2adjacency(Source.faces, Source.vertices);
M = adjacency2incidence(A)';
% Precompute kronecker product of M and G
kron_M_G = kron(M, G);
% Set matrix D (equation (8) in Amberg et al.)
I = (1:nVertsSource)';
J = 4*I;
D = sparse([I;I;I;I],[J-3;J-2;J-1;J],[vertsSource(:);ones(nVertsSource,1)],nVertsSource, 4*nVertsSource);
% Set matrix Dl and Ul
if Options.landmarks == 1
nVertsLs = length(ls_source);
Dl = sparse(nVertsLs, 4*nVertsSource);
for j = 1:nVertsLs
cor = ls_source(j);
Dl(j,(cor*4-3):(cor*4)) = [vertsSource(cor,:) 1];
end
Ul = vertsTarget(ls_target, :);
end
% Set weights vector
wVec = ones(nVertsSource,1);
% Get boundary vertex indices on target surface if required.
if Options.ignoreBoundary == 1
bdr = find_bound(vertsTarget, Target.faces);
end
% Set target points matrix tarU and target weights matrix tarU
if Options.biDirectional == 1
tarU = samplesTarget;
tarW = eye(nSamplesTarget);
end
% Do rigid iterative closest point if Options.rigidInit == 1
if Options.rigidInit == 1
disp('* Performing rigid ICP...');
if Options.ignoreBoundary == 0
bdr = 0;
end
[R, t] = icp(vertsTarget', vertsSource', 50, 'Verbose', true, ...
'EdgeRejection', logical(Options.ignoreBoundary), ...
'Boundary', bdr', 'Matching', 'kDtree');
X = repmat([R'; t'], nVertsSource, 1);
vertsTransformed = D*X;
% Update plot
if Options.plot == 1
set(h, 'Vertices', vertsTransformed);
drawnow;
end
else
% Otherwise initialize transformation matrix X with identity matrices
X = repmat([eye(3); [0 0 0]], nVertsSource, 1);
end
% get number of element in the set of stiffness parameters Options.alphaSet
nAlpha = numel(Options.alphaSet);
% Enter outer loop of the non-rigid iterative closest point algorithm. The
% outer loop iterates over stiffness parameters alpha.
disp('* Performing non-rigid ICP...');
for i = 1:nAlpha
% Update stiffness
alpha = Options.alphaSet(i);
% Update landmark
beta = Options.betaSet(i);
% set oldX to be very different to X so that norm(X - oldX) is large on
% first iteration
oldX = 10*X;
% Enter inner loop. For each stiffness setting alternate between
% updating correspondences and getting optimal transformations X.
% Break the loop when consecutive transformations are similar.
while norm(X - oldX) >= Options.epsilon
% Transform source points by current transformation matrix X
vertsTransformed = D*X;
% Update plot
if Options.plot == 1
set(h, 'Vertices', full(vertsTransformed));
drawnow;
end
% Determine closest points on target U to transformed source points
% pointsTransformed.
targetId = knnsearch(vertsTarget, vertsTransformed);
U = vertsTarget(targetId,:);
% Optionally give zero weightings to transformations associated
% with boundary target vertices.
if Options.ignoreBoundary == 1
tarBoundary = ismember(targetId, bdr);
wVec = ~tarBoundary;
end
% Optionally transform surface normals to compare with target and
% give zero weight if surface and transformed normals do not have
% similar angles.
if Options.normalWeighting == 1
I = (1:nVertsSource)';
J = 4*I;
N = sparse([I;I;I;I],[J-3;J-2;J-1;J],[normalsSource(:);ones(nVertsSource,1)],nVertsSource, 4*nVertsSource);
normalsTransformed = N*X;
corNormalsTarget = normalsTarget(targetId,:);
crossNormals = cross(corNormalsTarget, normalsTransformed);
crossNormalsNorm = sqrt(sum(crossNormals.^2,2));
dotNormals = dot(corNormalsTarget, normalsTransformed, 2);
angle = atan2(crossNormalsNorm, dotNormals);
wVec = wVec .* (angle<pi/4);
end
% Update weight matrix
W = spdiags(wVec, 0, nVertsSource, nVertsSource);
% Get closest points on source tarD to target samples samplesTarget
if Options.biDirectional == 1
transformedId = knnsearch(vertsTransformed, samplesTarget);
tarD = sparse(nSamplesTarget, 4 * nVertsSource);
for j = 1:nSamplesTarget
cor = transformedId(j);
tarD(j,(4 * cor-3):(4 * cor)) = [vertsSource(cor,:) 1];
end
end
% Specify B and C (See equation (12) from paper)
A = [...
alpha .* kron_M_G;
W * D;
];
B = [...
zeros(size(M,1)*size(G,1), 3);
W * U;
];
% Concatentate additional terms if Options.biDirectional == 1.
if Options.biDirectional == 1
A = [...
A;
Options.lambda .* tarW * tarD
];
B = [...
B;
Options.lambda .* tarW * tarU
];
end
% Concatentate landmarks terms if Options.landmarks == 1.
if Options.landmarks == 1
A = [...
A;
beta .* Dl;
];
B = [...
B;
beta .* Ul;
];
end
% Get optimal transformation X and remember old transformation oldX
oldX = X;
X = (A' * A) \ (A' * B);
end
end
% Compute transformed points
vertsTransformed = D*X;
% If Options.useNormals == 1 project along surface normals to target
% surface, otherwise snap to closest points on target.
if Options.useNormals == 1
disp('* Projecting transformed points onto target along surface normals...');
% Get template surface normals
normalsTemplate = Source.normals;
% Transform surface normals with the X matrix
I = (1:nVertsSource)';
J = 4*I;
N = sparse([I;I;I;I],[J-3;J-2;J-1;J],[normalsTemplate(:);ones(nVertsSource,1)],nVertsSource, 4*nVertsSource);
normalsTransformed = N*X;
% Project normals to target surface
vertsTransformed = projectNormals(vertsTransformed, Target, ...
normalsTransformed);
else
% Snap template points to nearest vertices on surface
targetId = knnsearch(vertsTarget, vertsTransformed);
corTargets = vertsTarget(targetId,:);
if Options.ignoreBoundary == 1
tarBoundary = ismember(targetId, bdr);
wVec = ~tarBoundary;
end
vertsTransformed(wVec,:) = corTargets(wVec,:);
end
% Update plot and remove target mesh
if Options.plot == 1
set(h, 'Vertices', vertsTransformed);
drawnow;
pause(2);
delete(p);
end
function [projections] = projectNormals(sourceVertices, Target, normals)
% projectNormals takes a set of vertices and their surface normals and
% projects them to a target surface.
%
% Inputs:
% sourceVertices: N x 3 vertices of source surface.
% Target: Structured object with fields -
% Target.vertices: V x 3 vertices of template model
% Target.faces: D x 3 list of connected vertices.
% normals: N x 3 surface normals of sourceVertices.
% Get number of source vertices
nVerticesSource = size(sourceVertices, 1);
% Pre-allocate space for projections
projections = zeros(nVerticesSource, 3);
% Loop over source vertices projecting onto the target surface
for i=1:nVerticesSource
% Get vertex and normal
vertex = sourceVertices(i,:);
normal = normals(i,:);
% Define line in direction normal that passes through vertex
line = createLine3d(vertex, normal(1), normal(2), normal(3));
% Compute the intersection of the line and the source surface
intersection = intersectLineMesh3d(line, Target.vertices, Target.faces);
% If multiple intersections choose the one closest to the source vertex
if ~isempty(intersection)
[~,I] = min(sqrt(sum((intersection - ...
repmat(vertex,size(intersection,1),1)).^2, 2)));
projections(i,:) = intersection(I,:);
else
% If no intersections just keep the source vertex position
projections(i,:) = vertex;
end
end
function [ samples ] = sampleVerts( Mesh, radius )
% sampleVerts sub samples the vertices of a mesh. Vertices are selected
% so that no other nodes lie within a pre-determined radius.
%
% Inputs:
% Mesh : structured object with fields:
% Mesh.vertices: N x 3 vertices of Mesh.
% Mesh.faces: M x 3 list of connected vertices.
% radius : controls the spacing of the vertices.
samples = [];
vertsLeft = Mesh.vertices;
itt = 1;
while size(vertsLeft, 1) > 0
nVertsLeft = size(vertsLeft, 1);
% pick a sample from remaining points
vertN = randsample(nVertsLeft, 1);
vert = vertsLeft(vertN, :);
% Add it to sample set
samples(itt,:) = vert;
% Remove nearby vertices
idx = rangesearch(vertsLeft, vert, radius);
idRemove = idx{1};
vertsLeft(idRemove, :) = [];
itt = itt + 1;
end
function bound = find_bound(pts, poly)
% From Iterative Closest Point:
% http://www.mathworks.com/matlabcentral/fileexchange/27804-iterative-closest-point
% Boundary point determination. Given a set of 3D points and a
% corresponding triangle representation, returns those point indices that
% define the border/edge of the surface.
% Correcting polygon indices and converting datatype
poly = double(poly);
pts = double(pts);
%Calculating freeboundary points:
TR = triangulation(poly, pts);
FF = freeBoundary(TR);
%Output
bound = FF(:,1);