Debian Codegraph @

conversion/ana2mnc/doc/spm_realign.m

raw
1 function spm_realign(P,flags)
2 % Estimation of within modality rigid body movement parameters
3 % FORMAT spm_realign(P,flags)
4 %
5 % P - matrix of filenames {one string per row}
6 % All operations are performed relative to the first image.
7 % ie. Coregistration is to the first image, and resampling
8 % of images is into the space of the first image.
9 % For multiple sessions, P should be a cell array, where each
10 % cell should be a matrix of filenames.
11 %
12 % flags - a structure containing various options. The fields are:
13 % quality - Quality versus speed trade-off. Highest quality
14 % (1) gives most precise results, whereas lower
15 % qualities gives faster realignment.
16 % The idea is that some voxels contribute little to
17 % the estimation of the realignment parameters.
18 % This parameter is involved in selecting the number
19 % of voxels that are used.
20 %
21 % fwhm - The FWHM of the Gaussian smoothing kernel (mm)
22 % applied to the images before estimating the
23 % realignment parameters.
24 %
25 % sep - the default separation (mm) to sample the images.
26 %
27 % rtm - Register to mean. If field exists then a two pass
28 % procedure is to be used in order to register the
29 % images to the mean of the images after the first
30 % realignment.
31 %
32 % PW - a filename of a weighting image (reciprocal of
33 % standard deviation). If field does not exist, then
34 % no weighting is done.
35 %
36 % hold - hold for interpolation (see spm_slice_vol and
37 % spm_sample_vol).
38 %
39 %__________________________________________________________________________
40 %
41 % Inputs
42 % A series of *.img conforming to SPM data format (see 'Data Format').
43 %
44 % Outputs
45 % The parameter estimation part writes out ".mat" files for each of the
46 % input images. The details of the transformation are displayed in the
47 % results window as plots of translation and rotation.
48 % A set of realignment parameters are saved for each session, named:
49 % realignment_params_*.txt.
50 %__________________________________________________________________________
51 %
52 % The `.mat' files.
53 %
54 % This simply contains a 4x4 affine transformation matrix in a variable `M'.
55 % These files are normally generated by the `realignment' and
56 % `coregistration' modules. What these matrixes contain is a mapping from
57 % the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate
58 % (1,1,1)), to coordinates in millimeters (x1,y1,z1). By default, the
59 % the new coordinate system is derived from the `origin' and `vox' fields
60 % of the image header.
61 %
62 % x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)
63 % y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)
64 % z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)
65 %
66 % Assuming that image1 has a transformation matrix M1, and image2 has a
67 % transformation matrix M2, the mapping from image1 to image2 is: M2\M1
68 % (ie. from the coordinate system of image1 into millimeters, followed
69 % by a mapping from millimeters into the space of image2).
70 %
71 % These `.mat' files allow several realignment or coregistration steps to be
72 % combined into a single operation (without the necessity of resampling the
73 % images several times). The `.mat' files are also used by the spatial
74 % normalisation module.
75 %__________________________________________________________________________
76 % Ref:
77 % Friston KJ, Ashburner J, Frith CD, Poline J-B, Heather JD & Frackowiak
78 % RSJ (1995) Spatial registration and normalization of images Hum. Brain
79 % Map. 2:165-189
80 %__________________________________________________________________________
81 % @(#)spm_realign.m 2.27 John Ashburner 99/10/26
82
83 if nargin==0, spm_realign_ui; return; end;
84
85 def_flags = struct('quality',1,'fwhm',6,'sep',4.5,'hold',-8);
86 if nargin < 2,
87 flags = def_flags;
88 else,
89 fnms = fieldnames(def_flags);
90 for i=1:length(fnms),
91 if ~isfield(flags,fnms{i}),
92 flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
93 end;
94 end;
95 end;
96
97 linfun = inline('fprintf('' %-60s%s'', x,sprintf(''\b'')*ones(1,60))');
98
99 if isempty(P), warning('Nothing to do'); return; end;
100 if ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end;
101 P = spm_vol(P);
102 if isfield(flags,'PW'), flags.PW = spm_vol(flags.PW); end;
103
104 if length(P)==1,
105 linfun('Registering images..');
106 P{1} = realign_series(P{1},flags);
107 save_parameters(P{1});
108 else,
109 linfun('Registering together the first image of each session..');
110 Ptmp = P{1}(1);
111 for s=2:prod(size(P)),
112 Ptmp = [Ptmp ; P{s}(1)];
113 end;
114 Ptmp = realign_series(Ptmp,flags);
115 for s=1:prod(size(P)),
116 M = Ptmp(s).mat*inv(P{s}(1).mat);
117 for i=1:prod(size(P{s})),
118 P{s}(i).mat = M*P{s}(i).mat;
119 end;
120 end;
121
122 for s=1:prod(size(P)),
123 linfun(['Registering together images from session ' num2str(s) '..']);
124 P{s} = realign_series(P{s},flags);
125 save_parameters(P{s});
126 end;
127 end;
128
129 % Save Realignment Parameters
130 %---------------------------------------------------------------------------
131 linfun('Saving parameters..');
132 for s=1:prod(size(P)),
133 for i=1:prod(size(P{s})),
134 spm_get_space(P{s}(i).fname, P{s}(i).mat);
135 end;
136 end;
137 plot_parameters(P);
138
139 return;
140 %_______________________________________________________________________
141
142 %_______________________________________________________________________
143 function P = realign_series(P,flags)
144 % Realign a time series of 3D images to the first of the series.
145 % FORMAT P = realign_series(P,flags)
146 % P - a vector of volumes (see spm_vol)
147 %-----------------------------------------------------------------------
148 % P(i).mat is modified to reflect the modified position of the image i.
149 % The scaling (and offset) parameters are also set to contain the
150 % optimum scaling required to match the images.
151 %_______________________________________________________________________
152
153 if prod(size(P))<2, return; end;
154
155 lkp = [1 2 3 4 5 6];
156 if P(1).dim(3) < 3, lkp = [1 2 6]; end;
157
158 % Points to sample in reference image
159 %-----------------------------------------------------------------------
160 skip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
161 d = P(1).dim(1:3);
162 [x1,x2,x3]=ndgrid(1:skip(1):d(1),1:skip(2):d(2),1:skip(3):d(3));
163 x1 = x1(:);
164 x2 = x2(:);
165 x3 = x3(:);
166
167
168 % Possibly mask an area of the sample volume.
169 %-----------------------------------------------------------------------
170 if isfield(flags,'PW'),
171 [y1,y2,y3]=coords([0 0 0 0 0 0],P(1).mat,flags.PW.mat,x1,x2,x3);
172 wt = spm_sample_vol(flags.PW,y1,y2,y3,1);
173 msk = find(wt>0.01);
174 x1 = x1(msk);
175 x2 = x2(msk);
176 x3 = x3(msk);
177 wt = wt(msk);
178 else,
179 wt = [];
180 end;
181 n = prod(size(x1));
182
183
184 % Compute rate of change of chi2 w.r.t changes in parameters (matrix A)
185 %-----------------------------------------------------------------------
186 V = smooth_vol(P(1),flags.fwhm);
187 [G,dG1,dG2,dG3] = spm_sample_vol(V,x1,x2,x3,flags.hold);
188 clear V
189 A0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,wt,lkp);
190
191 b = G;
192 if ~isempty(wt), b = b.*wt; end;
193
194 %-----------------------------------------------------------------------
195 if prod(size(P)) > 2,
196 % Remove voxels that contribute very little to the final estimate.
197 % Simulated annealing or something similar could be used to
198 % eliminate a better choice of voxels - but this way will do for
199 % now. It basically involves removing the voxels that contribute
200 % least to the determinant of the inverse covariance matrix.
201
202 spm_chi2_plot('Init','Eliminating Unimportant Voxels',...
203 'Fractional loss of quality','Iteration');
204 Alpha = spm_atranspa([A0 b]);
205 det0 = det(Alpha);
206 det1 = det0;
207 spm_chi2_plot('Set',det1/det0);
208 while det1/det0 > flags.quality,
209 dets = zeros(size(A0,1),1);
210 for i=1:size(A0,1),
211 dets(i) = det(Alpha - spm_atranspa([A0(i,:) b(i)]));
212 end;
213 [junk,msk] = sort(det1-dets);
214 msk = msk(1:round(length(dets)/10));
215 A0(msk,:) = []; b(msk,:) = []; G(msk,:) = [];
216 x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = [];
217 dG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = [];
218 if ~isempty(wt), wt(msk,:) = []; end;
219 Alpha = spm_atranspa([A0 b]);
220 det1 = det(Alpha);
221 spm_chi2_plot('Set',det1/det0);
222 end;
223 spm_chi2_plot('Clear');
224 end;
225 %-----------------------------------------------------------------------
226
227
228 if isfield(flags,'rtm'),
229 count = ones(size(b));
230 ave = G;
231 grad1 = dG1;
232 grad2 = dG2;
233 grad3 = dG3;
234 end;
235
236 spm_progress_bar('Init',length(P)-1,'Registering Images');
237 % Loop over images
238 %-----------------------------------------------------------------------
239 for i=2:length(P),
240 V=smooth_vol(P(i),flags.fwhm);
241 ss = Inf;
242 countdown = -1;
243 Hold = 1; % Begin with bi-linear interpolation.
244 for iter=1:64,
245 [y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,P(i).mat,x1,x2,x3);
246 msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));
247 if length(msk)<32, error_message(P(i)); end;
248
249 F = spm_sample_vol(V, y1(msk),y2(msk),y3(msk),Hold);
250 if ~isempty(wt), F = F.*wt(msk); end;
251
252 A = [A0(msk,:) F];
253 Alpha = spm_atranspa(A);
254 Beta = A'*b(msk);
255 soln = Alpha\Beta;
256
257 p = [0 0 0 0 0 0 1 1 1 0 0 0];
258 p(lkp) = soln(1:(end-1));
259 P(i).mat = inv(spm_matrix(p))*P(i).mat;
260
261 pss = ss;
262 ss = sum((F*soln(end)-b(msk)).^2)/length(msk);
263 if (pss-ss)/pss < 1e-8 & countdown == -1, % Stopped converging.
264 % Switch to a better (slower) interpolation
265 % and do two final iterations
266 Hold = flags.hold;
267 countdown = 2;
268 end;
269 if countdown ~= -1,
270 if countdown==0, break; end;
271 countdown = countdown -1;
272 end;
273 end;
274
275 if isfield(flags,'rtm'),
276 % Generate mean and derivatives of mean
277 tiny = 5e-2; % From spm_vol_utils.c
278 msk = find((y1>=(1-tiny) & y1<=(d(1)+tiny) &...
279 y2>=(1-tiny) & y2<=(d(2)+tiny) &...
280 y3>=(1-tiny) & y3<=(d(3)+tiny)));
281 count(msk) = count(msk) + 1;
282 [G,dG1,dG2,dG3] = spm_sample_vol(V,y1(msk),y2(msk),y3(msk),flags.hold);
283 ave(msk) = ave(msk) + G.*soln(end);
284 grad1(msk) = grad1(msk) + dG1.*soln(end);
285 grad2(msk) = grad2(msk) + dG2.*soln(end);
286 grad3(msk) = grad3(msk) + dG3.*soln(end);
287 end;
288 spm_progress_bar('Set',i-1);
289 end;
290 spm_progress_bar('Clear');
291
292 if ~isfield(flags,'rtm'), return; end;
293 %_______________________________________________________________________
294 M=P(1).mat;
295 A0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,wt,lkp);
296 if ~isempty(wt), b = (ave./count).*wt;
297 else, b = (ave./count); end
298
299 clear ave grad1 grad2 grad3
300
301 % Loop over images
302 %-----------------------------------------------------------------------
303 spm_progress_bar('Init',length(P),'Registering Images to Mean');
304 for i=1:length(P),
305 V=smooth_vol(P(i),flags.fwhm);
306 ss = Inf;
307 countdown = -1;
308 for iter=1:64,
309 [y1,y2,y3] = coords([0 0 0 0 0 0],M,P(i).mat,x1,x2,x3);
310 msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));
311 if length(msk)<32, error_message(P(i)); end;
312
313 F = spm_sample_vol(V, y1(msk),y2(msk),y3(msk),flags.hold);
314 if ~isempty(wt), F = F.*wt(msk); end;
315
316 A = [A0(msk,:) F];
317 Alpha = spm_atranspa(A);
318 Beta = A'*b(msk);
319 soln = Alpha\Beta;
320
321 p = [0 0 0 0 0 0 1 1 1 0 0 0];
322 p(lkp) = soln(1:(end-1));
323 P(i).mat = inv(spm_matrix(p))*P(i).mat;
324
325 pss = ss;
326 ss = sum((F*soln(end)-b(msk)).^2)/length(msk);
327 if (pss-ss)/pss < 1e-8 & countdown == -1 % Stopped converging.
328 % Do three final iterations to finish off with
329 countdown = 2;
330 end;
331 if countdown ~= -1
332 if countdown==0, break; end;
333 countdown = countdown -1;
334 end;
335 end;
336 spm_progress_bar('Set',i);
337 end;
338 spm_progress_bar('Clear');
339
340
341 % Since we are supposed to be aligning everything to the first
342 % image, then we had better do so
343 %-----------------------------------------------------------------------
344 M = M/P(1).mat;
345 for i=1:length(P)
346 P(i).mat = M*P(i).mat;
347 end
348
349 return;
350 %_______________________________________________________________________
351
352 %_______________________________________________________________________
353 function [y1,y2,y3]=coords(p,M1,M2,x1,x2,x3)
354 % Rigid body transformation of a set of coordinates.
355 M = (inv(M2)*inv(spm_matrix(p(1:6)))*M1);
356 y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
357 y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
358 y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
359 return;
360 %_______________________________________________________________________
361
362 %_______________________________________________________________________
363 function V = smooth_vol(P,fwhm)
364 % Convolve the volume in memory.
365 s = sqrt(sum(P.mat(1:3,1:3).^2)).^(-1)*(fwhm/sqrt(8*log(2)));
366 x = round(6*s(1)); x = [-x:x];
367 y = round(6*s(2)); y = [-y:y];
368 z = round(6*s(3)); z = [-z:z];
369 x = exp(-(x).^2/(2*(s(1)).^2));
370 y = exp(-(y).^2/(2*(s(2)).^2));
371 z = exp(-(z).^2/(2*(s(3)).^2));
372 x = x/sum(x);
373 y = y/sum(y);
374 z = z/sum(z);
375
376 i = (length(x) - 1)/2;
377 j = (length(y) - 1)/2;
378 k = (length(z) - 1)/2;
379
380 V = zeros(P.dim(1:3));
381 spm_conv_vol(P,V,x,y,z,-[i j k]);
382 return;
383 %_______________________________________________________________________
384
385 %_______________________________________________________________________
386 function A = make_A(M,x1,x2,x3,dG1,dG2,dG3,wt,lkp)
387 % Matrix of rate of change of weighted difference w.r.t. parameter changes
388 p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
389 A = zeros(prod(size(x1)),length(lkp));
390 for i=1:length(lkp)
391 pt = p0;
392 pt(lkp(i)) = pt(i)+1e-6;
393 [y1,y2,y3] = coords(pt,M,M,x1,x2,x3);
394 tmp = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)/(-1e-6);
395 if ~isempty(wt), A(:,i) = tmp.*wt;
396 else, A(:,i) = tmp; end
397 end
398 return;
399 %_______________________________________________________________________
400
401 %_______________________________________________________________________
402 function error_message(P)
403
404 str = { 'There is not enough overlap in the images',...
405 'to obtain a solution.',...
406 ' ',...
407 'Offending image:',...
408 P.fname,...
409 ' ',...
410 'Please check that your header information is OK.'};
411 spm('alert*',str,mfilename,sqrt(-1));
412 error('insufficient image overlap')
413
414 return
415 %_______________________________________________________________________
416
417 %_______________________________________________________________________
418 function plot_parameters(P)
419 fg=spm_figure('FindWin','Graphics');
420 if ~isempty(fg),
421 P = cat(1,P{:});
422 if length(P)<2, return; end;
423 Params = zeros(prod(size(P)),12);
424 for i=1:prod(size(P)),
425 Params(i,:) = spm_imatrix(P(i).mat/P(1).mat);
426 end
427
428 % display results
429 % translation and rotation over time series
430 %-------------------------------------------------------------------
431 spm_figure('Clear','Graphics');
432 ax=axes('Position',[0.1 0.65 0.8 0.2],'Parent',fg,'Visible','off');
433 set(get(ax,'Title'),'String','Image realignment','FontSize',16,'FontWeight','Bold','Visible','on');
434 x = 0.1;
435 y = 0.9;
436 for i = 1:min([prod(size(P)) 12])
437 text(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax);
438 y = y - 0.08;
439 end
440 if prod(size(P)) > 12
441 text(x,y,'................ etc','FontSize',10,'Parent',ax); end
442
443 ax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');
444 plot(Params(:,1:3),'Parent',ax)
445 s = ['x translation';'y translation';'z translation'];
446 text([2 2 2], Params(2, 1:3), s, 'Fontsize',10,'Parent',ax)
447 set(get(ax,'Title'),'String','translation','FontSize',16,'FontWeight','Bold');
448 set(get(ax,'Xlabel'),'String','image');
449 set(get(ax,'Ylabel'),'String','mm');
450
451
452 ax=axes('Position',[0.1 0.05 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');
453 plot(Params(:,4:6)*180/pi,'Parent',ax)
454 s = ['pitch';'roll ';'yaw '];
455 text([2 2 2], Params(2, 4:6)*180/pi, s, 'Fontsize',10,'Parent',ax)
456 set(get(ax,'Title'),'String','rotation','FontSize',16,'FontWeight','Bold');
457 set(get(ax,'Xlabel'),'String','image');
458 set(get(ax,'Ylabel'),'String','degrees');
459
460 % print realigment parameters
461 spm_print
462 end
463 return;
464 %_______________________________________________________________________
465
466 %_______________________________________________________________________
467 function save_parameters(V)
468 fname = [spm_str_manip(prepend(V(1).fname,'realignment_params_'),'s') '.txt'];
469 n = length(V);
470 Q = zeros(n,6);
471 for j=1:n,
472 qq = spm_imatrix(V(j).mat/V(1).mat);
473 Q(j,:) = qq(1:6);
474 end;
475 save(fname,'Q','-ascii');
476 return;
477 %_______________________________________________________________________
478
479 %_______________________________________________________________________
480 function PO = prepend(PI,pre)
481 [pth,nm,xt,vr] = fileparts(deblank(PI));
482 PO = fullfile(pth,[pre nm xt vr]);
483 return;
484 %_______________________________________________________________________