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
| function x = spm_coreg(varargin)
if nargin>=4,
x = optfun(varargin{:});
return;
end;
def_flags = struct('sep',[4 2],'params',[0 0 0 0 0 0], 'cost_fun','nmi','fwhm',[7 7],...
'tol',[0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001],'graphics',1);
if nargin < 3,
flags = def_flags;
else
flags = varargin{3};
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end;
end;
end;
%disp(flags)
if nargin < 1,
VG = spm_vol(spm_select(1,'image','Select reference image'));
else
VG = varargin{1};
if ischar(VG), VG = spm_vol(VG); end;
end;
if nargin < 2,
VF = spm_vol(spm_select(Inf,'image','Select moved image(s)'));
else
VF = varargin{2};
if ischar(VF) || iscellstr(VF), VF = spm_vol(strvcat(VF)); end;
end;
if ~isfield(VG, 'uint8'),%codage en format 8bit
VG.uint8 = loaduint8(VG);
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));%calcul le volume des voxels
fwhmg = sqrt(max([1 1 1]*flags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;% distance entre voxels
VG = smooth_uint8(VG,fwhmg); % Note side effects
end;
sc = flags.tol(:)'; % Required accuracy
sc = sc(1:length(flags.params));
xi = diag(sc*20); %diagonalisation de xi (c'est matrice)
for k=1:numel(VF), % de 1 jusqu'au nombre d'éléments du vecteur volume de l'image fonctionnelle
VFk = VF(k);
if ~isfield(VFk, 'uint8'), %on vérifie si chaque fichier est ds le format de codage 8bit
VFk.uint8 = loaduint8(VFk);
vxf = sqrt(sum(VFk.mat(1:3,1:3).^2));
fwhmf = sqrt(max([1 1 1]*flags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;
VFk = smooth_uint8(VFk,fwhmf); % Note side effects
end;
xk = flags.params(:);%calcul du vecteur
for samp=flags.sep(:)',
xk = spm_powell(xk(:), xi,sc,mfilename,VG,VFk,samp,flags.cost_fun,flags.fwhm); %optimisation avec la méthode de Powell
x(k,:) = xk(:)';
end;
if flags.graphics,
display_results(VG(1),VFk(1),xk(:)',flags); %flags prend la valeur de xk(:)
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function o = optfun(x,VG,VF,s,cf,fwhm)
% The function that is minimised.
if nargin<6, fwhm = [7 7]; end; %si j'ai saisie que 5 param, le lissage à faire est de 256*256
if nargin<5, cf = 'mi'; end; %fonction cout:information mutuelle
if nargin<4, s = [1 1 1]; end; % ???
% Voxel sizes
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));
sg = s./vxg; %est ce que tous les voxels sont un truc bidule
% Create the joint histogram
H = spm_hist2(VG.uint8,VF.uint8, VF.mat\spm_matrix(x(:)')*VG.mat ,sg);
% Smooth the histogram %lissage de l'histogramme
lim = ceil(2*fwhm);
krn1 = smoothing_kernel(fwhm(1),-lim(1):lim(1)) ; krn1 = krn1/sum(krn1); H = conv2(H,krn1);
krn2 = smoothing_kernel(fwhm(2),-lim(2):lim(2))'; krn2 = krn2/sum(krn2); H = conv2(H,krn2);
% Compute cost function from histogram
H = H+eps;
sh = sum(H(:));
H = H/sh;
s1 = sum(H,1);
s2 = sum(H,2);
switch lower(cf)
case 'mi',
% Mutual Information:
H = H.*log2(H./(s2*s1));
mi = sum(H(:));
o = -mi;
case 'ecc',
% Entropy Correlation Coefficient of:
% Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).
% "Multimodality image registration by maximisation of mutual
% information". IEEE Transactions on Medical Imaging 16(2):187-198
H = H.*log2(H./(s2*s1));
mi = sum(H(:));
ecc = -2*mi/(sum(s1.*log2(s1))+sum(s2.*log2(s2)));
o = -ecc;
case 'nmi',
% Normalised Mutual Information of:
% Studholme, Hill & Hawkes (1998).
% "A normalized entropy measure of 3-D medical image alignment".
% in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
nmi = (sum(s1.*log2(s1))+sum(s2.*log2(s2)))/sum(sum(H.*log2(H)));
o = -nmi;
case 'ncc',
% Normalised Cross Correlation
i = 1:size(H,1);
j = 1:size(H,2);
m1 = sum(s2.*i');
m2 = sum(s1.*j);
sig1 = sqrt(sum(s2.*(i'-m1).^2));
sig2 = sqrt(sum(s1.*(j -m2).^2));
[i,j] = ndgrid(i-m1,j-m2);
ncc = sum(sum(H.*i.*j))/(sig1*sig2);
o = -ncc;
otherwise,
error('Invalid cost function specified');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function udat = loaduint8(V)
% Load data from file indicated by V into an array of unsigned bytes.
if size(V.pinfo,2)==1 && V.pinfo(1) == 2,
mx = 255*V.pinfo(1) + V.pinfo(2);
mn = V.pinfo(2);
else
spm_progress_bar('Init',V.dim(3),...
['Computing max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
mx = -Inf; mn = Inf;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
mx = max([max(img(:))+paccuracy(V,p) mx]);
mn = min([min(img(:)) mn]);
spm_progress_bar('Set',p);
end;
end;
% Another pass to find a maximum that allows a few hot-spots in the data.
spm_progress_bar('Init',V.dim(3),...
['2nd pass max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
nh = 2048;
h = zeros(nh,1);
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
img = img(isfinite(img));
img = round((img+((mx-mn)/(nh-1)-mn))*((nh-1)/(mx-mn)));
if spm_matlab_version_chk('7.0')>=0,
h = h + accumarray(img,1,[nh 1]);
else
h = h + full(sparse(img,1,1,nh,1));
end
spm_progress_bar('Set',p);
end;
tmp = [find(cumsum(h)/sum(h)>0.9999); nh];
mx = (mn*nh-mx+tmp(1)*(mx-mn))/(nh-1);
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
%udat = zeros(V.dim,'uint8'); Needs MATLAB 7 onwards
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3)) = 0;
rand('state',100);
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
acc = paccuracy(V,p);
if acc==0,
udat(:,:,p) = uint8(max(min(round((img-mn)*(255/(mx-mn))),255),0));
else
% Add random numbers before rounding to reduce aliasing artifact
r = rand(size(img))*acc;
udat(:,:,p) = uint8(max(min(round((img+r-mn)*(255/(mx-mn))),255),0));
end;
spm_progress_bar('Set',p);
end;
spm_progress_bar('Clear');
return;
function acc = paccuracy(V,p)
if ~spm_type(V.dt(1),'intt'),
acc = 0;
else
if size(V.pinfo,2)==1,
acc = abs(V.pinfo(1,1));
else
acc = abs(V.pinfo(1,p));
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function V = smooth_uint8(V,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
x = -lim(1):lim(1); x = smoothing_kernel(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = smoothing_kernel(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = smoothing_kernel(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function krn = smoothing_kernel(fwhm,x)
% Variance from FWHM
s = (fwhm/sqrt(8*log(2)))^2+eps;
% The simple way to do it. Not good for small FWHM
% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));
% For smoothing images, one should really convolve a Gaussian
% with a sinc function. For smoothing histograms, the
% kernel should be a Gaussian convolved with the histogram
% basis function used. This function returns a Gaussian
% convolved with a triangular (1st degree B-spline) basis
% function.
% Gaussian convolved with 0th degree B-spline
% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)
% w1 = 1/sqrt(2*s);
% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));
% Gaussian convolved with 1st degree B-spline
% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)
% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)
w1 = 0.5*sqrt(2/s);
w2 = -0.5/s;
w3 = sqrt(s/2/pi);
krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...
+w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));
krn(krn<0) = 0;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function display_results(VG,VF,x,flags)
fig = spm_figure('FindWin','Graphics');
if isempty(fig), return; end;
set(0,'CurrentFigure',fig);
spm_figure('Clear','Graphics');
%txt = 'Information Theoretic Coregistration';
switch lower(flags.cost_fun)
case 'mi', txt = 'Mutual Information Coregistration';
case 'ecc', txt = 'Entropy Correlation Coefficient Registration';
case 'nmi', txt = 'Normalised Mutual Information Coregistration';
case 'ncc', txt = 'Normalised Cross Correlation';
otherwise, error('Invalid cost function specified');
end;
% Display text
%-----------------------------------------------------------------------
ax = axes('Position',[0.1 0.8 0.8 0.15],'Visible','off','Parent',fig);
text(0.5,0.7, txt,'FontSize',16,...
'FontWeight','Bold','HorizontalAlignment','center','Parent',ax);
Q = inv(VF.mat\spm_matrix(x(:)')*VG.mat);
text(0,0.5, sprintf('X1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(1,:)),'Parent',ax);
text(0,0.3, sprintf('Y1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(2,:)),'Parent',ax);
text(0,0.1, sprintf('Z1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(3,:)),'Parent',ax);
% Display joint histograms
%-----------------------------------------------------------------------
ax = axes('Position',[0.1 0.5 0.35 0.3],'Visible','off','Parent',fig);
H = spm_hist2(VG.uint8,VF.uint8,VF.mat\VG.mat,[1 1 1]);
tmp = log(H+1);
image(tmp*(64/max(tmp(:))),'Parent',ax');
set(ax,'DataAspectRatio',[1 1 1],...
'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...
'XTick',[],'YTick',[]);
title('Original Joint Histogram','Parent',ax);
xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);
ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);
H = spm_hist2(VG.uint8,VF.uint8,VF.mat\spm_matrix(x(:)')*VG.mat,[1 1 1]);
ax = axes('Position',[0.6 0.5 0.35 0.3],'Visible','off','Parent',fig);
tmp = log(H+1);
image(tmp*(64/max(tmp(:))),'Parent',ax');
set(ax,'DataAspectRatio',[1 1 1],...
'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...
'XTick',[],'YTick',[]);
title('Final Joint Histogram','Parent',ax);
xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);
ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);
% Display ortho-views
%-----------------------------------------------------------------------
spm_orthviews('Reset');
spm_orthviews('Image',VG,[0.01 0.01 .48 .49]);
h2 = spm_orthviews('Image',VF,[.51 0.01 .48 .49]);
global st
st.vols{h2}.premul = inv(spm_matrix(x(:)'));
spm_orthviews('Space');
spm_print
return; |
Partager