plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
philippboehmsturm/antx-master
|
clip2clipcell.m
|
.m
|
antx-master/mritools/ant/clip2clipcell.m
| 535 |
utf_8
|
d16bd7454b17f3567c289ce192a36711
|
%% convertse cellstring (pahts) in clipboard to matlabstyle cell (back to clipboard)
function clip2clipcell
% mat2clip(s.folder);
a=clipboard('paste');
a2=strsplit2(a,char(10))';
ro =['{' ; cellfun(@(a) {[ ' ''' a '''']},a2); '};'];
mat2clip(ro);
function Tokens = strsplit2(String, Delim)
Tokens = [];
while (size(String,2) > 0)
if isempty(Delim)
[Tok, String] = strtok(String);
else
[Tok, String] = strtok(String, Delim);
end
Tokens{end+1} = Tok;
end
|
github
|
philippboehmsturm/antx-master
|
xsegment.m
|
.m
|
antx-master/mritools/ant/xsegment.m
| 6,419 |
utf_8
|
24a16dd3893c304bd366c9e57ab9f0e9
|
%% SEGMENT MOUSE
% function xsegment(t2,template)
% function xsegment(t2,template,job)...see below
% function xsegment(t2,template,'segment') %% SEGMENT ONLY without using Freiburg-normalization
%% INPUT:
% t2 : FPfile of t2.nii
% template: {cell} with ordered TPMs(GM,WM,CSF)+FPfile of reorient.mat
%% EXAMPLE
% t2='O:\harms1\koeln\dat\s20150701_BB1\t2.nii';
% template={ 'O:\harms1\koeln\dat\s20150701_BB1\_b1grey.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b2white.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b3csf.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\reorient.mat'}
% xsegment(t2,template)
function xsegment(t2,template,job)
t2destpath=fileparts(t2);
% b0only = 0;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file')
% options(4) = 4;
% else
% options = 0;
% end
% Preparing path names
% t2path = mouse.t2;
% t2destpath = mouse.outfolder;
% t2nii = cell(length(t2path));
% for k = 1:length(t2path),
% t2fullname = fullfile(t2destpath,['t2_' num2str(k)]);
% t2nii{k} = [t2fullname '.nii,1'];
% end
% Start of segmentation with t2.nii
% If t2.nii does not exist use b0.nii
cnt = 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') == 2 && b0only == 0
matlabbatch{cnt}.spm.spatial.preproc.data = {t2} ;%{t2nii{1}}; %% T2file
matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% else
% % matlabbatch{cnt}.spm.spatial.preproc.data = {fullfile(t2destpath,'b0.nii')};
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% end;
matlabbatch{cnt}.spm.spatial.preproc.output.GM = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.WM = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.CSF = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.biascor = 1;
matlabbatch{cnt}.spm.spatial.preproc.output.cleanup = 0;
matlabbatch{cnt}.spm.spatial.preproc.opts.tpm = template; % Define Templates here
matlabbatch{cnt}.spm.spatial.preproc.opts.ngaus = [3
2
2
4];
matlabbatch{cnt}.spm.spatial.preproc.opts.regtype = 'animal'; % 'animal' / '';
matlabbatch{cnt}.spm.spatial.preproc.opts.biasreg = 0.0001;%0.0001;
matlabbatch{cnt}.spm.spatial.preproc.opts.biasfwhm = 5;
matlabbatch{cnt}.spm.spatial.preproc.opts.samp = 0.1;%0.1;
matlabbatch{cnt}.spm.spatial.preproc.opts.msk = {''};
cnt = cnt + 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') && b0only == 0
matlabbatch{cnt}.spm.util.imcalc.input = {
fullfile(t2destpath,'c1t2.nii')
fullfile(t2destpath,'c2t2.nii')
};
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1t2_1.nii,1')
% fullfile(t2destpath,'c2t2_1.nii,1')
% };
% else
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1b0.nii,1')
% fullfile(t2destpath,'c2b0.nii,1')
% };
% end
matlabbatch{cnt}.spm.util.imcalc.output = 'c1c2mask.nii';
matlabbatch{cnt}.spm.util.imcalc.outdir = { t2destpath };
matlabbatch{cnt}.spm.util.imcalc.expression = '((i1 + i2)/2)>0.3';
matlabbatch{cnt}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{cnt}.spm.util.imcalc.options.mask = 0;
matlabbatch{cnt}.spm.util.imcalc.options.interp = 1;
matlabbatch{cnt}.spm.util.imcalc.options.dtype = 4;
cnt = cnt + 1;
%% SEGMENT ONLY
if exist('job') && strcmp(job,'segment')
spm_jobman('serial', matlabbatch);
return
end
% Convert Deformation Parameters
% Convert deformation parameters to iy/y format (forward)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'forward';
matlabbatch{cnt}.spm.util.defs.fnames = '';
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
cnt = cnt + 1;
% Convert deformation parameters to iy/y format (inverse)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_inv_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_inv_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_inv_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'inverse';
matlabbatch{cnt}.spm.util.defs.fnames = {''};
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
% Realign deformations to original template space
cnt = cnt + 1;
matlabbatch{cnt}.dtijobs.realigndef.yname = {fullfile(t2destpath,'y_forward.nii')};
matlabbatch{cnt}.dtijobs.realigndef.iyname = {fullfile(t2destpath,'y_inverse.nii')};
matlabbatch{cnt}.dtijobs.realigndef.matname = template(end);%template(4);
% return
spm_jobman('serial', matlabbatch);
|
github
|
philippboehmsturm/antx-master
|
listeval.m
|
.m
|
antx-master/mritools/ant/listeval.m
| 3,581 |
utf_8
|
234ee4dc1d9633a6812f57baf29db123
|
function out=listeval(p,ro)
% eval([name '=an;']);
% ro=an;
% ro=rmfield(ro,'ls');
% eval([name '=ro;']);
% p=struct2list(ro)
% eval(['p=struct2list(' name ')']);
v=1:size(p,1);
for i=1:size(p,1)
if ~isnan(v(i))
try
d=p{v(i)};
eval(d);
s=1;
n=0;
catch
n=1;
s=0;
while s==0
try
d=[d ';' p{v(i+n)}];
eval(d);
s=1;
catch
n=n+1;
end
end
end
v(i:i+n)=nan;
end
end
eval(['out' '=' ro ';']);
% varn=who
% varn(strcmp(varn,'varn'))=[]
% varn(strcmp(varn,'ans'))=[]
%
% for i=1:length(varn)
% if isstruct()
%
% end
%
%
%
% 'an.inf99='*** CONFIGURATION PARAMETERS *** ';'
% 'an.inf100='===================================';'
% 'an.inf1='% DEFAULTS ';'
% 'an.project='testData-study1';'
% 'an.datpath='O:\TOMsampleData\study2\dat';'
% 'an.voxsize=[0.07 0.07 0.07];'
% 'an.inf2='% WARPING ';'
% 'an.wa.refTPM={ 'O:\TOM\mritools\ant\templateBerlin_hres\_b1grey.nii' '
% ' 'O:\TOM\mritools\ant\templateBerlin_hres\_b2white.nii' '
% ' 'O:\TOM\mritools\ant\templateBerlin_hres\_b3csf.nii' };'
% 'an.wa.ano='O:\TOM\mritools\ant\templateBerlin_hres\ANO.nii';'
% 'an.wa.avg='O:\TOM\mritools\ant\templateBerlin_hres\AVGT.nii';'
% 'an.wa.fib='O:\TOM\mritools\ant\templateBerlin_hres\FIBT.nii';'
% 'an.wa.refsample='O:\TOM\mritools\ant\templateBerlin_hres\_sample.nii';'
% 'an.wa.create_gwc=[1];'
% 'an.wa.create_anopcol=[1];'
% 'an.wa.cleanup=[0];'
% 'an.wa.usePCT=[2];'
% 'an.wa.usePriorskullstrip=[1];'
% 'an.wa.elxParamfile={ 'O:\TOM\mritools\elastix\paramfiles\Par0025affine.txt' '
% ' 'O:\TOM\mritools\elastix\paramfiles\Par0033bspline_EM2.txt' };'
% 'an.wa.elxMaskApproach=[1];'
% 'an.wa.tf_ano=[1];'
% 'an.wa.tf_anopcol=[1];'
% 'an.wa.tf_avg=[1];'
% 'an.wa.tf_refc1=[1];'
% 'an.wa.tf_t2=[1];'
% 'an.wa.tf_c1=[1];'
% 'an.wa.tf_c2=[1];'
% 'an.wa.tf_c3=[1];'
% 'an.wa.tf_c1c2mask=[1];'
% 'an.templatepath='O:\TOMsampleData\study2\templates';'
% 'an.configfile='O:\TOMsampleData\study2\proj_study2.m';'
% 'an.mdirs={ 'O:\TOMsampleData\study2\dat\s20150908_FK_C1M02_1_3_1' '
% ' 'O:\TOMsampleData\study2\dat\s20150908_FK_C1M04_1_3_1' '
% ' 'O:\TOMsampleData\study2\dat\sbla1' '
% ' 'O:\TOMsampleData\study2\dat\sbla2' };'
%
%
%
%
%
%
%
%
%
%
%
%
%
%
% mnext=1;
% for i=1:size(p,1)
%
% if i==mnext
% d=p{i};
% try
% eval(d);
% s=1;
% mnext=i+1;
% catch
%
% s=0;
% n=1;
% dum=char(p(i));
% while s==0
% dum=[dum ';' char(p(i+n)) ];
% try
%
% eval( [dum] );
% s=1;
% mnext=i+1;
% dum
% catch
% n=n+1;
% end
% end
% end
% end
%
% end
%
% % out=ro;
% eval(['out' '=' ro ';']);
%
%
%
|
github
|
philippboehmsturm/antx-master
|
deform.m
|
.m
|
antx-master/mritools/ant/deform.m
| 2,241 |
utf_8
|
bb077683bbc4f48c80f10bd74dc37ca4
|
function deform( files ,direction, resolution, interpx)
if exist('direction')~=1; direction=[]; end;
if isempty(direction); direction =1; end
if exist('resolution')~=1; resolution=[]; end;
if isempty(resolution); resolution =[.025 .025 .025]; end
if exist('interpx')~=1; interpx=[]; end;
if isempty(interpx); interpx =4; end
pathx=fileparts(files{1});
% bbox = [-6 -9.5 -7
% 6 5.5 1];
% bbox = [nan nan nan;nan nan nan];
% bbox = [nan(2,3)];
bbox = world_bb(files{1});
cnt = 1;
nr = 1;
if direction==1
matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(pathx,'y_forward.nii')};
elseif direction==-1
matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(pathx,'y_inverse.nii')};
end
%matlabbatch{cnt}.spm.util.defs.comp{2}.id.space = '<UNDEFINED>'; % For fMRI Files use fMRI-Scan resolution.
matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.vox = resolution;
matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.bb = bbox;
matlabbatch{cnt}.spm.util.defs.ofname = '';
matlabbatch{cnt}.spm.util.defs.fnames = files(1:end);
matlabbatch{cnt}.spm.util.defs.savedir.savesrc = 1;
matlabbatch{cnt}.spm.util.defs.interp =interpx;% 4; default is 4 (spline4)
spm_jobman('serial', matlabbatch);
% resolution =[.025 .025 .025]
% bbox = [-6 -9.5 -7
% 6 5.5 1];
% cnt = 1;
% nr = 1;
% AMAfiles =..
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c1t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c2t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c1c2mask.nii,1'
% %
% matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(t2destpath,'y_forward.nii')};
% %matlabbatch{cnt}.spm.util.defs.comp{2}.id.space = '<UNDEFINED>'; % For fMRI Files use fMRI-Scan resolution.
% matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.vox = resolution;
% matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.bb = bbox;
% matlabbatch{cnt}.spm.util.defs.ofname = '';
% matlabbatch{cnt}.spm.util.defs.fnames = AMAfiles(1:end);
% matlabbatch{cnt}.spm.util.defs.savedir.savesrc = 1;
% matlabbatch{cnt}.spm.util.defs.interp = 4;
% spm_jobman('serial', matlabbatch);
|
github
|
philippboehmsturm/antx-master
|
warp_summary.m
|
.m
|
antx-master/mritools/ant/warp_summary.m
| 3,237 |
utf_8
|
2d5764972476ecc2dded7048bf8ad89b
|
% imswap==1: than rfile is on top
function warp_summary(s)
if 0
s.file='w_t2.nii';
s.slice=75;
warp_summary(s);
warp_summary(struct('sfile','x_t2.nii','slice',100))
end
jet=[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 0.9375;0.125 1 0.875;0.1875 1 0.8125;0.25 1 0.75;0.3125 1 0.6875;0.375 1 0.625;0.4375 1 0.5625;0.5 1 0.5;0.5625 1 0.4375;0.625 1 0.375;0.6875 1 0.3125;0.75 1 0.25;0.8125 1 0.1875;0.875 1 0.125;0.9375 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0;0.5 0 0];
jet(1,:)=[0 0 0];
if isfield(s,'file'); file=s.file ; else s.file='x_t2.nii' ; file=s.file ; end
if isfield(s,'doresize'); doresize=s.doresize ; else s.doresize=1 ; doresize=s.doresize ; end
if isfield(s,'slice'); slice=s.slice ; else s.slice=100 ; slice=s.slice ; end
if isfield(s,'cmap'); cmap=s.cmap ; else s.cmap=jet ; cmap=s.cmap ; ; end
fil=antcb('getsubjects');
fis=stradd(fil,[filesep file],2);
temppa=fullfile(fileparts(fileparts(fil{1})),'templates');
if isfield(s,'ref'); ref=[] ;
if isempty(ref)
ref= fis{1};
V=spm_vol(ref);
end
else ;
ref=fullfile(temppa,'AVGT.nii');
V=spm_vol(ref);
end
% ref=fullfile(temppa,'ANOpcol.nii');
% [ha a]=rgetnii(ref);
% [hb b]=rgetnii(fis{1});
% doresize=1;
% sliznum=100;
% V=spm_vol(ref);
C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1];
C(2,4) = slice;
DIM = V(1).dim([1 3]);
rf=rot90(spm_slice_vol(V, C, DIM, 0));
if doresize==1
newsize=repmat(min(size(rf)),[1 2]);
rf= imresize(rf, newsize);
end
rf=single(repmat(rf,[1 1 size(fis,1)]));
ri=single(zeros(size(rf)));
for i=1:size(fis,1)
hb=spm_vol(fis{i});
dd=rot90(spm_slice_vol(hb, C, DIM, 0));
if doresize==1
dd= imresize(dd, newsize);
end
dd=dd-min(dd(:)); dd=dd./max(dd(:));
ri(:,:,i)=dd;
end
add.title=replacefilepath(fil,'');
imoverlay2(rf,ri,[],[],cmap,[.5],'',add);;
% grid minor; set(gca,'xcolor','r','ycolor','r'); axis image;
us=get(gcf,'userdata');
us.add=s;
set(gcf,'userdata',us);
try;
set(gcf,'name',[ 'slice' num2str(s.slice) ' type<h>for shortcuts']);
end
%
% V=ha
% C = [1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1]
% C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1]
% %C=[0 -1 0 0 ; 0 0 1 0 ; 1 0 0 0; 0 0 0 1]
%
% DIM = V(1).dim([1 3]);
% C(2,4) = 75
% %C(3,4)=-p;
%
% % img = rot90(spm_slice_vol(V,C,DIM,0));
% % img = spm_slice_vol(V,inv(C),DIM,0);
% w=[]
% for i=1:length(V)
% w(:,:,i) = spm_slice_vol(V(i), C, DIM, 0);
% 'a'
% end
% w = squeeze(w);
% figure(10)
% imagesc(w)
|
github
|
philippboehmsturm/antx-master
|
snip_listbox_undocumented.m
|
.m
|
antx-master/mritools/ant/snip_listbox_undocumented.m
| 1,237 |
utf_8
|
37d32151a083cc83906345a3c6af639f
|
function snip_listbox_undocumented
fg;
set(gcf,'units','norm')
hListbox = uicontrol('Style','Listbox','units','norm','position',[.2 .3 .2 .55], 'String',...
{'item #1','item #2','item #3' '44444' '555' '66666' '77777','888888' '99999' '100000'},'fontsize',10);
jScrollPane = java(findjobj(hListbox))
jListbox = jScrollPane.getViewport.getView
% Set the mouse-movement event callback
set(jListbox, 'MouseMovedCallback', {@mouseMovedCallback,hListbox});
% Mouse-movement callback
function mouseMovedCallback(jListbox, jEventData, hListbox)
% Get the currently-hovered list-item
mousePos = java.awt.Point(jEventData.getX, jEventData.getY);
% hoverIndex = jListbox.locationToIndex(mousePos) + 1;
hoverIndex=get(mousePos,'Y');
fs=get(hListbox,'fontsize');
[hoverIndex hoverIndex/fs];
est=fs*2;
re=rem(hoverIndex,est);
va=(hoverIndex-re)/est;
% t=[hoverIndex va+1 ]
hoverIndex2=va+1;
listValues = get(hListbox,'string');
hoverValue = listValues{hoverIndex2};
% Modify the tooltip based on the hovered item
msgStr = sprintf('<html>item #%d: <b>%s</b></html>', hoverIndex2, hoverValue);
set(hListbox, 'Tooltip',msgStr);
% mouseMovedCallback
|
github
|
philippboehmsturm/antx-master
|
xsegment_test.m
|
.m
|
antx-master/mritools/ant/xsegment_test.m
| 6,476 |
utf_8
|
a24925f027d684bad739810fcaa3a89e
|
%% SEGMENT MOUSE
% function xsegment(t2,template)
% function xsegment(t2,template,job)...see below
% function xsegment(t2,template,'segment') %% SEGMENT ONLY without using Freiburg-normalization
%% INPUT:
% t2 : FPfile of t2.nii
% template: {cell} with ordered TPMs(GM,WM,CSF)+FPfile of reorient.mat
%% EXAMPLE
% t2='O:\harms1\koeln\dat\s20150701_BB1\t2.nii';
% template={ 'O:\harms1\koeln\dat\s20150701_BB1\_b1grey.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b2white.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b3csf.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\reorient.mat'}
% xsegment(t2,template)
function xsegment(t2,template,job)
t2destpath=fileparts(t2);
% b0only = 0;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file')
% options(4) = 4;
% else
% options = 0;
% end
% Preparing path names
% t2path = mouse.t2;
% t2destpath = mouse.outfolder;
% t2nii = cell(length(t2path));
% for k = 1:length(t2path),
% t2fullname = fullfile(t2destpath,['t2_' num2str(k)]);
% t2nii{k} = [t2fullname '.nii,1'];
% end
% Start of segmentation with t2.nii
% If t2.nii does not exist use b0.nii
cnt = 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') == 2 && b0only == 0
matlabbatch{cnt}.spm.spatial.preproc.data = {t2} ;%{t2nii{1}}; %% T2file
matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% else
% % matlabbatch{cnt}.spm.spatial.preproc.data = {fullfile(t2destpath,'b0.nii')};
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% end;
matlabbatch{cnt}.spm.spatial.preproc.output.GM = [0 0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.WM = [0 0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.CSF = [0 0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.SK = [0 0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.biascor = 1;
matlabbatch{cnt}.spm.spatial.preproc.output.cleanup = 0;
matlabbatch{cnt}.spm.spatial.preproc.opts.tpm = template; % Define Templates here
matlabbatch{cnt}.spm.spatial.preproc.opts.ngaus = [3
2
2
4];
matlabbatch{cnt}.spm.spatial.preproc.opts.regtype = 'animal'; % 'animal' / '';
matlabbatch{cnt}.spm.spatial.preproc.opts.biasreg = 0.0001;
matlabbatch{cnt}.spm.spatial.preproc.opts.biasfwhm = 5;
matlabbatch{cnt}.spm.spatial.preproc.opts.samp = 0.1;
matlabbatch{cnt}.spm.spatial.preproc.opts.msk = {''};
cnt = cnt + 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') && b0only == 0
matlabbatch{cnt}.spm.util.imcalc.input = {
fullfile(t2destpath,'c1t2.nii')
fullfile(t2destpath,'c2t2.nii')
};
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1t2_1.nii,1')
% fullfile(t2destpath,'c2t2_1.nii,1')
% };
% else
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1b0.nii,1')
% fullfile(t2destpath,'c2b0.nii,1')
% };
% end
matlabbatch{cnt}.spm.util.imcalc.output = 'c1c2mask.nii';
matlabbatch{cnt}.spm.util.imcalc.outdir = { t2destpath };
matlabbatch{cnt}.spm.util.imcalc.expression = '((i1 + i2)/2)>0.3';
matlabbatch{cnt}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{cnt}.spm.util.imcalc.options.mask = 0;
matlabbatch{cnt}.spm.util.imcalc.options.interp = 1;
matlabbatch{cnt}.spm.util.imcalc.options.dtype = 4;
cnt = cnt + 1;
%% SEGMENT ONLY
if exist('job') && strcmp(job,'segment')
spm_jobman('serial', matlabbatch);
return
end
% Convert Deformation Parameters
% Convert deformation parameters to iy/y format (forward)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'forward';
matlabbatch{cnt}.spm.util.defs.fnames = '';
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
cnt = cnt + 1;
% Convert deformation parameters to iy/y format (inverse)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_inv_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_inv_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_inv_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'inverse';
matlabbatch{cnt}.spm.util.defs.fnames = {''};
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
% Realign deformations to original template space
cnt = cnt + 1;
matlabbatch{cnt}.dtijobs.realigndef.yname = {fullfile(t2destpath,'y_forward.nii')};
matlabbatch{cnt}.dtijobs.realigndef.iyname = {fullfile(t2destpath,'y_inverse.nii')};
matlabbatch{cnt}.dtijobs.realigndef.matname = template(end);%template(4);
% return
spm_jobman('serial', matlabbatch);
|
github
|
philippboehmsturm/antx-master
|
warp_summary2.m
|
.m
|
antx-master/mritools/ant/warp_summary2.m
| 11,000 |
utf_8
|
08574cbfbd4cfa9cc61034bd961a5556
|
%nsb: number of slices : [],=[nan nan] [nan x] [x nan] [line]..each subject in one line
function warp_summary2(s)
if 0
study='O:\harms1\harms3_lesionfill\proj_Harms3_lesionfill.m'
ant,antcb('load',study);
s.file='w_t2.nii';
s.slice=75;
warp_summary(s);
cmap2=jet;
cmap2(1,:)=[0 0 0]
warp_summary2(struct('sfile','x_t2.nii','slice',100,'cmap',cm,'rfile', 'O:\harms1\harms3_lesionfill\templates\ANOpcol.nii','imswap',0))
warp_summary2(struct('sfile','x_t2.nii','slice',[80 100 140 ],'rfile', 'O:\harms1\harms3_lesionfill\templates\ANOpcol.nii','imswap',1,'nsb',[nan 3],'cut',[0.2 0 0.2 0]))
end
jet2=[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 0.9375;0.125 1 0.875;0.1875 1 0.8125;0.25 1 0.75;0.3125 1 0.6875;0.375 1 0.625;0.4375 1 0.5625;0.5 1 0.5;0.5625 1 0.4375;0.625 1 0.375;0.6875 1 0.3125;0.75 1 0.25;0.8125 1 0.1875;0.875 1 0.125;0.9375 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0;0.5 0 0];
jet2(1,:)=[0 0 0];
if isfield(s,'file'); file=s.file ; else s.file='x_t2.nii' ; file=s.file ; end
if isfield(s,'doresize'); doresize=s.doresize ; else s.doresize=1 ; doresize=s.doresize ; end
if isfield(s,'slice'); slice=s.slice ; else s.slice=100 ; slice=s.slice ; end
if isfield(s,'cmap'); cmap=s.cmap ; else s.cmap=jet2 ; cmap=s.cmap ; end
if isempty(cmap); s.cmap=jet2;end
fil=antcb('getsubjects');
fis=stradd(fil,[filesep file],2);
temppa=fullfile(fileparts(fileparts(fil{1})),'templates');
% ref=fullfile(temppa,'AVGT.nii');
% ref=fullfile(temppa,'ANOpcol.nii');
% if isfield(s,'rfile'); ref=s.rfile ; else s.rfile=fullfile(temppa,'AVGT.nii'); ref=s.rfile ; ; end
% if isfield(s,'rfile'); ref=s.rfile ; else s.rfile=[]; ref=s.rfile ; ; end
if isfield(s,'rfile'); ref=s.rfile ; else s.rfile=s.file; ref=s.rfile ; ; end
if ~isfield(s,'imswap'); s.imswap=0 ; end %background and overlay image swapped
if ~isfield(s,'nsb'); s.nsb=[] ; end ;%number of subplots
if ~isfield(s,'cut'); s.cut=[] ; end ;%number of subplots
if ~isfield(s,'alpha'); s.alpha=0.5 ; end ;%alphaValue
% [ha a]=rgetnii(ref);
% [hb b]=rgetnii(fis{1});
% doresize=1;
% sliznum=100;
% V=spm_vol(ref);
% C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1];
% C(2,4) = slice;
% DIM = V(1).dim([1 3]);
% rf=rot90(spm_slice_vol(V, C, DIM, 0));
% if doresize==1
% newsize=repmat(min(size(rf)),[1 2]);
% rf= imresize(rf, newsize);
% end
% rf=single(repmat(rf,[1 1 size(fis,1)]));
if ischar(s.slice) %plot every x.th slice
hd=spm_vol(ref);
every=str2num(strrep(s.slice,'''',''));
if length(every)==1
s.slice=[1:every(1):hd.dim(2)]';
elseif length(every)==2
s.slice=[every(2):every:hd.dim(2)-every(2)]';
elseif length(every)==3
s.slice=[every(2):every:hd.dim(2)-every(3)]';
end
end
if exist(s.rfile)==0
s.rfile=stradd(fil,[filesep s.rfile],2);
s.refexplicit=0;
exists=zeros(size(fis,1),1);
for i=1: size(fis,1) %check existence
if (exist(fis{i})==2) && (exist(s.rfile{i})==2) % (exist( fullfile(fileparts(fis{i}), s.rfile{i}) )==2)
exists(i)=1;
end
end
if sum(exists)==0
disp('no files found');
return
else
fis= fis(exists==1);
s.rfile=s.rfile( exists==1);
end
else
s.refexplicit=1;
end
if s.refexplicit==1
idxcord=zeros(3,length(s.slice));
idxcord(2,:)=[s.slice];
if ischar(s.rfile)
out=mni2idx(idxcord, spm_vol(s.rfile) , 'idx2mni' );
else
out=mni2idx(idxcord, spm_vol(s.rfile{1}) , 'idx2mni' );
end
s.sliceMM=out(:,2);
else
idxcord=zeros(3,length(s.slice));
idxcord(2,:)=[s.slice];
dum=[];
for i=1:size(s.rfile,1)
out=mni2idx(idxcord, spm_vol(s.rfile{i}) , 'idx2mni' );
dum=[dum; out(:,2) ];
end
s.sliceMM=dum;
end
if s.refexplicit==1
rf0=[];
for islice=1:length(s.slice)
V=spm_vol(ref);
C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1];
C(2,4) = s.slice(islice);
DIM = V(1).dim([1 3]);
rf=rot90(spm_slice_vol(V, C, DIM, 0));
if doresize==1
newsize=repmat(min(size(rf)),[1 2]);
rf= imresize(rf, newsize);
end
rf0(:,:,islice)=rf;%single(repmat(rf,[1 1 size(fis,1)]));
Cmat(:,:,islice)=C;
end
rf =single(repmat(rf0,[1 1 size(fis,1)]));
Cmat=single(repmat(Cmat,[1 1 size(fis,1)]));
cord =single(repmat(s.sliceMM(:),[size(fis,1) 1]));
sliceID=single(repmat(s.slice(:),[size(fis,1) 1]));
fis=repmat(fis,[1 length(s.slice)])';
fis=fis(:);
else
n=1;
for j=1:size(s.rfile,1)
V=spm_vol(s.rfile{j});
for islice=1:length(s.slice)
C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1];
C(2,4) = s.slice(islice);
DIM = V(1).dim([1 3]);
rf=rot90(spm_slice_vol(V, C, DIM, 0));
if doresize==1
newsize=repmat(min(size(rf)),[1 2]);
rf= imresize(rf, newsize);
end
rf0(:,:,n)=rf;%single(repmat(rf,[1 1 size(fis,1)]));
Cmat(:,:,n)=C;
% fis2{n,1}=fis{j};
% disp(fis{j});
sliceID(n,1) =s.slice(islice);
cord(n,1) =s.sliceMM(n);
n=n+1;
end
% rf =single(repmat(rf0,[1 1 size(fis,1)]));
% Cmat=single(repmat(Cmat,[1 1 size(fis,1)]));
% cord =single(repmat(s.sliceMM(:),[size(fis,1) 1]));
% sliceID=single(repmat(s.slice(:),[size(fis,1) 1]));
end
fis2=repmat(fis,[1 length(s.slice)])';
fis=fis2(:);
rf=rf0;
end
ri=single(zeros(size(rf)));
for i=1:size(fis,1)
hb=spm_vol(fis{i});
dd=rot90(spm_slice_vol(hb, double(squeeze(Cmat(:,:,i))), DIM, 0));
if doresize==1
dd= imresize(dd, newsize);
end
dd=dd-min(dd(:)); dd=dd./max(dd(:));
ri(:,:,i)=dd;
end
%cut percent
if ~isempty(s.cut)
if length(s.cut)==4
si=size(ri);
cut=[round(si(1)*s.cut(2)) round(si(1)*s.cut(1)) round(si(2)*s.cut(3)) round(si(2)*s.cut(4)) ];
ri=ri(1+cut(1):end-cut(2),1+cut(3):end-cut(4),:);
rf=rf(1+cut(1):end-cut(2),1+cut(3):end-cut(4),:);
else
end
end
titlex={};
for i=1:length(fis)
[paw fiw extw]=fileparts(fis{i});
[paw2 fiw2]=fileparts(paw);
if s.refexplicit==1
[paz fiz extz]=fileparts(s.rfile);
else
[paz fiz extz]=fileparts(ref);
end
ar='';
if length(s.slice)==1
ar=[[fiw2 filesep fiw extw '-' fiz extz]];
else
if mod(i,length(s.slice))==1;
ar=[[fiw2 filesep fiw extw '-' fiz extz]];
else
end
end
titlex{i,1}=ar;
end
% rf(rf>0)=1;%just for now
% rf=ceil(rf);
% rf(rf<.1)=0;
% rf(rf>1.1)=2;
% rf(rf~=0 & rf~=2)=1;
%
add=[];
if isstr(s.nsb)
if strcmp(s.nsb,'line') %one subject in each line
add.nsb=[nan length(s.slice) ] ;
end
else
add.nsb=s.nsb;
end
add.title=titlex;
add.cord=[sliceID cord ];
if s.imswap==0
imoverlay2(rf,ri,[],[],s.cmap,s.alpha,'',add);;
else
imoverlay2(ri,rf,[],[],s.cmap,s.alpha,'',add);;
end
% grid minor; set(gca,'xcolor','r','ycolor','r'); axis image;
us=get(gcf,'userdata');
us.add=s;
set(gcf,'userdata',us);
try;
set(gcf,'name',[ 'slice' num2str(s.slice) ' type<h>for shortcuts']);
end
%
% V=ha
% C = [1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1]
% C=[1 0 0 0; 0 0 1 0; 0 1 1 0; 0 0 0 1]
% %C=[0 -1 0 0 ; 0 0 1 0 ; 1 0 0 0; 0 0 0 1]
%
% DIM = V(1).dim([1 3]);
% C(2,4) = 75
% %C(3,4)=-p;
%
% % img = rot90(spm_slice_vol(V,C,DIM,0));
% % img = spm_slice_vol(V,inv(C),DIM,0);
% w=[]
% for i=1:length(V)
% w(:,:,i) = spm_slice_vol(V(i), C, DIM, 0);
% 'a'
% end
% w = squeeze(w);
% figure(10)
% imagesc(w)
function res=mni2idx(cords, hdr, mode )
% convert cords from [idx to mni] or [mni to idx]
% cords must be [3xX]
% ===========================
% convert idx2mni
% res=mni2idx( orig.x.XYZ(:,1:10000) , orig.x.hdr, 'idx2mni' );
% sum(sum(orig.x.XYZmm(:,1:10000)-res'))
% % convert mni2idx
% res=mni2idx( orig.x.XYZmm(:,1:10000) , orig.x.hdr, 'mni2idx' );
% test: sum(sum(orig.x.XYZ(:,1:10000)-res'))
% hdr =orig.x.hdr;
% xyz =orig.x.XYZ;
% xyzmm =orig.x.XYZmm;
hb=hdr.mat;
%% idx2mni
if strcmp(mode,'idx2mni')
q=cords;
%q=xyz(:,i);
Q =[q ; ones(1,size(q,2))];
Q2=Q'*hb';
Q2=Q2(:,1:3);
res=Q2;
% n=xyzmm(:,i)'
% Q2-n
elseif strcmp(mode,'mni2idx')
%% mni2idx
si=size(cords);
if si(1)==1
cords=cords';
end
Q2=cords';
%Q2= xyzmm(:,i)';
Q2=[Q2 ones(size(Q2,1),1)] ;
Q =hb\Q2';
Q=Q(1:3,:)';
% f=xyz(:,i)'
% Q-f
res=Q;
else
error('use idx2mni or mni2idx');
end
%
%
%
% orig.x.XYZ
% orig.x.XYZmm
% orig.x.hdr
%
%
% m=orig.x.hdr.mat
% hb=m
% s_x=hb(1,:);%hb.hdr.hist.srow_x;
% s_y=hb(2,:);%hb.hdr.hist.srow_y;
% s_z=hb(3,:);%hb.hdr.hist.srow_z;
%
% for j=1:10000
% i=j
% q=orig.x.XYZ(:,i);
% n=orig.x.XYZmm(:,i);
%
%
% % s_x(find(s_x(1:3)==0))=1;
% % s_y(find(s_y(1:3)==0))=1;
% % s_z(find(s_z(1:3)==0))=1;
%
%
% ff=q';
%
% nc(:,1) = s_x(1).* ff(:,1) + s_x(2).* ff(:,2) + s_x(3).* ff(:,3) + s_x(4);
% nc(:,2) = s_y(1).* ff(:,1) + s_y(2).* ff(:,2) + s_y(3).* ff(:,3) + s_y(4);
% nc(:,3) = s_z(1).* ff(:,1) + s_z(2).* ff(:,2) + s_z(3).* ff(:,3) + s_z(4);
%
% q(:)'
% n(:)'
% nc(:)'
%
% nn(j,:)=nc;
% end
%
% % sum(sum(abs(nn-Q2)))
%
% %% idx2mni
% i=1:5
%
% q=orig.x.XYZ(:,i)
% Q =[q ; ones(1,size(q,2))];
% Q2=Q'*hb';
% Q2=Q2(:,1:3)
% n=orig.x.XYZmm(:,i)'
%
% Q2-n
%
% %% mni2idx
% Q2= orig.x.XYZmm(:,i)';
% Q2=[Q2 ones(size(Q2,1),1)] ;
% Q =hb\Q2';
% Q=Q(1:3,:)'
%
% f=orig.x.XYZ(:,i)'
%
% Q-f
%
|
github
|
philippboehmsturm/antx-master
|
xnewproject.m
|
.m
|
antx-master/mritools/ant/xnewproject.m
| 2,841 |
utf_8
|
5e4d3c95835c354517bc4a4c7751597d
|
%% create a new Project for a study
% #yg GUI-NOTE
% for some parameters exist #r "interactive selectors" #w (this selectors appear on the very left side of the parameter as icon)
% to use the "interactive selectors" move coursor to the line of the parameter, if an "interactive selectors" exists
% for this parameter, click it or use [f1] and follow the instructions
%
% #yg PARAMETERS
% #r MANDATORY SPECIFICATIONS:
% specify the projectName: [x.project] : this is an arbitray project-name (example "studyXY")
% specify the data-path : [x.datpath] : this is an existing fullpath-name , the terminal folder-name must be "dat", e.g. "c:\b\study1\dat"
% specifiy thex voxelsize: [x.voxsize] : this is the x,y,z-voxel-resolution (default is [.07 .07 .07])
%
% #b Problem: to work with external data drives on different machines the drive-letter may change
% #b Solution: if there are no explicit changes with respect to the templates and Elastix-parameter-files,
% #b than delete all path-"pointers" (delete, x.wa.refTPM,x.wa.ano ... x.wa.elxParamfile)
% #b -->note: missing parameters will be filled with the defaults
%
% #b if there are no further changes, and you accept the defaults (besides of [x.project,x.datpath,x.voxsize]):
% #b than you can delete all stuff below the x.voxsize -parameter
% #b -->note: missing parameters will be filled with the defaults
%
% #yg SAVE PROJECTFILE
% -(as m-file): hit [ok] --> it is recommended to save the project-file on the upper level of the "dat"-folder
% example: studyfolder is "c:\b\study1"
% thus: datafolder must be "c:\b\study1\dat"
% projectfile can be "c:\b\study1\projectXY.m"
% #yg LOAD PROJECT
% if the projectfile is created, you can decide to immediately to load the projectfile
function xnewproject
%% make new project
[m z]=antconfig(1,'parameter','default','savecb','no');
pat=z.datpath;
[pa fi ext]=fileparts(pat);
if strcmp(fi,'dat')~=1;
errordlg('"datpath" folder must terminate to a folder namd "dat", such as "c:\study-1\dat" ','File Error');
return
end
%% make dir and UI for projectName
if exist(pat)==0
mkdir(pat);
end
[fi pa]=uiputfile('*.m','save configfile (example "project_study1")' ,fullfile(fileparts(pat),'proj.m'));
if pa~=0
pwrite2file(fullfile(pa,fi),m);
end
try;
%explorer(pa) ;
disp(['open folder with new project <a href="matlab: explorer('' ' pa ' '')">' pa '</a>']);% show h<perlink
end
%% questDLG
dlgTitle = '';
dlgQuestion = ['load the new project: ' fullfile(pa,fi) ' now' ];
choice = questdlg(dlgQuestion,dlgTitle,'Yes','No', 'Yes');
if strcmp(choice,'Yes')
cd(pa)
ant; antcb('load',fullfile(pa,fi)) ;
end
|
github
|
philippboehmsturm/antx-master
|
test_atlasreadout.m
|
.m
|
antx-master/mritools/ant/test_atlasreadout.m
| 603 |
utf_8
|
c3ee34538cfcd72548303952bac60921
|
function lut= test_atlasreadout(tmpVOL, ANO2,idxLUT)
% luts,ANO2,tmpVOL
d=tmpVOL>.3;
w=ANO2.*d;
id=unique(w(:));
id(id==0)=[];
w2=w(:);
a=ANO2(:);
tb=zeros(length(id),3);
for i=1:length(id)
tb(i,:)= [ id(i) length(find(w==id(i))) length(find(a==id(i))) ];
end
tb(:,4)=tb(:,2)./tb(:,3);
a1=[idxLUT(:).id]';
for i=1:length(idxLUT)
idxLUT(i).tb=[0 0 0 0];
end
for i=1:size(tb,1)
ix=find(a1==tb(i,1));
idxLUT(ix).tb= [tb(i,:)];
end
lut=idxLUT;
%
% a2=[[idxLUT(:).atlas_id]']
%
% r=intersect(a1,tb(:,1))
% r2=intersect(a2,tb(:,1))
|
github
|
philippboehmsturm/antx-master
|
testgetVoxsize.m
|
.m
|
antx-master/mritools/ant/templateBerlin_hres/testgetVoxsize.m
| 308 |
utf_8
|
1c4e4b05e48cbabccb276fca2e15f8bf
|
function testgetVoxsize
% idxLUT = BrAt_ComputeAreaSize(idxLUT,ANO2,FIBT2);
load myLabels_line178
a=idxLUT
fn=fieldnames(a(1))
t={}
for i=1:length(a)
r=a(i);
t(i,:)= struct2cell(r)';
end
an=ANO2;
s=single(ANO2==70);
for i=10:size(t,1)
c=a(i).children
end
|
github
|
philippboehmsturm/antx-master
|
preadfile2.m
|
.m
|
antx-master/mritools/basic/preadfile2.m
| 3,378 |
utf_8
|
66f380d6bab308aa4ce2da43114a0b57
|
function d=preadfile2(fil)
%___________________________________________________________________________
% % function [dat ]=preadfile(fil);
%___________________________________________________________________________
% Rread file (e.g *.vmrk/*.m/*.txt)
% _________________________________________________________________________
% see also preadfile pwrite2file
%___________________________________________________________________________
%======================1.1 READ=====================================================
fid=fopen(fil);
j=1;
while 1
tline = fgetl(fid);
if ~ischar(tline), break, end
d{j,1}=tline;
j=j+1;
end
fclose(fid);
if exist('d')==0
d=' ';
end
return
%=====================1.2 separate header and real markers (no 'new segments')=================================================
if nargin==3
FSheadend=varargin{1};
FSfileend=varargin{2};
% FSheadend='#DATA BEGINS'; clear HTIS;
% FSfileend='#DATA ENDS'
Fadditheadline=2;
FSline=' ' ;
markALL=char(d);
% markALL(100:7400,:)=[];
%==========================================================================
% llinewise check
%==========================================================================
%=
h=1; k=1;
for j=1:size(markALL)
if h==1 %HEADER
if isempty(findstr(markALL(j,:),FSheadend))==1
header(j,:)=markALL(j,:);
else
h=0;T=j;
end
elseif h==0 %MARKER
if isempty(findstr(markALL(j,:),FSline))==0 &...
isempty(findstr(markALL(j,:),FSfileend))==1;
% disp(markALL(j,:));
mrk{k,:}=markALL(j,:); %
k=k+1;
else
% part=mrk(k,:);
% part
h=999;
end
end
end
%=====================%=====================
% out- 2
%=====================%=====================
dat.header=(header);
dat.dat= (mrk);
% dat.header=char(header);
% dat.dat=char(markALL);
end
%=====================%=====================
% out- 2
%=====================%=====================
dat.all=(d);
% dat.all=char(d);
%#############################################
% if 1
%
% % infmrk.mrktyp=unique(mark(:,1));
% end
% %
% %
% % % BK
% %
% % h=1; k=1;
% % for j=1:size(markALL)
% % if h==1 %HEADER
% % if isempty(findstr(markALL(j,:),'Mk1'))==1
% % header(j,:)=markALL(j,:);
% % else
% % h=0;
% % end
% % elseif h==0 %MARKER
% % if isempty(findstr(markALL(j,:),'Stimulus'))==0; %select ONLY STIMULUS nothing else
% % mrk(k,:)=markALL(j,:); %'no NEW SEGMENTS or RESPONSE'
% % k=k+1;
% % end
% % end
% % end
% %
% %
% % %===================== 1.3 extract mrk and timecolumn as double =================================================
% % for j=1:size(mrk)
% % dum=findstr(mrk(j,:),',');
% % mark(j,:)=[ str2num(mrk(j,dum(1)+2:dum(2)-1)) str2num(mrk(j,dum(2)+1:dum(3)-1)) ];
% % end
% %
% %
% % infmrk.header=header;
% % infmrk.mrkALL=markALL;
% % infmrk.mrktyp=unique(mark(:,1));
|
github
|
philippboehmsturm/antx-master
|
cfg_getfile3.m
|
.m
|
antx-master/mritools/basic/cfg_getfile3.m
| 54,634 |
utf_8
|
91aaf726f873730f5bc19ca90fab8c59
|
function [t,sts] = cfg_getfile2(varargin)
% File selector
% FORMAT [t,sts] = cfg_getfile2(n,typ,mesg,sel,wd,filt,frames)
% n - Number of files
% A single value or a range. e.g.
% 1 - Select one file
% Inf - Select any number of files
% [1 Inf] - Select 1 to Inf files
% [0 1] - select 0 or 1 files
% [10 12] - select from 10 to 12 files
% typ - file type
% 'any' - all files
% 'batch' - SPM batch files (.m, .mat and XML)
% 'dir' - select a directory
% 'image' - Image files (".img" and ".nii")
% Note that it gives the option to select
% individual volumes of the images.
% 'mat' - Matlab .mat files or .txt files (assumed to contain
% ASCII representation of a 2D-numeric array)
% 'mesh' - Mesh files (".gii" and ".mat")
% 'nifti' - NIfTI files without the option to select frames
% 'xml' - XML files
% Other strings act as a filter to regexp. This means
% that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$'
% mesg - a prompt (default 'Select files...')
% sel - list of already selected files
% wd - Directory to start off in
% filt - value for user-editable filter (default '.*')
% frames - Image frame numbers to include (default '1')
%
% t - selected files
% sts - status (1 means OK, 0 means window quit)
%
% FORMAT [t,ind] = cfg_getfile2('Filter',files,typ,filt,frames)
% filter the list of files (cell array) in the same way as the
% GUI would do. There is an additional typ 'extimage' which will match
% images with frame specifications, too. The 'frames' argument
% is currently ignored, i.e. image files will not be filtered out if
% their frame numbers do not match.
% When filtering directory names, the filt argument will be applied to the
% last directory in a path only.
% t returns the filtered list (cell array), ind an index array, such that
% t = files(ind).
%
% FORMAT cpath = cfg_getfile2('CPath',path,cwd)
% function to canonicalise paths: Prepends cwd to relative paths, processes
% '..' & '.' directories embedded in path.
% path - string matrix containing path name
% cwd - current working directory [default '.']
% cpath - conditioned paths, in same format as input path argument
%
% FORMAT [files,dirs]=cfg_getfile2('List',direc,filt)
% Returns files matching the filter (filt) and directories within dire
% direc - directory to search
% filt - filter to select files with (see regexp) e.g. '^w.*\.img$'
% files - files matching 'filt' in directory 'direc'
% dirs - subdirectories of 'direc'
% FORMAT [files,dirs]=cfg_getfile2('ExtList',direc,filt,frames)
% As above, but for selecting frames of 4D NIfTI files
% frames - vector of frames to select (defaults to 1, if not
% specified). If the frame number is Inf, all frames for the
% matching images are listed.
% FORMAT [files,dirs]=cfg_getfile2('FPList',direc,filt)
% FORMAT [files,dirs]=cfg_getfile2('ExtFPList',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to each)
% FORMAT [files,dirs]=cfg_getfile2('FPListRec',direc,filt)
% FORMAT [files,dirs]=cfg_getfile2('ExtFPListRec',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to
% each) and searches through sub directories recursively.
%
% FORMAT cfg_getfile2('prevdirs',dir)
% Add directory dir to list of previous directories.
% FORMAT dirs=cfg_getfile2('prevdirs')
% Retrieve list of previous directories.
%
% This code is based on the file selection dialog in SPM5, with virtual
% file handling turned off.
%____________________________________________________________________________
%% addit struct as 8th. input
%% [1] search recoursively only in specified paths
% w. recpaths: {2x1 cell} : search recoursively only in this paths
% [maskfi,sts] = cfg_getfile2(inf,'any',msg,[],prefdir,'img|nii' ,[],w);
% -->hack in subfct: "select_rec"
%% optional STRUCT INPUT =8th. variable
clear global glob_cfg_getfile2
if length(varargin)==8
global glob_cfg_getfile2;
glob_cfg_getfile2=varargin{8};
if isempty(varargin{7}) ; vardel=1; else; vardel=0; end
varargin(8-vardel:8)=[]; %clear variable again
end
t = {};
sts = false;
if nargin > 0 && ischar(varargin{1})
switch lower(varargin{1})
case {'addvfiles', 'clearvfiles', 'vfiles'}
cfg_message('matlabbatch:deprecated:vfiles', ...
'Trying to use deprecated ''%s'' call.', ...
lower(varargin{1}));
case 'cpath'
cfg_message(nargchk(2,Inf,nargin,'struct'));
t = cpath(varargin{2:end});
sts = true;
case 'filter'
filt = mk_filter(varargin{3:end});
t = varargin{2};
if numel(t) == 1 && isempty(t{1})
sts = 1;
return;
end;
t1 = cell(size(t));
if any(strcmpi(varargin{3},{'dir','extdir'}))
% only filter last directory in path
for k = 1:numel(t)
t{k} = cpath(t{k});
if t{k}(end) == filesep
[p n] = fileparts(t{k}(1:end-1));
else
[p n] = fileparts(t{k});
end
if strcmpi(varargin{3},'extdir')
t1{k} = [n filesep];
else
t1{k} = n;
end
end
else
% only filter filenames, not paths
for k = 1:numel(t)
[p n e] = fileparts(t{k});
t1{k} = [n e];
end
end
[t1,sts1] = do_filter(t1,filt.ext);
[t1,sts2] = do_filter(t1,filt.filt);
sts = sts1(sts2);
t = t(sts);
case {'list', 'fplist', 'extlist', 'extfplist'}
if nargin > 3
frames = varargin{4};
else
frames = 1; % (ignored in listfiles if typ==any)
end;
if regexpi(varargin{1}, 'ext') % use frames descriptor
typ = 'extimage';
else
typ = 'any';
end
filt = mk_filter(typ, varargin{3}, frames);
[t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here)
sts = sts(~(strcmp(sts,'.')|strcmp(sts,'..'))); % remove '.' and '..' entries
if regexpi(varargin{1}, 'fplist') % return full pathnames
direc = cfg_getfile2('cpath', varargin{2});
% remove trailing path separator if present
direc = regexprep(direc, [filesep '$'], '');
if ~isempty(t)
t = strcat(direc, filesep, t);
end
if nargout > 1
% subdirs too
sts = cellfun(@(sts1)cpath(sts1, direc), sts, 'UniformOutput',false);
end
end
case {'fplistrec', 'extfplistrec'}
% list directory
[f1 d1] = cfg_getfile2(varargin{1}(1:end-3),varargin{2:end});
f2 = cell(size(d1));
d2 = cell(size(d1));
for k = 1:numel(d1)
% recurse into sub directories
[f2{k} d2{k}] = cfg_getfile2(varargin{1}, d1{k}, ...
varargin{3:end});
end
t = vertcat(f1, f2{:});
if nargout > 1
sts = vertcat(d1, d2{:});
end
case 'prevdirs',
if nargin > 1
prevdirs(varargin{2});
end;
if nargout > 0 || nargin == 1
t = prevdirs;
sts = true;
end;
otherwise
cfg_message('matlabbatch:usage','Inappropriate usage.');
end
else
[t,sts] = selector(varargin{:});
end
%=======================================================================
%=======================================================================
function [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin)
if nargin<1 || ~isnumeric(n) || numel(n) > 2
n = [0 Inf];
else
if numel(n)==1, n = [n n]; end;
if n(1)>n(2), n = n([2 1]); end;
if ~isfinite(n(1)), n(1) = 0; end;
end
if nargin<2 || ~ischar(typ), typ = 'any'; end;
if nargin<3 || ~(ischar(mesg) || iscellstr(mesg))
mesg = 'Select files...';
elseif iscellstr(mesg)
mesg = char(mesg);
end
if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1}))
already = {};
else
% Add folders of already selected files to prevdirs list
pd1 = cellfun(@(a1)strcat(fileparts(a1),filesep), already, ...
'UniformOutput',false);
prevdirs(pd1);
end
if nargin<5 || isempty(wd) || ~ischar(wd)
if isempty(already)
wd = pwd;
else
wd = fileparts(already{1});
if isempty(wd)
wd = pwd;
end
end;
end
if nargin<6 || ~ischar(filt), filt = '.*'; end;
if nargin<7 || ~(isnumeric(frames) || ischar(frames))
frames = '1';
elseif isnumeric(frames)
frames = char(gencode_rvalue(frames(:)'));
elseif ischar(frames)
try
ev = eval(frames);
if ~isnumeric(ev)
frames = '1';
end
catch
frames = '1';
end
end
ok = 0;
t = '';
sfilt = mk_filter(typ,filt,eval(frames));
[col1,col2,col3,lf,bf] = colours;
% delete old selector, if any
fg = findobj(0,'Tag',mfilename);
if ~isempty(fg)
delete(fg);
end
% create figure
if size(mesg,1)>1
mesg2=mesg(1,:);
else
mesg2=mesg;
end
fg = figure('IntegerHandle','off',...
'Tag',mfilename,...
'Name',mesg2,...
'NumberTitle','off',...
'Units','Pixels',...
'MenuBar','none',...
'DefaultTextInterpreter','none',...
'DefaultUicontrolInterruptible','on',...
'Visible','off');
cfg_onscreen(fg);
set(fg,'Visible','on');
sellines = min([max([n(2) numel(already)]), 4]);
[pselp pcntp pfdp pdirp] = panelpositions(fg, sellines+1);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'position',posinpanel([0 sellines/(sellines+1) 1 1/(sellines+1)],pselp),...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'HorizontalAlignment','left',...
'string','',...%mesg
'tag','msg');
% Selected Files
sel = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0 0 1 sellines/(sellines+1)],pselp),...
lf,...
'Callback',@unselect,...
'tag','selected',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',10000,...
'Min',0,...
'String',already,...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(sel,'uicontextmenu',c0);
uimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all);
% get cwidth for buttons
tmp=uicontrol('style','text','string',repmat('X',[1,50]),bf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
cw = 3*fnp(3)/50;
if strcmpi(typ,'image'),
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 0 0.37 .45],pcntp),...
'Callback',@update_frames,...
'tag','frame',...
lf,...
'BackgroundColor',col1,...
'String',frames,'UserData',eval(frames));
% 'ForegroundGolor',col3,...
end;
% Help
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.02 .5 cw .45],pcntp),...
bf,...
'Callback',@heelp,...
'tag','?',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','?',...
'ToolTipString','Show Help');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.03+cw .5 cw .45],pcntp),...
bf,...
'Callback',@editwin,...
'tag','Ed',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Ed',...
'ToolTipString','Edit Selected Files');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.04+2*cw .5 cw .45],pcntp),...
bf,...
'Callback',@select_rec,...
'tag','Rec',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Rec',...
'ToolTipString','Recursively Select Files with Current Filter');
% Done
dne = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.05+3*cw .5 0.45-3*cw .45],pcntp),...
bf,...
'Callback',@(h,e)delete(h),...
'tag','D',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Done',...
'Enable','off',...
'DeleteFcn',@null);
if numel(already)>=n(1) && numel(already)<=n(2),
set(dne,'Enable','on');
end;
% Filter Button
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.51 .5 0.1 .45],pcntp),...
bf,...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Callback',@clearfilt,...
'String','Filt');
% Filter
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 .5 0.37 .45],pcntp),...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
lf,...
'Callback',@(ob,ev)update(ob),...
'tag','regexp',...
'String',filt,...
'UserData',sfilt);
% Directories
db = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.47 1],pfdp),...
lf,...
'Callback',@click_dir_box,...
'tag','dirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',1,...
'Min',0,...
'String','',...
'UserData',wd,...
'Value',1);
% Files
tmp = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.51 0 0.47 1],pfdp),...
lf,...
'Callback',@click_file_box,...
'tag','files',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'UserData',n,...
'Max',10240,...
'Min',0,...
'String','',...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(tmp,'uicontextmenu',c0);
uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all);
% Drives
if strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'),
% get fh for lists
tmp=uicontrol('style','text','string','X',lf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
fh = 2*fnp(4); % Heuristics: why do we need 2*
sz = get(db,'Position');
sz(4) = sz(4)-fh-2*0.01;
set(db,'Position',sz);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1-fh-0.01 0.10 fh],pfdp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Drive');
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1-fh-0.01 0.37 fh],pfdp),...
lf,...
'Callback',@setdrive,...
'tag','drive',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',listdrives(false),...
'Value',1);
end;
[pd,vl] = prevdirs([wd filesep]);
% Previous dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 .05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','previous',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pd,...
'Value',vl);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Prev');
% Parent dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1/3+.05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','pardirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pardirs(wd));
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Up');
% Directory
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.12 2/3 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@edit_dir,...
'tag','edit',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String','');
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 2/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Dir');
resize_fun(fg);
set(fg, 'ResizeFcn',@resize_fun);
update(sel,wd)
%% paul HACK
%=====================
units=get(gcf,'units');
set(gcf,'units','normalized');
set(gcf,'position',[0.0336 0.1299 0.6070 0.7334]);
%% fontsize
% screensize=get(0,'screensize');
% if screensize(4)<=1024
% fs=8;
% else
% fs=14;
% end
fs=8;
ch=get(gcf,'children');
for i=1:length(ch)
try; set(ch(i),'fontsize',fs);end
end
%%larger selection range
hh=findobj(gcf,'string','Filt');
pos=get(hh,'position');
set(hh,'position',[.01 .32 .1 .02]);
hh=findobj(gcf,'tag','regexp');
pos=get(hh,'position');
set(hh,'position',[.11 .38 .3 .02],'backgroundcolor',[ 0.8392 0.9098 0.8510]);
hh=findobj(gcf,'tag','files');
pos=get(hh,'position');
set(hh,'position',[ 0.5100 0.315 0.4700 0.53]);
%% chnge arangement uf UIcontrols
p=uicontrol('style','edit','max',10,'units','normalized',...
'position',[0.001 .69 .5 .09 ],'style','edit','backgroundcolor',[.8 .8 .8],'foregroundcolor',[0 .6 0],...
'string',cellstr(mesg),'fontsize',14,'fontweight','bold','tag','pmsgbox','horizontalalignment','left' );
set(p,'position',[.001 .59 .5 .19])
hdirs=findobj(gcf,'tag','dirs'); set(hdirs,'position',[0.0200 0.37 0.4700 0.2216]);
hhelp=findobj(gcf,'string','?'); set(hhelp,'position',[ 0.0100 0.325 0.0316 0.0394],'visible','off');
hed=findobj(gcf,'string','Ed'); set(hed,'position',[ 0.00 0.325 0.0316 0.0394]);
hrec=findobj(gcf,'string','Rec'); set(hrec,'position',[ 0.1434 0.325 0.0316 0.0394]);
hre=findobj(gcf,'string','Filt'); set(hre,'position', [ 0.175 0.325 0.05 0.0394]);
hre=findobj(gcf,'tag','regexp'); set(hre,'position', [ 0.22 0.325 0.2 0.0394]);
hre=findobj(gcf,'string','Done'); set(hre,'position',[ 0.42 0.325 0.1 0.0394],'backgroundcolor',[0 .6 0]);
hmsg=findobj(gcf,'tag','msg'); set(hmsg,'position',[0 .25 1 .075])
%% get rec. all filenames-Button
p=uicontrol('style','pushbutton','units','normalized',...
'position',[.0934 .325 .05 .0394 ],'backgroundcolor',[1 1 1],'foregroundcolor',[0 .6 0],...
'string', 'fileSTR' ,'fontsize',12,'fontweight','bold','tag','pmsgbox','horizontalalignment','left', 'tooltip',...
'list all filesname from subfolders (the output can be used as fileFilter)',...
'callback' ,@p_findrecfiles);
set(gcf,'units',units);
set(findobj(gcf,'style','pushbutton'),'fontsize',8);
set(findobj(gcf,'tag','pmsgbox'),'fontsize',8);
ContextMenu=uicontextmenu;
uimenu('Parent',ContextMenu, 'Label','show help in external figure', 'callback', {@cmenuInfo,'showInfo',cellstr(mesg) } ,'ForegroundColor',[0 .5 0]);
set(findobj(gcf,'tag','pmsgbox'),'UIContextMenu',ContextMenu);
%===============paul end======
set(fg,'windowstyle', 'modal');
waitfor(dne);
drawnow;
if ishandle(sel),
t = get(sel,'String');
if isempty(t)
t = {''};
elseif sfilt.code == -1
% canonicalise non-empty folder selection
t = cellfun(@(t1)cpath(t1, pwd), t, 'UniformOutput',false);
end;
ok = 1;
end;
if ishandle(fg), delete(fg); end;
drawnow;
return;
%=======================================================================
function cmenuInfo(he,ho,task,arg)
if strcmp(task,'showInfo')
uhelp(arg);
set(findobj(gcf,'styl','listbox'),'fontsize',8);
end
%=======================================================================
function apos = posinpanel(rpos,ppos)
% Compute absolute positions based on panel position and relative
% position
apos = [ppos(1:2)+ppos(3:4).*rpos(1:2) ppos(3:4).*rpos(3:4)];
%=======================================================================
%=======================================================================
function [pselp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines)
if nargin == 1
na = numel(get(findobj(fg,'Tag','selected'),'String'));
n = get(findobj(fg,'Tag','files'),'Userdata');
sellines = min([max([n(2) na]), 4]);
end
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
% Create dummy text to estimate character height
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',lf);
lfh = 1.05*get(t,'extent');
delete(t)
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',bf);
bfh = 1.05*get(t,'extent');
delete(t)
% panel heights
% 3 lines for directory, parent and prev directory list
% variable height for dir/file navigation
% 2 lines for buttons, filter etc
% sellines plus scrollbar for selected files
pselh = sellines*lfh(4) + 1.2*lfh(4);
pselp = [0 0 1 pselh];
pcnth = 2*bfh(4);
pcntp = [0 pselh 1 pcnth];
pdirh = 3*lfh(4);
pdirp = [0 1-pdirh 1 pdirh];
pfdh = 1-(pselh+pcnth+pdirh);
pfdp = [0 pselh+pcnth 1 pfdh];
%=======================================================================
%=======================================================================
function null(varargin)
%=======================================================================
%=======================================================================
function omsg = msg(ob,str)
ob = sib(ob,'msg');
omsg = get(ob,'String');
set(ob,'String',str);
if nargin>=3,
set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold');
else
set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal');
end;
drawnow;
return;
%=======================================================================
%=======================================================================
function setdrive(ob,varargin)
st = get(ob,'String');
vl = get(ob,'Value');
update(ob,st{vl});
return;
%=======================================================================
%=======================================================================
function resize_fun(fg,varargin)
% do nothing
return;
[pselp pcntp pfdp pdirp] = panelpositions(fg);
set(findobj(fg,'Tag','msg'), 'Position',pselp);
set(findobj(fg,'Tag','pcnt'), 'Position',pcntp);
set(findobj(fg,'Tag','pfd'), 'Position',pfdp);
set(findobj(fg,'Tag','pdir'), 'Position',pdirp);
return;
%=======================================================================
%=======================================================================
function [d,mch] = prevdirs(d)
persistent pd
if ~iscell(pd), pd = {}; end;
if nargin == 0
d = pd;
else
if ~iscell(d)
d = cellstr(d);
end
d = unique(d(:));
mch = cellfun(@(d1)find(strcmp(d1,pd)), d, 'UniformOutput',false);
sel = cellfun(@isempty, mch);
npd = numel(pd);
pd = [pd(:);d(sel)];
mch = [mch{~sel} npd+(1:nnz(sel))];
d = pd;
end
return;
%=======================================================================
%=======================================================================
function pd = pardirs(wd)
if ispc
fs = '\\';
else
fs = filesep;
end
pd1 = textscan(wd,'%s','delimiter',fs,'MultipleDelimsAsOne',1);
if ispc
pd = cell(size(pd1{1}));
pd{end} = pd1{1}{1};
for k = 2:numel(pd1{1})
pd{end-k+1} = fullfile(pd1{1}{1:k},filesep);
end
else
pd = cell(numel(pd1{1})+1,1);
pd{end} = filesep;
for k = 1:numel(pd1{1})
pd{end-k} = fullfile(filesep,pd1{1}{1:k},filesep);
end
end
%=======================================================================
%=======================================================================
function clearfilt(ob,varargin)
set(sib(ob,'regexp'),'String','.*');
update(ob);
return;
%=======================================================================
%=======================================================================
function click_dir_list(ob,varargin)
vl = get(ob,'Value');
ls = get(ob,'String');
update(ob,deblank(ls{vl}));
return;
%=======================================================================
%=======================================================================
function edit_dir(ob,varargin)
update(ob,get(ob,'String'));
return;
%=======================================================================
%=======================================================================
function c = get_current_char(lb)
fg = sib(lb, mfilename);
c = get(fg, 'CurrentCharacter');
if ~isempty(c)
% reset CurrentCharacter
set(fg, 'CurrentCharacter', char(13));
end
%=======================================================================
%=======================================================================
function click_dir_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c,char(13))
vl = get(lb,'Value');
str = get(lb,'String');
pd = get(sib(lb,'edit'),'String');
while ~isempty(pd) && strcmp(pd(end),filesep)
pd=pd(1:end-1); % Remove any trailing fileseps
end
sel = str{vl};
if strcmp(sel,'..'), % Parent directory
[dr odr] = fileparts(pd);
elseif strcmp(sel,'.'), % Current directory
dr = pd;
odr = '';
else
dr = fullfile(pd,sel);
odr = '';
end;
update(lb,dr);
if ~isempty(odr)
% If moving up one level, try to set focus on previously visited
% directory
cdrs = get(lb, 'String');
dind = find(strcmp(odr, cdrs));
if ~isempty(dind)
set(lb, 'Value',dind(1));
end
end
end
return;
%=======================================================================
%=======================================================================
function re = getfilt(ob)
ob = sib(ob,'regexp');
ud = get(ob,'UserData');
re = struct('code',ud.code,...
'frames',get(sib(ob,'frame'),'UserData'),...
'ext',{ud.ext},...
'filt',{{get(sib(ob,'regexp'),'String')}});
return;
%=======================================================================
%=======================================================================
function update(lb,dr)
lb = sib(lb,'dirs');
if nargin<2 || isempty(dr) || ~ischar(dr)
dr = get(lb,'UserData');
end;
if ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'))
dr = [filesep dr filesep];
else
dr = [dr filesep];
end;
dr(strfind(dr,[filesep filesep])) = [];
[f,d] = listfiles(dr,getfilt(lb));
if isempty(d),
dr = get(lb,'UserData');
[f,d] = listfiles(dr,getfilt(lb));
else
set(lb,'UserData',dr);
end;
set(lb,'Value',1,'String',d);
set(sib(lb,'files'),'Value',1,'String',f);
set(sib(lb,'pardirs'),'String',pardirs(dr),'Value',1);
[ls,mch] = prevdirs(dr);
set(sib(lb,'previous'),'String',ls,'Value',mch);
set(sib(lb,'edit'),'String',dr);
if numel(dr)>1 && dr(2)==':',
str = char(get(sib(lb,'drive'),'String'));
mch = find(lower(str(:,1))==lower(dr(1)));
if ~isempty(mch),
set(sib(lb,'drive'),'Value',mch);
end;
end;
return;
%=======================================================================
%=======================================================================
function update_frames(lb,varargin)
str = get(lb,'String');
%r = get(lb,'UserData');
try
r = eval(['[',str,']']);
catch
msg(lb,['Failed to evaluate "' str '".'],'r');
beep;
return;
end;
if ~isnumeric(r),
msg(lb,['Expression non-numeric "' str '".'],'r');
beep;
else
set(lb,'UserData',r);
msg(lb,'');
update(lb);
end;
%=======================================================================
%=======================================================================
function select_all(ob,varargin)
lb = sib(ob,'files');
set(lb,'Value',1:numel(get(lb,'String')));
drawnow;
click_file_box(lb);
return;
%=======================================================================
%=======================================================================
function click_file_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c, char(13))
vlo = get(lb,'Value');
if isempty(vlo),
msg(lb,'Nothing selected');
return;
end;
lim = get(lb,'UserData');
ob = sib(lb,'selected');
str3 = get(ob,'String');
str = get(lb,'String');
lim1 = min([max([lim(2)-numel(str3),0]),numel(vlo)]);
if lim1==0,
msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']);
beep;
set(sib(lb,'D'),'Enable','on');
return;
end;
vl = vlo(1:lim1);
msk = false(size(str,1),1);
if vl>0, msk(vl) = true; else msk = []; end;
str1 = str( msk);
str2 = str(~msk);
dr = get(sib(lb,'edit'), 'String');
str1 = strcat(dr, str1);
set(lb,'Value',min([vl(1),numel(str2)]),'String',str2);
r = (1:numel(str1))+numel(str3);
str3 = [str3(:);str1(:)];
set(ob,'String',str3,'Value',r);
if numel(vlo)>lim1,
msg(lb,['Retained ' num2str(lim1) '/' num2str(numel(vlo))...
' of selection.']);
beep;
elseif isfinite(lim(2))
if lim(1)==lim(2),
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(2)) ' files.']);
else
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if size(str3,1) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Selected ' num2str(numel(str3)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str3)>=lim(1),
set(sib(lb,'D'),'Enable','on');
end;
end
return;
%=======================================================================
%=======================================================================
function obj = sib(ob,tag)
persistent fg;
if isempty(fg) || ~ishandle(fg)
fg = findobj(0,'Tag',mfilename);
end
obj = findobj(fg,'Tag',tag);
return;
%if isempty(obj),
% cfg_message('matlabbatch:usage',['Can''t find object with tag "' tag '".']);
%elseif length(obj)>1,
% cfg_message('matlabbatch:usage',['Found ' num2str(length(obj)) ' objects with tag "' tag '".']);
%end;
%return;
%=======================================================================
%=======================================================================
function unselect(lb,varargin)
vl = get(lb,'Value');
if isempty(vl), return; end;
str = get(lb,'String');
msk = true(numel(str),1);
if vl~=0, msk(vl) = false; end;
str2 = str(msk);
set(lb,'Value',min(vl(1),numel(str2)),'String',str2);
lim = get(sib(lb,'files'),'UserData');
if numel(str2)>= lim(1) && numel(str2)<= lim(2),
set(sib(lb,'D'),'Enable','on');
else
set(sib(lb,'D'),'Enable','off');
end;
if numel(str2) == 1, ss1 = ''; else ss1 = 's'; end;
%msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']);
if numel(vl) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ...
num2str(numel(str2)) ' file' ss1 ' remaining.']);
return;
%=======================================================================
%=======================================================================
function unselect_all(ob,varargin)
lb = sib(ob,'selected');
set(lb,'Value',[],'String',{},'ListBoxTop',1);
msg(lb,'Unselected all files.');
lim = get(sib(lb,'files'),'UserData');
if lim(1)>0, set(sib(lb,'D'),'Enable','off'); end;
return;
%=======================================================================
%=======================================================================
function [f,d] = listfiles(dr,filt)
try
ob = sib(gco,'msg');
domsg = ~isempty(ob);
catch
domsg = false;
end
if domsg
omsg = msg(ob,'Listing directory...');
end
if nargin<2, filt = ''; end;
if nargin<1, dr = '.'; end;
de = dir(dr);
if ~isempty(de),
d = {de([de.isdir]).name};
if ~any(strcmp(d, '.'))
d = [{'.'}, d(:)'];
end;
if filt.code~=-1,
f = {de(~[de.isdir]).name};
else
% f = d(3:end);
f = d;
end;
else
d = {'.','..'};
f = {};
end;
if domsg
msg(ob,['Filtering ' num2str(numel(f)) ' files...']);
end
f = do_filter(f,filt.ext);
f = do_filter(f,filt.filt);
ii = cell(1,numel(f));
if filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1),
if domsg
msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);
end
for i=1:numel(f),
try
ni = nifti(fullfile(dr,f{i}));
dm = [ni.dat.dim 1 1 1 1 1];
d4 = (1:dm(4))';
catch
d4 = 1;
end;
if all(isfinite(filt.frames))
msk = false(size(filt.frames));
for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end;
ii{i} = filt.frames(msk);
else
ii{i} = d4;
end;
end
elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1),
for i=1:numel(f),
ii{i} = 1;
end;
end;
if domsg
msg(ob,['Listing ' num2str(numel(f)) ' files...']);
end
[f,ind] = sortrows(f(:));
ii = ii(ind);
msk = true(1,numel(f));
for i=2:numel(f),
if strcmp(f{i-1},f{i}),
if filt.code==1,
tmp = sort([ii{i}(:) ; ii{i-1}(:)]);
tmp(~diff(tmp,1)) = [];
ii{i} = tmp;
end;
msk(i-1) = false;
end;
end;
f = f(msk);
if filt.code==1,
% Combine filename and frame number(s)
ii = ii(msk);
nii = cellfun(@numel, ii);
c = cell(sum(nii),1);
fi = cell(numel(f),1);
for k = 1:numel(fi)
fi{k} = k*ones(1,nii(k));
end
ii = [ii{:}];
fi = [fi{:}];
for i=1:numel(c),
c{i} = sprintf('%s,%d', f{fi(i)}, ii(i));
end;
f = c;
elseif filt.code==-1,
fs = filesep;
for i=1:numel(f),
f{i} = [f{i} fs];
end;
end;
f = f(:);
d = unique(d(:));
if domsg
msg(ob,omsg);
end
return;
%=======================================================================
%=======================================================================
function [f,ind] = do_filter(f,filt)
t2 = false(numel(f),1);
filt_or = sprintf('(%s)|',filt{:});
t1 = regexp(f,filt_or(1:end-1));
if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;
for i=1:numel(t1),
t2(i) = ~isempty(t1{i});
end;
ind = find(t2);
f = f(t2);
return;
%=======================================================================
%=======================================================================
function heelp(ob,varargin)
[col1,col2,col3,fn] = colours;
fg = sib(ob,mfilename);
t = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.01 0.01 0.98 0.98],...
fn,...
'BackgroundColor',col2,...
'ForegroundColor',col3,...
'Max',0,...
'Min',0,...
'tag','HelpWin',...
'String',' ');
c0 = uicontextmenu('Parent',fg);
set(t,'uicontextmenu',c0);
uimenu('Label','Done', 'Parent',c0,'Callback',@helpclear);
str = cfg_justify(t, {[...
'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). '],...
'',[...
'The panel at the bottom shows files that are already selected. ',...
'Clicking a selected file will un-select it. To un-select several, you can ',...
'drag the cursor over the files, and they will be gone on release. ',...
'You can use the right mouse button to un-select everything.'],...
'',[...
'Directories are navigated by editing the name of the current directory (where it says "Dir"), ',...
'by going to one of the previously entered directories ("Prev"), ',...
'by going to one of the parent directories ("Up") or by navigating around ',...
'the parent or subdirectories listed in the left side panel.'],...
'',[...
'Files matching the filter ("Filt") are shown in the panel on the right. ',...
'These can be selected by clicking or dragging. Use the right mouse button if ',...
'you would like to select all files. Note that when selected, the files disappear ',...
'from this panel. They can be made to reappear by re-specifying the directory ',...
'or the filter. '],...
'',[...
'Both directory and file lists can also be browsed by typing the leading ',...
'character(s) of a directory or file name.'],...
'',[...
'Note that the syntax of the filter differs from that used by most other file selectors. ',...
'The filter works using so called ''regular expressions''. Details can be found in the ',...
'MATLAB help text on ''regexp''. ',...
'The following is a list of symbols with special meaning for filtering the filenames:'],...
' ^ start of string',...
' $ end of string',...
' . any character',...
' \ quote next character',...
' * match zero or more',...
' + match one or more',...
' ? match zero or one, or match minimally',...
' {} match a range of occurrances',...
' [] set of characters',...
' [^] exclude a set of characters',...
' () group subexpression',...
' \w match word [a-z_A-Z0-9]',...
' \W not a word [^a-z_A-Z0-9]',...
' \d match digit [0-9]',...
' \D not a digit [^0-9]',...
' \s match white space [ \t\r\n\f]',...
' \S not a white space [^ \t\r\n\f]',...
' \<WORD\> exact word match',...
'',[...
'Individual time frames of image files can also be selected. The frame filter ',...
'allows specified frames to be shown, which is useful for image files that ',...
'contain multiple time points. If your images are only single time point, then ',...
'reading all the image headers can be avoided by specifying a frame filter of "1". ',...
'The filter should contain a list of integers indicating the frames to be used. ',...
'This can be generated by e.g. "1:100", or "1:2:100".'],...
'',[...
'The recursive selection button (Rec) allows files matching the regular expression to ',...
'be recursively selected. If there are many directories to search, then this can take ',...
'a while to run.'],...
'',[...
'There is also an edit button (Ed), which allows you to edit your selection of files. ',...
'When you are done, then use the menu-button of your mouse to either cancel or accept your changes.'],''});
set(t,'String',str);
return;
%=======================================================================
%=======================================================================
function helpclear(ob,varargin)
ob = get(ob,'Parent');
ob = get(ob,'Parent');
ob = findobj(ob,'Tag','HelpWin');
delete(ob);
%=======================================================================
%=======================================================================
function t = cpath(t,d)
switch filesep,
case '/',
mch = '^/';
fs = '/';
fs1 = '/';
case '\',
mch = '^.:\\';
fs = '\';
fs1 = '\\';
otherwise;
cfg_message('matlabbatch:usage','What is this filesystem?');
end
if isempty(regexp(t,mch,'once')),
if (nargin<2)||isempty(d), d = pwd; end;
t = [d fs t];
end;
% Replace occurences of '/./' by '/' (problems with e.g. /././././././')
re = [fs1 '\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs);
end;
t = regexprep(t,[fs1 '\.' '$'], fs);
% Replace occurences of '/abc/../' by '/'
re = [fs1 '[^' fs1 ']+' fs1 '\.\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs,'once');
end;
t = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\.\.' '$'],fs,'once');
% Replace '//'
t = regexprep(t,[fs1 '+'], fs);
%=======================================================================
%=======================================================================
function editwin(ob,varargin)
[col1,col2,col3,lf,bf] = colours;
fg = gcbf;
lb = sib(ob,'selected');
str = get(lb,'String');
ac = allchild(fg);
acv = get(ac,'Visible');
h = uicontrol(fg,...
'Style','Edit',...
'units','normalized',...
'String',str,...
lf,...
'Max',2,...
'Tag','EditWindow',...
'HorizontalAlignment','Left',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Position',[0.01 0.08 0.98 0.9],...
'Userdata',struct('ac',{ac},'acv',{acv}));
ea = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.01 .01,.32,.07],...
bf,...
'Callback',@editdone,...
'tag','EditWindowAccept',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Accept');
ee = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.34 .01,.32,.07],...
bf,...
'Callback',@editeval,...
'tag','EditWindowEval',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Eval');
ec = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.67 .01,.32,.07],...
bf,...
'Callback',@editclear,...
'tag','EditWindowCancel',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Cancel');
set(ac,'visible','off');
%=======================================================================
%=======================================================================
function editeval(ob,varargin)
ob = get(ob, 'Parent');
ob = sib(ob, 'EditWindow');
str = get(ob, 'String');
if ~isempty(str)
[out,sts] = cfg_eval_valedit(char(str));
if sts && (iscellstr(out) || ischar(out))
set(ob, 'String', cellstr(out));
else
fgc = get(ob, 'ForegroundColor');
set(ob, 'ForegroundColor', 'red');
pause(1);
set(ob, 'ForegroundColor', fgc);
end
end
%=======================================================================
%=======================================================================
function editdone(ob,varargin)
ob = get(ob,'Parent');
ob = sib(ob,'EditWindow');
str = cellstr(get(ob,'String'));
if isempty(str) || isempty(str{1})
str = {};
else
dstr = deblank(str);
if ~isequal(str, dstr)
c = questdlg(['Some of the filenames contain trailing blanks. This may ' ...
'be due to copy/paste of strings between MATLAB and the ' ...
'edit window. Do you want to remove any trailing blanks?'], ...
'Trailing Blanks in Filenames', ...
'Remove', 'Keep', 'Remove');
switch lower(c)
case 'remove'
str = dstr;
end
end
filt = getfilt(ob);
if filt.code >= 0 % filter files, but not dirs
[p,n,e] = cellfun(@fileparts, str, 'uniformoutput',false);
fstr = strcat(n, e);
[fstr1,fsel] = do_filter(fstr, filt.ext);
str = str(fsel);
end
end
lim = get(sib(ob,'files'),'UserData');
if numel(str)>lim(2),
msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']);
beep;
str = str(1:lim(2));
elseif isfinite(lim(2)),
if lim(1)==lim(2),
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']);
else
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if numel(str) == 1, ss = ''; else ss = 's'; end;
msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
set(sib(ob,'selected'),'String',str,'Value',[]);
acs = get(ob,'Userdata');
fg = gcbf;
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function editclear(ob,varargin)
fg = gcbf;
acs = get(findobj(fg,'Tag','EditWindow'),'Userdata');
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function [c1,c2,c3,lf,bf] = colours
c1 = [1 1 1];
c2 = [1 1 1];
c3 = [0 0 0];
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
if isempty(lf)
lf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
if isempty(bf)
bf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
%=======================================================================
%% paul HAck
function p_findrecfiles(do,varg)
ob=findobj(gcf,'tag','Rec');
start = get(sib(ob,'edit'),'String');
filt = get(sib(ob,'regexp'),'Userdata');
filt.filt = {get(sib(ob,'regexp'), 'String')};
fob = sib(ob,'frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
% flt=struct('code' ,0, 'frames', [], 'ext', {'.*'}, 'filt', '{''img|nii''}' )
try
global glob_cfg_getfile2
if ~isempty(glob_cfg_getfile2)
if isfield(glob_cfg_getfile2, 'recpaths')
selx={};
for i=1:length(glob_cfg_getfile2.recpaths)
selx=[ selx ; select_rec1( glob_cfg_getfile2.recpaths{i} , filt) ];
end
selx;
% else
% hdirlb=findobj(gcf,'tag','dirs')
end
% filetags=regexprep(selx,'.*\','')
filetags=repmat({''},length(selx),1);
for i=1:length(selx)
[pa fi ext]=fileparts(selx{i});
[pa2 fi2]=fileparts(pa);
fi2=regexprep([fi ext], [fi2 '|' fi2(2:end)],'' );
filetags{i}=fi2;
end
files=sort((filetags));
[files2,junk,ind] = unique(files);
freqs = histc(ind,1:numel(files2));
freqs=cellstr(num2str(freqs));
files3=cellfun(@(x, y) [ '(' y ') ' x ],files2,freqs,'un',0);
[is ix]=sort(freqs); %sort accor frequency
files4=flipud(files3(ix));
% ids=selector(files4);
ids=selector(files4);
ids2=regexprep(files4([ids]),'(\s*\d*\)\s*',''); %remove filecounting, i.e. "( 34 ) "
hflt= findobj(gcf,'tag','regexp');
filters=cell2str(ids2,'|^') ;
filters=['^' filters];
set(hflt, 'string', filters );
% uhelp(flipud(files3(ix))) ;
%uhelp(files3) ;
end
end
%=======================================================================
function select_rec(ob, varargin)
start = get(sib(ob,'edit'),'String');
filt = get(sib(ob,'regexp'),'Userdata');
filt.filt = {get(sib(ob,'regexp'), 'String')};
fob = sib(ob,'frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
ptr = get(gcbf,'Pointer');
try
%% PAUL hack
try
global glob_cfg_getfile2
if ~isempty(glob_cfg_getfile2)
if isfield(glob_cfg_getfile2, 'recpaths')
selx={};
for i=1:length(glob_cfg_getfile2.recpaths)
selx=[ selx ; select_rec1( glob_cfg_getfile2.recpaths{i} ,filt) ];
end
sel=selx;
end
set(gcbf,'Pointer','watch');
else
sel = select_rec1(start,filt);
end
catch
sel = select_rec1(start,filt);
end
catch
set(gcbf,'Pointer',ptr);
sel = {};
end;
set(gcbf,'Pointer',ptr);
already= get(sib(ob,'selected'),'String');
fb = sib(ob,'files');
lim = get(fb,'Userdata');
limsel = min(lim(2)-size(already,1),size(sel,1));
set(sib(ob,'selected'),'String',[already(:);sel(1:limsel)],'Value',[]);
msg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1)));
if ~isfinite(lim(1)) || size(sel,1)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
%=======================================================================
%=======================================================================
function sel=select_rec1(cdir,filt)
sel={};
[t,d] = listfiles(cdir,filt);
if ~isempty(t)
sel = strcat([cdir,filesep],t);
end;
for k = 1:numel(d)
if ~any(strcmp(d{k},{'.','..'}))
sel1 = select_rec1(fullfile(cdir,d{k}),filt);
sel = [sel(:); sel1(:)];
end;
end;
%=======================================================================
%=======================================================================
function sfilt=mk_filter(typ,filt,frames)
if nargin<3, frames = 1; end;
if nargin<2, filt = '.*'; end;
if nargin<1, typ = 'any'; end;
switch lower(typ),
case {'any','*'}, code = 0; ext = {'.*'};
case {'image'}, code = 1; ext = {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$','.*\.NII(,\d+){0,2}$','.*\.IMG(,\d+){0,2}$'};
case {'mesh'}, code = 0; ext = {'.*\.gii$','.*\.GII$','.*\.mat$','.*\.MAT$'};
case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'};
case {'gifti'}, code = 0; ext = {'.*\.gii$','.*\.GII$'};
case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,2}$',...
'.*\.img(,[0-9]*){0,2}$',...
'.*\.NII(,[0-9]*){0,2}$',...
'.*\.IMG(,[0-9]*){0,2}$'};
case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'};
case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.txt','.*\.TXT'};
case {'batch'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.m$','.*\.M$','.*\.xml$','.*\.XML$'};
case {'dir'}, code =-1; ext = {'.*'};
case {'extdir'}, code =-1; ext = {['.*' filesep '$']};
otherwise, code = 0; ext = {typ};
end;
sfilt = struct('code',code,'frames',frames,'ext',{ext},...
'filt',{{filt}});
%=======================================================================
%=======================================================================
function drivestr = listdrives(reread)
persistent mydrivestr;
if isempty(mydrivestr) || reread
driveLett = strcat(cellstr(char(('C':'Z')')), ':');
dsel = false(size(driveLett));
for i=1:numel(driveLett)
dsel(i) = exist([driveLett{i} '\'],'dir')~=0;
end
mydrivestr = driveLett(dsel);
end;
drivestr = mydrivestr;
%=======================================================================
%=======================================================================
function varargout = cfg_onscreen(fg)
% Move figure on the screen containing the mouse
% cfg_onscreen(fg) - move figure fg on the screen containing the mouse
% pos = cfg_onscreen(fg) - compute position of figure, do not move it
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_onscreen.m 4033 2010-08-04 15:53:35Z volkmar $
rev = '$Rev: 4033 $';
% save figure units - use pixels here
units = get(fg,'Units');
set(fg,'Units','pixels');
Rect = get(fg,'Position');
S0 = get(0,'MonitorPosition');
if size(S0,1) > 1 % Multiple Monitors
%-Use Monitor containing the Pointer
pl = get(0,'PointerLocation');
w = find(pl(1)>=S0(:,1) & pl(1)<S0(:,1)+S0(:,3)-1 &...
pl(2)>=S0(:,2) & pl(2)<S0(:,2)+S0(:,4));
if numel(w)~=1, w = 1; end
S0 = S0(w,:);
end
Rect(1) = S0(1) + (S0(3) - Rect(3))/2;
Rect(2) = S0(2) + (S0(4) - Rect(4))/2;
if nargout == 0
set(fg, 'Position',Rect);
else
varargout{1} = Rect;
end
set(fg,'Units',units);
|
github
|
philippboehmsturm/antx-master
|
cfg_getfile2.m
|
.m
|
antx-master/mritools/basic/cfg_getfile2.m
| 55,020 |
utf_8
|
32241ea18ea3aa966a282f90f9b3996b
|
function [t,sts] = cfg_getfile2(varargin)
% File selector2
% FORMAT [t,sts] = cfg_getfile2(n,typ,mesg,sel,wd,filt,frames)
% n - Number of files
% A single value or a range. e.g.
% 1 - Select one file
% Inf - Select any number of files
% [1 Inf] - Select 1 to Inf files
% [0 1] - select 0 or 1 files
% [10 12] - select from 10 to 12 files
% typ - file type
% 'any' - all files
% 'batch' - SPM batch files (.m, .mat and XML)
% 'dir' - select a directory
% 'image' - Image files (".img" and ".nii")
% Note that it gives the option to select
% individual volumes of the images.
% 'mat' - Matlab .mat files or .txt files (assumed to contain
% ASCII representation of a 2D-numeric array)
% 'mesh' - Mesh files (".gii" and ".mat")
% 'nifti' - NIfTI files without the option to select frames
% 'xml' - XML files
% Other strings act as a filter to regexp. This means
% that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$'
% mesg - a prompt (default 'Select files...')
% sel - list of already selected files
% wd - Directory to start off in
% filt - value for user-editable filter (default '.*')
% frames - Image frame numbers to include (default '1')
%
% t - selected files
% sts - status (1 means OK, 0 means window quit)
%
% FORMAT [t,ind] = cfg_getfile2('Filter',files,typ,filt,frames)
% filter the list of files (cell array) in the same way as the
% GUI would do. There is an additional typ 'extimage' which will match
% images with frame specifications, too. The 'frames' argument
% is currently ignored, i.e. image files will not be filtered out if
% their frame numbers do not match.
% When filtering directory names, the filt argument will be applied to the
% last directory in a path only.
% t returns the filtered list (cell array), ind an index array, such that
% t = files(ind).
%
% FORMAT cpath = cfg_getfile2('CPath',path,cwd)
% function to canonicalise paths: Prepends cwd to relative paths, processes
% '..' & '.' directories embedded in path.
% path - string matrix containing path name
% cwd - current working directory [default '.']
% cpath - conditioned paths, in same format as input path argument
%
% FORMAT [files,dirs]=cfg_getfile2('List',direc,filt)
% Returns files matching the filter (filt) and directories within dire
% direc - directory to search
% filt - filter to select files with (see regexp) e.g. '^w.*\.img$'
% files - files matching 'filt' in directory 'direc'
% dirs - subdirectories of 'direc'
% FORMAT [files,dirs]=cfg_getfile2('ExtList',direc,filt,frames)
% As above, but for selecting frames of 4D NIfTI files
% frames - vector of frames to select (defaults to 1, if not
% specified). If the frame number is Inf, all frames for the
% matching images are listed.
% FORMAT [files,dirs]=cfg_getfile2('FPList',direc,filt)
% FORMAT [files,dirs]=cfg_getfile2('ExtFPList',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to each)
% FORMAT [files,dirs]=cfg_getfile2('FPListRec',direc,filt)
% FORMAT [files,dirs]=cfg_getfile2('ExtFPListRec',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to
% each) and searches through sub directories recursively.
%
% FORMAT cfg_getfile2('prevdirs',dir)
% Add directory dir to list of previous directories.
% FORMAT dirs=cfg_getfile2('prevdirs')
% Retrieve list of previous directories.
%
% This code is based on the file selection dialog in SPM5, with virtual
% file handling turned off.
%____________________________________________________________________________
%% addit struct as 8th. input
%% [1] search recoursively only in specified paths
% w. recpaths: {2x1 cell} : search recoursively only in this paths
% [maskfi,sts] = cfg_getfile2(inf,'any',msg,[],prefdir,'img|nii' ,[],w);
% -->hack in subfct: "select_rec"
%% optional STRUCT INPUT =8th. variable
clear global glob_cfg_getfile2
if length(varargin)==8
global glob_cfg_getfile2;
glob_cfg_getfile2=varargin{8};
if isempty(varargin{7}) ; vardel=1; else; vardel=0; end
varargin(8-vardel:8)=[]; %clear variable again
end
t = {};
sts = false;
if nargin > 0 && ischar(varargin{1})
switch lower(varargin{1})
case {'addvfiles', 'clearvfiles', 'vfiles'}
cfg_message('matlabbatch:deprecated:vfiles', ...
'Trying to use deprecated ''%s'' call.', ...
lower(varargin{1}));
case 'cpath'
cfg_message(nargchk(2,Inf,nargin,'struct'));
t = cpath(varargin{2:end});
sts = true;
case 'filter'
filt = mk_filter(varargin{3:end});
t = varargin{2};
if numel(t) == 1 && isempty(t{1})
sts = 1;
return;
end;
t1 = cell(size(t));
if any(strcmpi(varargin{3},{'dir','extdir'}))
% only filter last directory in path
for k = 1:numel(t)
t{k} = cpath(t{k});
if t{k}(end) == filesep
[p n] = fileparts(t{k}(1:end-1));
else
[p n] = fileparts(t{k});
end
if strcmpi(varargin{3},'extdir')
t1{k} = [n filesep];
else
t1{k} = n;
end
end
else
% only filter filenames, not paths
for k = 1:numel(t)
[p n e] = fileparts(t{k});
t1{k} = [n e];
end
end
[t1,sts1] = do_filter(t1,filt.ext);
[t1,sts2] = do_filter(t1,filt.filt);
sts = sts1(sts2);
t = t(sts);
case {'list', 'fplist', 'extlist', 'extfplist'}
if nargin > 3
frames = varargin{4};
else
frames = 1; % (ignored in listfiles if typ==any)
end;
if regexpi(varargin{1}, 'ext') % use frames descriptor
typ = 'extimage';
else
typ = 'any';
end
filt = mk_filter(typ, varargin{3}, frames);
[t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here)
sts = sts(~(strcmp(sts,'.')|strcmp(sts,'..'))); % remove '.' and '..' entries
if regexpi(varargin{1}, 'fplist') % return full pathnames
direc = cfg_getfile2('cpath', varargin{2});
% remove trailing path separator if present
direc = regexprep(direc, [filesep '$'], '');
if ~isempty(t)
t = strcat(direc, filesep, t);
end
if nargout > 1
% subdirs too
sts = cellfun(@(sts1)cpath(sts1, direc), sts, 'UniformOutput',false);
end
end
case {'fplistrec', 'extfplistrec'}
% list directory
[f1 d1] = cfg_getfile2(varargin{1}(1:end-3),varargin{2:end});
f2 = cell(size(d1));
d2 = cell(size(d1));
for k = 1:numel(d1)
% recurse into sub directories
[f2{k} d2{k}] = cfg_getfile2(varargin{1}, d1{k}, ...
varargin{3:end});
end
t = vertcat(f1, f2{:});
if nargout > 1
sts = vertcat(d1, d2{:});
end
case 'prevdirs',
if nargin > 1
prevdirs(varargin{2});
end;
if nargout > 0 || nargin == 1
t = prevdirs;
sts = true;
end;
otherwise
cfg_message('matlabbatch:usage','Inappropriate usage.');
end
else
[t,sts] = selector2(varargin{:});
end
%=======================================================================
%=======================================================================
function [t,ok] = selector2(n,typ,mesg,already,wd,filt,frames,varargin)
if nargin<1 || ~isnumeric(n) || numel(n) > 2
n = [0 Inf];
else
if numel(n)==1, n = [n n]; end;
if n(1)>n(2), n = n([2 1]); end;
if ~isfinite(n(1)), n(1) = 0; end;
end
if nargin<2 || ~ischar(typ), typ = 'any'; end;
if nargin<3 || ~(ischar(mesg) || iscellstr(mesg))
mesg = 'Select files...';
elseif iscellstr(mesg)
mesg = char(mesg);
end
if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1}))
already = {};
else
% Add folders of already selected files to prevdirs list
pd1 = cellfun(@(a1)strcat(fileparts(a1),filesep), already, ...
'UniformOutput',false);
prevdirs(pd1);
end
if nargin<5 || isempty(wd) || ~ischar(wd)
if isempty(already)
wd = pwd;
else
wd = fileparts(already{1});
if isempty(wd)
wd = pwd;
end
end;
end
if nargin<6 || ~ischar(filt), filt = '.*'; end;
if nargin<7 || ~(isnumeric(frames) || ischar(frames))
frames = '1';
elseif isnumeric(frames)
frames = char(gencode_rvalue(frames(:)'));
elseif ischar(frames)
try
ev = eval(frames);
if ~isnumeric(ev)
frames = '1';
end
catch
frames = '1';
end
end
ok = 0;
t = '';
sfilt = mk_filter(typ,filt,eval(frames));
[col1,col2,col3,lf,bf] = colours;
% delete old selector2, if any
fg = findobj(0,'Tag',mfilename);
if ~isempty(fg)
delete(fg);
end
% create figure
if size(mesg,1)>1
mesg2=mesg(1,:);
else
mesg2=mesg;
end
fg = figure('IntegerHandle','off',...
'Tag',mfilename,...
'Name',mesg2,...
'NumberTitle','off',...
'Units','Pixels',...
'MenuBar','none',...
'DefaultTextInterpreter','none',...
'DefaultUicontrolInterruptible','on',...
'Visible','off');
cfg_onscreen(fg);
set(fg,'Visible','on');
sellines = min([max([n(2) numel(already)]), 4]);
[pselp pcntp pfdp pdirp] = panelpositions(fg, sellines+1);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'position',posinpanel([0 sellines/(sellines+1) 1 1/(sellines+1)],pselp),...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'HorizontalAlignment','left',...
'string','',...%mesg
'tag','msg');
% Selected Files
sel = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0 0 1 sellines/(sellines+1)],pselp),...
lf,...
'Callback',@unselect,...
'tag','selected',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',10000,...
'Min',0,...
'String',already,...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(sel,'uicontextmenu',c0);
uimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all);
% get cwidth for buttons
tmp=uicontrol('style','text','string',repmat('X',[1,50]),bf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
cw = 3*fnp(3)/50;
if strcmpi(typ,'image'),
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 0 0.37 .45],pcntp),...
'Callback',@update_frames,...
'tag','frame',...
lf,...
'BackgroundColor',col1,...
'String',frames,'UserData',eval(frames));
% 'ForegroundGolor',col3,...
end;
% Help
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.02 .5 cw .45],pcntp),...
bf,...
'Callback',@heelp,...
'tag','?',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','?',...
'ToolTipString','Show Help');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.03+cw .5 cw .45],pcntp),...
bf,...
'Callback',@editwin,...
'tag','Ed',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Ed',...
'ToolTipString','Edit Selected Files');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.04+2*cw .5 cw .45],pcntp),...
bf,...
'Callback',@select_rec,...
'tag','Rec',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Rec',...
'ToolTipString','Recursively Select Files with Current Filter');
% Done
dne = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.05+3*cw .5 0.45-3*cw .45],pcntp),...
bf,...
'Callback',@(h,e)delete(h),...
'tag','D',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Done',...
'Enable','off',...
'DeleteFcn',@null);
if numel(already)>=n(1) && numel(already)<=n(2),
set(dne,'Enable','on');
end;
% Filter Button
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.51 .5 0.1 .45],pcntp),...
bf,...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Callback',@clearfilt,...
'String','Filt');
% Filter
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 .5 0.37 .45],pcntp),...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
lf,...
'Callback',@(ob,ev)update(ob),...
'tag','regexp',...
'String',filt,...
'UserData',sfilt);
% Directories
db = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.47 1],pfdp),...
lf,...
'Callback',@click_dir_box,...
'tag','dirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',1,...
'Min',0,...
'String','',...
'UserData',wd,...
'Value',1);
% Files
tmp = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.51 0 0.47 1],pfdp),...
lf,...
'Callback',@click_file_box,...
'tag','files',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'UserData',n,...
'Max',10240,...
'Min',0,...
'String','',...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(tmp,'uicontextmenu',c0);
uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all);
% Drives
if strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'),
% get fh for lists
tmp=uicontrol('style','text','string','X',lf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
fh = 2*fnp(4); % Heuristics: why do we need 2*
sz = get(db,'Position');
sz(4) = sz(4)-fh-2*0.01;
set(db,'Position',sz);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1-fh-0.01 0.10 fh],pfdp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Drive');
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1-fh-0.01 0.37 fh],pfdp),...
lf,...
'Callback',@setdrive,...
'tag','drive',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',listdrives(false),...
'Value',1);
end;
[pd,vl] = prevdirs([wd filesep]);
% Previous dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 .05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','previous',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pd,...
'Value',vl);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Prev');
% Parent dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1/3+.05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','pardirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pardirs(wd));
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Up');
% Directory
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.12 2/3 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@edit_dir,...
'tag','edit',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String','');
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 2/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Dir');
resize_fun(fg);
set(fg, 'ResizeFcn',@resize_fun);
update(sel,wd)
%% paul HACK
%=====================
units=get(gcf,'units');
set(gcf,'units','normalized');
set(gcf,'position',[0.0336 0.1299 0.6070 0.7334]);
%% fontsize
% screensize=get(0,'screensize');
% if screensize(4)<=1024
% fs=8;
% else
% fs=14;
% end
fs=8;
ch=get(gcf,'children');
for i=1:length(ch)
try; set(ch(i),'fontsize',fs);end
end
%%larger selection range
hh=findobj(gcf,'string','Filt');
pos=get(hh,'position');
set(hh,'position',[.01 .32 .1 .02]);
hh=findobj(gcf,'tag','regexp');
pos=get(hh,'position');
set(hh,'position',[.11 .38 .3 .02],'backgroundcolor',[ 0.8392 0.9098 0.8510]);
hh=findobj(gcf,'tag','files');
pos=get(hh,'position');
set(hh,'position',[ 0.5100 0.315 0.4700 0.53]);
%% chnge arangement uf UIcontrols
p=uicontrol('style','edit','max',10,'units','normalized',...
'position',[0.001 .69 .5 .09 ],'style','edit','backgroundcolor',[.8 .8 .8],'foregroundcolor',[0 .6 0],...
'string',cellstr(mesg),'fontsize',14,'fontweight','bold','tag','pmsgbox','horizontalalignment','left' );
set(p,'position',[.001 .59 .5 .19])
hdirs=findobj(gcf,'tag','dirs'); set(hdirs,'position',[0.0200 0.37 0.4700 0.2216]);
hhelp=findobj(gcf,'string','?'); set(hhelp,'position',[ 0.0100 0.325 0.0316 0.0394],'visible','off');
hed=findobj(gcf,'string','Ed'); set(hed,'position',[ 0.00 0.325 0.0316 0.0394]);
hrec=findobj(gcf,'string','Rec'); set(hrec,'position',[ 0.1434 0.325 0.0316 0.0394]);
hre=findobj(gcf,'string','Filt'); set(hre,'position', [ 0.175 0.325 0.05 0.0394]);
hre=findobj(gcf,'tag','regexp'); set(hre,'position', [ 0.22 0.325 0.2 0.0394]);
hre=findobj(gcf,'string','Done'); set(hre,'position',[ 0.42 0.325 0.1 0.0394],'backgroundcolor',[0 .6 0]);
hmsg=findobj(gcf,'tag','msg'); set(hmsg,'position',[0 .25 1 .075])
%% get rec. all filenames-Button
p=uicontrol('style','pushbutton','units','normalized',...
'position',[.0934 .325 .05 .0394 ],'backgroundcolor',[1 1 1],'foregroundcolor',[0 .6 0],...
'string', 'fileSTR' ,'fontsize',12,'fontweight','bold','tag','pmsgbox','horizontalalignment','left', 'tooltip',...
'list all filesname from subfolders (the output can be used as fileFilter)',...
'callback' ,@p_findrecfiles);
set(gcf,'units',units);
set(findobj(gcf,'style','pushbutton'),'fontsize',8);
set(findobj(gcf,'tag','pmsgbox'),'fontsize',8);
ContextMenu=uicontextmenu;
uimenu('Parent',ContextMenu, 'Label','show help in external figure', 'callback', {@cmenuInfo,'showInfo',cellstr(mesg) } ,'ForegroundColor',[0 .5 0]);
set(findobj(gcf,'tag','pmsgbox'),'UIContextMenu',ContextMenu);
%===============paul end======
set(fg,'windowstyle', 'modal');
waitfor(dne);
drawnow;
if ishandle(sel),
t = get(sel,'String');
if isempty(t)
t = {''};
elseif sfilt.code == -1
% canonicalise non-empty folder selection
t = cellfun(@(t1)cpath(t1, pwd), t, 'UniformOutput',false);
end;
ok = 1;
end;
if ishandle(fg), delete(fg); end;
drawnow;
return;
%=======================================================================
function cmenuInfo(he,ho,task,arg)
if strcmp(task,'showInfo')
uhelp(arg);
set(findobj(gcf,'styl','listbox'),'fontsize',8);
end
%=======================================================================
function apos = posinpanel(rpos,ppos)
% Compute absolute positions based on panel position and relative
% position
apos = [ppos(1:2)+ppos(3:4).*rpos(1:2) ppos(3:4).*rpos(3:4)];
%=======================================================================
%=======================================================================
function [pselp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines)
if nargin == 1
na = numel(get(findobj(fg,'Tag','selected'),'String'));
n = get(findobj(fg,'Tag','files'),'Userdata');
sellines = min([max([n(2) na]), 4]);
end
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
% Create dummy text to estimate character height
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',lf);
lfh = 1.05*get(t,'extent');
delete(t)
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',bf);
bfh = 1.05*get(t,'extent');
delete(t)
% panel heights
% 3 lines for directory, parent and prev directory list
% variable height for dir/file navigation
% 2 lines for buttons, filter etc
% sellines plus scrollbar for selected files
pselh = sellines*lfh(4) + 1.2*lfh(4);
pselp = [0 0 1 pselh];
pcnth = 2*bfh(4);
pcntp = [0 pselh 1 pcnth];
pdirh = 3*lfh(4);
pdirp = [0 1-pdirh 1 pdirh];
pfdh = 1-(pselh+pcnth+pdirh);
pfdp = [0 pselh+pcnth 1 pfdh];
%=======================================================================
%=======================================================================
function null(varargin)
%=======================================================================
%=======================================================================
function omsg = msg(ob,str)
ob = sib(ob,'msg');
omsg = get(ob,'String');
set(ob,'String',str);
if nargin>=3,
set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold');
else
set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal');
end;
drawnow;
return;
%=======================================================================
%=======================================================================
function setdrive(ob,varargin)
st = get(ob,'String');
vl = get(ob,'Value');
update(ob,st{vl});
return;
%=======================================================================
%=======================================================================
function resize_fun(fg,varargin)
% do nothing
return;
[pselp pcntp pfdp pdirp] = panelpositions(fg);
set(findobj(fg,'Tag','msg'), 'Position',pselp);
set(findobj(fg,'Tag','pcnt'), 'Position',pcntp);
set(findobj(fg,'Tag','pfd'), 'Position',pfdp);
set(findobj(fg,'Tag','pdir'), 'Position',pdirp);
return;
%=======================================================================
%=======================================================================
function [d,mch] = prevdirs(d)
persistent pd
if ~iscell(pd), pd = {}; end;
if nargin == 0
d = pd;
else
if ~iscell(d)
d = cellstr(d);
end
d = unique(d(:));
mch = cellfun(@(d1)find(strcmp(d1,pd)), d, 'UniformOutput',false);
sel = cellfun(@isempty, mch);
npd = numel(pd);
pd = [pd(:);d(sel)];
mch = [mch{~sel} npd+(1:nnz(sel))];
d = pd;
end
return;
%=======================================================================
%=======================================================================
function pd = pardirs(wd)
if ispc
fs = '\\';
else
fs = filesep;
end
pd1 = textscan(wd,'%s','delimiter',fs,'MultipleDelimsAsOne',1);
if ispc
pd = cell(size(pd1{1}));
pd{end} = pd1{1}{1};
for k = 2:numel(pd1{1})
pd{end-k+1} = fullfile(pd1{1}{1:k},filesep);
end
else
pd = cell(numel(pd1{1})+1,1);
pd{end} = filesep;
for k = 1:numel(pd1{1})
pd{end-k} = fullfile(filesep,pd1{1}{1:k},filesep);
end
end
%=======================================================================
%=======================================================================
function clearfilt(ob,varargin)
set(sib(ob,'regexp'),'String','.*');
update(ob);
return;
%=======================================================================
%=======================================================================
function click_dir_list(ob,varargin)
vl = get(ob,'Value');
ls = get(ob,'String');
update(ob,deblank(ls{vl}));
return;
%=======================================================================
%=======================================================================
function edit_dir(ob,varargin)
update(ob,get(ob,'String'));
return;
%=======================================================================
%=======================================================================
function c = get_current_char(lb)
fg = sib(lb, mfilename);
c = get(fg, 'CurrentCharacter');
if ~isempty(c)
% reset CurrentCharacter
set(fg, 'CurrentCharacter', char(13));
end
%=======================================================================
%=======================================================================
function click_dir_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c,char(13))
vl = get(lb,'Value');
str = get(lb,'String');
pd = get(sib(lb,'edit'),'String');
while ~isempty(pd) && strcmp(pd(end),filesep)
pd=pd(1:end-1); % Remove any trailing fileseps
end
sel = str{vl};
if strcmp(sel,'..'), % Parent directory
[dr odr] = fileparts(pd);
elseif strcmp(sel,'.'), % Current directory
dr = pd;
odr = '';
else
dr = fullfile(pd,sel);
odr = '';
end;
update(lb,dr);
if ~isempty(odr)
% If moving up one level, try to set focus on previously visited
% directory
cdrs = get(lb, 'String');
dind = find(strcmp(odr, cdrs));
if ~isempty(dind)
set(lb, 'Value',dind(1));
end
end
end
return;
%=======================================================================
%=======================================================================
function re = getfilt(ob)
ob = sib(ob,'regexp');
ud = get(ob,'UserData');
re = struct('code',ud.code,...
'frames',get(sib(ob,'frame'),'UserData'),...
'ext',{ud.ext},...
'filt',{{get(sib(ob,'regexp'),'String')}});
return;
%=======================================================================
%=======================================================================
function update(lb,dr)
lb = sib(lb,'dirs');
if nargin<2 || isempty(dr) || ~ischar(dr)
dr = get(lb,'UserData');
end;
if ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'))
dr = [filesep dr filesep];
else
dr = [dr filesep];
end;
dr(strfind(dr,[filesep filesep])) = [];
[f,d] = listfiles(dr,getfilt(lb));
if isempty(d),
dr = get(lb,'UserData');
[f,d] = listfiles(dr,getfilt(lb));
else
set(lb,'UserData',dr);
end;
set(lb,'Value',1,'String',d);
set(sib(lb,'files'),'Value',1,'String',f);
set(sib(lb,'pardirs'),'String',pardirs(dr),'Value',1);
[ls,mch] = prevdirs(dr);
set(sib(lb,'previous'),'String',ls,'Value',mch);
set(sib(lb,'edit'),'String',dr);
if numel(dr)>1 && dr(2)==':',
str = char(get(sib(lb,'drive'),'String'));
mch = find(lower(str(:,1))==lower(dr(1)));
if ~isempty(mch),
set(sib(lb,'drive'),'Value',mch);
end;
end;
return;
%=======================================================================
%=======================================================================
function update_frames(lb,varargin)
str = get(lb,'String');
%r = get(lb,'UserData');
try
r = eval(['[',str,']']);
catch
msg(lb,['Failed to evaluate "' str '".'],'r');
beep;
return;
end;
if ~isnumeric(r),
msg(lb,['Expression non-numeric "' str '".'],'r');
beep;
else
set(lb,'UserData',r);
msg(lb,'');
update(lb);
end;
%=======================================================================
%=======================================================================
function select_all(ob,varargin)
lb = sib(ob,'files');
set(lb,'Value',1:numel(get(lb,'String')));
drawnow;
click_file_box(lb);
return;
%=======================================================================
%=======================================================================
function click_file_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c, char(13))
vlo = get(lb,'Value');
if isempty(vlo),
msg(lb,'Nothing selected');
return;
end;
lim = get(lb,'UserData');
ob = sib(lb,'selected');
str3 = get(ob,'String');
str = get(lb,'String');
lim1 = min([max([lim(2)-numel(str3),0]),numel(vlo)]);
if lim1==0,
msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']);
beep;
set(sib(lb,'D'),'Enable','on');
return;
end;
vl = vlo(1:lim1);
msk = false(size(str,1),1);
if vl>0, msk(vl) = true; else msk = []; end;
str1 = str( msk);
str2 = str(~msk);
dr = get(sib(lb,'edit'), 'String');
str1 = strcat(dr, str1);
set(lb,'Value',min([vl(1),numel(str2)]),'String',str2);
r = (1:numel(str1))+numel(str3);
str3 = [str3(:);str1(:)];
set(ob,'String',str3,'Value',r);
if numel(vlo)>lim1,
msg(lb,['Retained ' num2str(lim1) '/' num2str(numel(vlo))...
' of selection.']);
beep;
elseif isfinite(lim(2))
if lim(1)==lim(2),
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(2)) ' files.']);
else
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if size(str3,1) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Selected ' num2str(numel(str3)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str3)>=lim(1),
set(sib(lb,'D'),'Enable','on');
end;
end
return;
%=======================================================================
%=======================================================================
function obj = sib(ob,tag)
persistent fg;
if isempty(fg) || ~ishandle(fg)
fg = findobj(0,'Tag',mfilename);
end
obj = findobj(fg,'Tag',tag);
return;
%if isempty(obj),
% cfg_message('matlabbatch:usage',['Can''t find object with tag "' tag '".']);
%elseif length(obj)>1,
% cfg_message('matlabbatch:usage',['Found ' num2str(length(obj)) ' objects with tag "' tag '".']);
%end;
%return;
%=======================================================================
%=======================================================================
function unselect(lb,varargin)
vl = get(lb,'Value');
if isempty(vl), return; end;
str = get(lb,'String');
msk = true(numel(str),1);
if vl~=0, msk(vl) = false; end;
str2 = str(msk);
set(lb,'Value',min(vl(1),numel(str2)),'String',str2);
lim = get(sib(lb,'files'),'UserData');
if numel(str2)>= lim(1) && numel(str2)<= lim(2),
set(sib(lb,'D'),'Enable','on');
else
set(sib(lb,'D'),'Enable','off');
end;
if numel(str2) == 1, ss1 = ''; else ss1 = 's'; end;
%msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']);
if numel(vl) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ...
num2str(numel(str2)) ' file' ss1 ' remaining.']);
return;
%=======================================================================
%=======================================================================
function unselect_all(ob,varargin)
lb = sib(ob,'selected');
set(lb,'Value',[],'String',{},'ListBoxTop',1);
msg(lb,'Unselected all files.');
lim = get(sib(lb,'files'),'UserData');
if lim(1)>0, set(sib(lb,'D'),'Enable','off'); end;
return;
%=======================================================================
%=======================================================================
function [f,d] = listfiles(dr,filt)
try
ob = sib(gco,'msg');
domsg = ~isempty(ob);
catch
domsg = false;
end
if domsg
omsg = msg(ob,'Listing directory...');
end
if nargin<2, filt = ''; end;
if nargin<1, dr = '.'; end;
de = dir(dr);
if ~isempty(de),
d = {de([de.isdir]).name};
if ~any(strcmp(d, '.'))
d = [{'.'}, d(:)'];
end;
if filt.code~=-1,
f = {de(~[de.isdir]).name};
else
% f = d(3:end);
f = d;
end;
else
d = {'.','..'};
f = {};
end;
if domsg
msg(ob,['Filtering ' num2str(numel(f)) ' files...']);
end
f = do_filter(f,filt.ext);
f = do_filter(f,filt.filt);
ii = cell(1,numel(f));
if filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1),
if domsg
msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);
end
for i=1:numel(f),
try
ni = nifti(fullfile(dr,f{i}));
dm = [ni.dat.dim 1 1 1 1 1];
d4 = (1:dm(4))';
catch
d4 = 1;
end;
if all(isfinite(filt.frames))
msk = false(size(filt.frames));
for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end;
ii{i} = filt.frames(msk);
else
ii{i} = d4;
end;
end
elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1),
for i=1:numel(f),
ii{i} = 1;
end;
end;
if domsg
msg(ob,['Listing ' num2str(numel(f)) ' files...']);
end
[f,ind] = sortrows(f(:));
ii = ii(ind);
msk = true(1,numel(f));
for i=2:numel(f),
if strcmp(f{i-1},f{i}),
if filt.code==1,
tmp = sort([ii{i}(:) ; ii{i-1}(:)]);
tmp(~diff(tmp,1)) = [];
ii{i} = tmp;
end;
msk(i-1) = false;
end;
end;
f = f(msk);
if filt.code==1,
% Combine filename and frame number(s)
ii = ii(msk);
nii = cellfun(@numel, ii);
c = cell(sum(nii),1);
fi = cell(numel(f),1);
for k = 1:numel(fi)
fi{k} = k*ones(1,nii(k));
end
ii = [ii{:}];
fi = [fi{:}];
for i=1:numel(c),
c{i} = sprintf('%s,%d', f{fi(i)}, ii(i));
end;
f = c;
elseif filt.code==-1,
fs = filesep;
for i=1:numel(f),
f{i} = [f{i} fs];
end;
end;
f = f(:);
d = unique(d(:));
if domsg
msg(ob,omsg);
end
return;
%=======================================================================
%=======================================================================
function [f,ind] = do_filter(f,filt)
t2 = false(numel(f),1);
filt_or = sprintf('(%s)|',filt{:});
t1 = regexp(f,filt_or(1:end-1));
if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;
for i=1:numel(t1),
t2(i) = ~isempty(t1{i});
end;
ind = find(t2);
f = f(t2);
return;
%=======================================================================
%=======================================================================
function heelp(ob,varargin)
[col1,col2,col3,fn] = colours;
fg = sib(ob,mfilename);
t = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.01 0.01 0.98 0.98],...
fn,...
'BackgroundColor',col2,...
'ForegroundColor',col3,...
'Max',0,...
'Min',0,...
'tag','HelpWin',...
'String',' ');
c0 = uicontextmenu('Parent',fg);
set(t,'uicontextmenu',c0);
uimenu('Label','Done', 'Parent',c0,'Callback',@helpclear);
str = cfg_justify(t, {[...
'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). '],...
'',[...
'The panel at the bottom shows files that are already selected. ',...
'Clicking a selected file will un-select it. To un-select several, you can ',...
'drag the cursor over the files, and they will be gone on release. ',...
'You can use the right mouse button to un-select everything.'],...
'',[...
'Directories are navigated by editing the name of the current directory (where it says "Dir"), ',...
'by going to one of the previously entered directories ("Prev"), ',...
'by going to one of the parent directories ("Up") or by navigating around ',...
'the parent or subdirectories listed in the left side panel.'],...
'',[...
'Files matching the filter ("Filt") are shown in the panel on the right. ',...
'These can be selected by clicking or dragging. Use the right mouse button if ',...
'you would like to select all files. Note that when selected, the files disappear ',...
'from this panel. They can be made to reappear by re-specifying the directory ',...
'or the filter. '],...
'',[...
'Both directory and file lists can also be browsed by typing the leading ',...
'character(s) of a directory or file name.'],...
'',[...
'Note that the syntax of the filter differs from that used by most other file selectors. ',...
'The filter works using so called ''regular expressions''. Details can be found in the ',...
'MATLAB help text on ''regexp''. ',...
'The following is a list of symbols with special meaning for filtering the filenames:'],...
' ^ start of string',...
' $ end of string',...
' . any character',...
' \ quote next character',...
' * match zero or more',...
' + match one or more',...
' ? match zero or one, or match minimally',...
' {} match a range of occurrances',...
' [] set of characters',...
' [^] exclude a set of characters',...
' () group subexpression',...
' \w match word [a-z_A-Z0-9]',...
' \W not a word [^a-z_A-Z0-9]',...
' \d match digit [0-9]',...
' \D not a digit [^0-9]',...
' \s match white space [ \t\r\n\f]',...
' \S not a white space [^ \t\r\n\f]',...
' \<WORD\> exact word match',...
'',[...
'Individual time frames of image files can also be selected. The frame filter ',...
'allows specified frames to be shown, which is useful for image files that ',...
'contain multiple time points. If your images are only single time point, then ',...
'reading all the image headers can be avoided by specifying a frame filter of "1". ',...
'The filter should contain a list of integers indicating the frames to be used. ',...
'This can be generated by e.g. "1:100", or "1:2:100".'],...
'',[...
'The recursive selection button (Rec) allows files matching the regular expression to ',...
'be recursively selected. If there are many directories to search, then this can take ',...
'a while to run.'],...
'',[...
'There is also an edit button (Ed), which allows you to edit your selection of files. ',...
'When you are done, then use the menu-button of your mouse to either cancel or accept your changes.'],''});
set(t,'String',str);
return;
%=======================================================================
%=======================================================================
function helpclear(ob,varargin)
ob = get(ob,'Parent');
ob = get(ob,'Parent');
ob = findobj(ob,'Tag','HelpWin');
delete(ob);
%=======================================================================
%=======================================================================
function t = cpath(t,d)
switch filesep,
case '/',
mch = '^/';
fs = '/';
fs1 = '/';
case '\',
mch = '^.:\\';
fs = '\';
fs1 = '\\';
otherwise;
cfg_message('matlabbatch:usage','What is this filesystem?');
end
if isempty(regexp(t,mch,'once')),
if (nargin<2)||isempty(d), d = pwd; end;
t = [d fs t];
end;
% Replace occurences of '/./' by '/' (problems with e.g. /././././././')
re = [fs1 '\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs);
end;
t = regexprep(t,[fs1 '\.' '$'], fs);
% Replace occurences of '/abc/../' by '/'
re = [fs1 '[^' fs1 ']+' fs1 '\.\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs,'once');
end;
t = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\.\.' '$'],fs,'once');
% Replace '//'
t = regexprep(t,[fs1 '+'], fs);
%=======================================================================
%=======================================================================
function editwin(ob,varargin)
[col1,col2,col3,lf,bf] = colours;
fg = gcbf;
lb = sib(ob,'selected');
str = get(lb,'String');
ac = allchild(fg);
acv = get(ac,'Visible');
h = uicontrol(fg,...
'Style','Edit',...
'units','normalized',...
'String',str,...
lf,...
'Max',2,...
'Tag','EditWindow',...
'HorizontalAlignment','Left',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Position',[0.01 0.08 0.98 0.9],...
'Userdata',struct('ac',{ac},'acv',{acv}));
ea = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.01 .01,.32,.07],...
bf,...
'Callback',@editdone,...
'tag','EditWindowAccept',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Accept');
ee = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.34 .01,.32,.07],...
bf,...
'Callback',@editeval,...
'tag','EditWindowEval',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Eval');
ec = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.67 .01,.32,.07],...
bf,...
'Callback',@editclear,...
'tag','EditWindowCancel',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Cancel');
set(ac,'visible','off');
%=======================================================================
%=======================================================================
function editeval(ob,varargin)
ob = get(ob, 'Parent');
ob = sib(ob, 'EditWindow');
str = get(ob, 'String');
if ~isempty(str)
[out,sts] = cfg_eval_valedit(char(str));
if sts && (iscellstr(out) || ischar(out))
set(ob, 'String', cellstr(out));
else
fgc = get(ob, 'ForegroundColor');
set(ob, 'ForegroundColor', 'red');
pause(1);
set(ob, 'ForegroundColor', fgc);
end
end
%=======================================================================
%=======================================================================
function editdone(ob,varargin)
ob = get(ob,'Parent');
ob = sib(ob,'EditWindow');
str = cellstr(get(ob,'String'));
if isempty(str) || isempty(str{1})
str = {};
else
dstr = deblank(str);
if ~isequal(str, dstr)
c = questdlg(['Some of the filenames contain trailing blanks. This may ' ...
'be due to copy/paste of strings between MATLAB and the ' ...
'edit window. Do you want to remove any trailing blanks?'], ...
'Trailing Blanks in Filenames', ...
'Remove', 'Keep', 'Remove');
switch lower(c)
case 'remove'
str = dstr;
end
end
filt = getfilt(ob);
if filt.code >= 0 % filter files, but not dirs
[p,n,e] = cellfun(@fileparts, str, 'uniformoutput',false);
fstr = strcat(n, e);
[fstr1,fsel] = do_filter(fstr, filt.ext);
str = str(fsel);
end
end
lim = get(sib(ob,'files'),'UserData');
if numel(str)>lim(2),
msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']);
beep;
str = str(1:lim(2));
elseif isfinite(lim(2)),
if lim(1)==lim(2),
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']);
else
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if numel(str) == 1, ss = ''; else ss = 's'; end;
msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
set(sib(ob,'selected'),'String',str,'Value',[]);
acs = get(ob,'Userdata');
fg = gcbf;
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function editclear(ob,varargin)
fg = gcbf;
acs = get(findobj(fg,'Tag','EditWindow'),'Userdata');
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function [c1,c2,c3,lf,bf] = colours
c1 = [1 1 1];
c2 = [1 1 1];
c3 = [0 0 0];
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
if isempty(lf)
lf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
if isempty(bf)
bf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
%=======================================================================
%% paul HAck
function p_findrecfiles(do,varg)
ob=findobj(gcf,'tag','Rec');
start = get(sib(ob,'edit'),'String');
filt = get(sib(ob,'regexp'),'Userdata');
filt.filt = {get(sib(ob,'regexp'), 'String')};
fob = sib(ob,'frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
% flt=struct('code' ,0, 'frames', [], 'ext', {'.*'}, 'filt', '{''img|nii''}' )
try
global glob_cfg_getfile2
if 1%~isempty(glob_cfg_getfile2)
if isfield(glob_cfg_getfile2, 'recpaths')
selx={};
for i=1:length(glob_cfg_getfile2.recpaths)
selx=[ selx ; select_rec1( glob_cfg_getfile2.recpaths{i} , filt) ];
end
else
hdirlb=findobj(gcf,'tag','dirs');
alldirs=get(hdirlb,'string');
alldirs(1:2)=[];%remove ./..
pa=get(hdirlb,'userdata');
recpaths=cellfun(@(fi) {[pa fi]}, alldirs(:));
selx={};
for i=1:length(recpaths)
selx=[ selx ; select_rec1( recpaths{i} , filt) ];
end
end
% filetags=regexprep(selx,'.*\','')
filetags=repmat({''},length(selx),1);
for i=1:length(selx)
[pa fi ext]=fileparts(selx{i});
[pa2 fi2]=fileparts(pa);
fi2=regexprep([fi ext], [fi2 '|' fi2(2:end)],'' );
filetags{i}=fi2;
end
files=sort((filetags));
[files2,junk,ind] = unique(files);
freqs = histc(ind,1:numel(files2));
freqs=cellstr(num2str(freqs));
files3=cellfun(@(x, y) [ '(' y ') ' x ],files2,freqs,'un',0);
[is ix]=sort(freqs); %sort accor frequency
files4=flipud(files3(ix));
% ids=selector2(files4);
ids=selector3(files4,{'files'});
ids2=regexprep(files4([ids]),'(\s*\d*\)\s*',''); %remove filecounting, i.e. "( 34 ) "
hflt= findobj(gcf,'tag','regexp');
filters=cell2str(ids2,'|^') ;
filters=['^' filters];
set(hflt, 'string', filters );
% uhelp(flipud(files3(ix))) ;
%uhelp(files3) ;
end
end
%=======================================================================
function select_rec(ob, varargin)
start = get(sib(ob,'edit'),'String');
filt = get(sib(ob,'regexp'),'Userdata');
filt.filt = {get(sib(ob,'regexp'), 'String')};
fob = sib(ob,'frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
ptr = get(gcbf,'Pointer');
try
%% PAUL hack
try
global glob_cfg_getfile2
if ~isempty(glob_cfg_getfile2)
if isfield(glob_cfg_getfile2, 'recpaths')
selx={};
for i=1:length(glob_cfg_getfile2.recpaths)
selx=[ selx ; select_rec1( glob_cfg_getfile2.recpaths{i} ,filt) ];
end
sel=selx;
end
set(gcbf,'Pointer','watch');
else
sel = select_rec1(start,filt);
end
catch
sel = select_rec1(start,filt);
end
catch
set(gcbf,'Pointer',ptr);
sel = {};
end;
set(gcbf,'Pointer',ptr);
already= get(sib(ob,'selected'),'String');
fb = sib(ob,'files');
lim = get(fb,'Userdata');
limsel = min(lim(2)-size(already,1),size(sel,1));
set(sib(ob,'selected'),'String',[already(:);sel(1:limsel)],'Value',[]);
msg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1)));
if ~isfinite(lim(1)) || size(sel,1)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
%=======================================================================
%=======================================================================
function sel=select_rec1(cdir,filt)
sel={};
[t,d] = listfiles(cdir,filt);
if ~isempty(t)
sel = strcat([cdir,filesep],t);
end;
for k = 1:numel(d)
if ~any(strcmp(d{k},{'.','..'}))
sel1 = select_rec1(fullfile(cdir,d{k}),filt);
sel = [sel(:); sel1(:)];
end;
end;
%=======================================================================
%=======================================================================
function sfilt=mk_filter(typ,filt,frames)
if nargin<3, frames = 1; end;
if nargin<2, filt = '.*'; end;
if nargin<1, typ = 'any'; end;
switch lower(typ),
case {'any','*'}, code = 0; ext = {'.*'};
case {'image'}, code = 1; ext = {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$','.*\.NII(,\d+){0,2}$','.*\.IMG(,\d+){0,2}$'};
case {'mesh'}, code = 0; ext = {'.*\.gii$','.*\.GII$','.*\.mat$','.*\.MAT$'};
case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'};
case {'gifti'}, code = 0; ext = {'.*\.gii$','.*\.GII$'};
case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,2}$',...
'.*\.img(,[0-9]*){0,2}$',...
'.*\.NII(,[0-9]*){0,2}$',...
'.*\.IMG(,[0-9]*){0,2}$'};
case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'};
case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.txt','.*\.TXT'};
case {'batch'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.m$','.*\.M$','.*\.xml$','.*\.XML$'};
case {'dir'}, code =-1; ext = {'.*'};
case {'extdir'}, code =-1; ext = {['.*' filesep '$']};
otherwise, code = 0; ext = {typ};
end;
sfilt = struct('code',code,'frames',frames,'ext',{ext},...
'filt',{{filt}});
%=======================================================================
%=======================================================================
function drivestr = listdrives(reread)
persistent mydrivestr;
if isempty(mydrivestr) || reread
driveLett = strcat(cellstr(char(('C':'Z')')), ':');
dsel = false(size(driveLett));
for i=1:numel(driveLett)
dsel(i) = exist([driveLett{i} '\'],'dir')~=0;
end
mydrivestr = driveLett(dsel);
end;
drivestr = mydrivestr;
%=======================================================================
%=======================================================================
function varargout = cfg_onscreen(fg)
% Move figure on the screen containing the mouse
% cfg_onscreen(fg) - move figure fg on the screen containing the mouse
% pos = cfg_onscreen(fg) - compute position of figure, do not move it
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_onscreen.m 4033 2010-08-04 15:53:35Z volkmar $
rev = '$Rev: 4033 $';
% save figure units - use pixels here
units = get(fg,'Units');
set(fg,'Units','pixels');
Rect = get(fg,'Position');
S0 = get(0,'MonitorPosition');
if size(S0,1) > 1 % Multiple Monitors
%-Use Monitor containing the Pointer
pl = get(0,'PointerLocation');
w = find(pl(1)>=S0(:,1) & pl(1)<S0(:,1)+S0(:,3)-1 &...
pl(2)>=S0(:,2) & pl(2)<S0(:,2)+S0(:,4));
if numel(w)~=1, w = 1; end
S0 = S0(w,:);
end
Rect(1) = S0(1) + (S0(3) - Rect(3))/2;
Rect(2) = S0(2) + (S0(4) - Rect(4))/2;
if nargout == 0
set(fg, 'Position',Rect);
else
varargout{1} = Rect;
end
set(fg,'Units',units);
|
github
|
philippboehmsturm/antx-master
|
regexpi2.m
|
.m
|
antx-master/mritools/basic/regexpi2.m
| 239 |
utf_8
|
b8607d0cd879b58ffd5464e037d9a370
|
function id=regexpi2(cells, str,varargin)
%same as regexpi but jelds indizes of mathing cells , instead of empty cells ('I'm tired to code this again and again)
id=regexpi(cells,str,varargin{:});
id=find(cellfun('isempty',id)==0);
|
github
|
philippboehmsturm/antx-master
|
pwrite2file2.m
|
.m
|
antx-master/mritools/basic/pwrite2file2.m
| 2,649 |
utf_8
|
e2ae057b7002f2041cdc57b5405d13ae
|
function pwrite2file2(pathname, dataX,header , varargin );
%___________________________________________________________________________
% function pwrite2file2(pathname, dataX ,header );
% function pwrite2file2(pathname, dataX,header,1 ); %OPENS WITH GUI
%___________________________________________________________________________
% pwrite2file2(pathname, dataX,header );:
% IN____
% pathRT :path (with endeslash)
% pathname :filename
% dataX : -writes dataX/data (must be a cell/double)
% header : =headerline(s) as char or /CELL-array /or empty,[];
%
% example
% a=rand(10,3); b={'nr' 'pb' 'val'};
% pwrite2file2('aaa14.txt',a,b );
% _________________________________________________________________________
% see also preadfile pwrite2file
%___________________________________________________________________________
% paul,BNIC, mar.2007
%___________________________________________________________________________
% 'l'
if nargin==4
[fi pa]= uiputfile;
pathname=[pa fi];
end
a=whos('dataX');
clas=a.class;
% 'a'
%############################################# double2char
if strcmp(clas,'double')==1 | strcmp(clas,'single')==1
for i=1:size(dataX,1)
dataX2(i,:)={num2str(dataX(i,:))};
end
dataX=dataX2;
a=whos('dataX');
clas=a.class;
end
%#############################################
fid = fopen([ pathname ],'w','n');
if ~isempty(header)
if ~iscell(header) ;%if char
for i=1:size(header,1)
dumh=char( (header(i,:)) );
fprintf(fid,'%s\n',dumh);
end
elseif iscell(header) ;%%CELL
if size(header,2)==1 %only one element in a cellline
for i=1:size(header,1)
dumh=char( (header(i,:)) );
fprintf(fid,'%s\n',dumh);
end
else %more elements per line
for i=1:size(header,1)
dl=(header(i,:));
dnew='';
for j=1:length(dl)
dele=[char(dl(j)) ' '];
dnew(end+1:end+length(dele))=dele;
end
dumh= dnew ;
fprintf(fid,'%s\n',dumh);
end
end
end
end
%------dataX
if ( strcmp(clas,'cell')==1 | strcmp(clas,'char')==1)
for i=1:size(dataX,1)
dumh=char( (dataX(i,:)) );
fprintf(fid,'%s\n',dumh);
end
elseif (strcmp(clas,'double')==1 | strcmp(clas,'single')==1)
for i=1:size(dataX,1)
dumh=sprintf('%s', num2str((dataX(i,:))));
fprintf(fid,'%s\n',num2str(dumh));
end
end
fclose(fid);
|
github
|
philippboehmsturm/antx-master
|
saveppt2.m
|
.m
|
antx-master/mritools/basic/saveppt2.m
| 34,821 |
utf_8
|
ebc652b861c7b914076b2bb03fb52fa7
|
% SAVEPPT2 saves plots to PowerPoint.
% SAVEPPT2(save_file,<additional parameters>)
% Saves the current Matlab figure window or Simulink model window to a PowerPoint
% file designated by save_file. If save_file is omitted, the user is prompted to enter
% one via UIPUTFILE. If the path is omitted from filespec, the
% PowerPoint file is created in the current Matlab working directory.
%
% powerpoint_object=SAVEPPT2(save_file,'close',false);
% Return the PowerPoint presentation object if it isn't to be closed.
%
% Batch Processing:
% powerpoint_object=SAVEPPT2(save_file,'init')
% Initializes a powerpoint object for use with batch processing.
% SAVEPPT2('ppt',powerpoint_object);
% Saves the current Matlab figure to the opened PowerPoint Object
% SAVEPPT2(save_file,'ppt',powerpoint_object,'close');
% Saves and closes the PowerPoint object.
%
% SAVEPPT2 also accepts numerous additional optional parameters, they can
% be called from the matlab command line or in function form. All options
% can be preceded with a '-', but this is not required. Short and Long
% named options are listed on the same line.
%
% % Annotation:
% 'n' 'notes' - Add information to notes section.
% 'text' 'textbox' - Add text box.
% 'comment' 'comments' - Add comment. (Only works if PowerPoint is visible)
% - \t and \n are converted to tab and new line, respectively.
% 't' 'title' - Add a title or add a blank title so that one may be added later. Title is placed at the top of the presentation unless a padding is specified.
% If 'title' or 'textbox' is specified alone a blank placeholder will be added.
%
% % Figure Options
% 'f' 'fig' 'figure' - Use the specified figure handle. Also accepts an array of figures. More than 4 figures is not recommended as it makes it difficult to see in the plot. Default: gcf
% If figure is 0, a blank page is added. If a title is specified then a title page is added.
% 'd' 'driver' 'drivers' - [meta, bitmap]. Send figure to clipboard Metafile or Bitmap format. See also print help.
% 'r' 'render' - [painters,zbuffer,opengl]. Choose print render mode. See also print help.
% 'res' 'resolution' - Dots-per-inch resolution. Default: 90 for Simulink, 150 for figures. See also print help.
%
% % Slide Layout
% 'st' 'stretch' - Used only with scale, stretch the figure to fill all remaining space (taking into account padding and title). Default: on
% 's' 'sc' 'scale' - Scale the figure to remaining space on the page while maintaining aspect ratio, takes into account padding and title spacing. Default: on
% 'h' 'halign' - ['left','center','right']. Horizontally align figure. Default: center
% 'v' 'valign' - ['top','center','bottom']. Vertically align the graph. Default: center
% 'p' 'pad' 'padding' - Place a padding around the figure that is used for alignment and scaling. Can be one number to be applied equally or an array in the format of [left right top bottom]. Useful when plotting to template files. Default: 0
% 'c' 'col' 'columns' - Number of columns to place multiple plots in. Default: 2
%
% % PowerPoint Control
% 'i' 'init' - Initialize PowerPoint presentation for use in batch mode. Returns a PowerPoint Presentation Object.
% 'close' - Close PowerPoint presentation. Default: true
% 'save' - Save PowerPoint Presentation. Useful for saves in batch mode.
% 'ppt' - Call saveppt2 with specified PowerPoint Presentation object.
% 'visible' - Make PowerPoint visible.
% 'template' - Use template file specified. Is only used if the save file does not already exist.
%
% For binary options use: 'yes','on' ,'true' ,true to enable
% 'no', 'off','false',false to disable
% Examples:
% % Simplest Call
% plot(rand(1,100),rand(1,100),'*');
% saveppt2
%
% % Add a title "Hello World"
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','title','Hello World');
% saveppt2('test.ppt','t','Hello World');
% saveppt2 test.ppt -title 'Hello World'
% saveppt2 test.ppt -t 'Hello World'
%
% % Add a note
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','notes','Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
%
% % Add multiline note
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','notes','Lifetime, relational competence.\n\tTactical, integrated solution');
% note=sprintf('Latest Quarter Sales: %%fM',rand(1,1)*100);
% saveppt2('test.ppt','notes',note);
%
% Add a TextBox
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','texbox','Totally, groupwide mindset');
%
% % Add a comment (PowerPoint must be visible)
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','visible','comment','Virtual, logic-based culture');
%
% % Scaling & Stretching the plot to fill the page.
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','note','Scaling & Stretching On (Default)');
% saveppt2('test.ppt','stretch','false','Stretching Off');
% saveppt2('test.ppt','scale',off,'note','Scaling Off');
%
% % Stretching the plot to fill the page.
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','Stretching On');
%
% saveppt2('test.ppt','stretch',false);
% saveppt2 test.ppt -stretch off
%
% % copy the plot as both a meta and bitmap.
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','driver','meta','scale','stretch');
% saveppt2('test.ppt','driver','bitmap','scale','stretch');
%
% % scale the plot to fill the page, ignoring aspect ratio, with 150 pixels
% % of padding on all sides
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','scale','stretch','Padding',150);
% saveppt2('test.ppt','scale',true,'stretch',true,'Padding',150);
%
% % scale the plot to fill the page, ignoring aspect ratio, with 150 pixels
% % of padding on left and right sides
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','scale','stretch','Padding',[150 150 0 0]);
% saveppt2('test.ppt','scale',true,'stretch',true,'Padding',[150 150 0 0]);
%
% % scale the plot to fill the page, ignoring aspect ratio add blank title
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','scale','stretch','title');
% saveppt2('test.ppt','scale',true,'stretch',true,'title',true);
%
% % Align the figure in the upper left corner
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','halign','left','valign','top');
%
% % Align the figure in the upper left corner
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','halign','right','valign','bottom');
%
% % Use the template 'Group Report.ppt'
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('test.ppt','template','Group Report.ppt');
%
% % Plot 4 figures horizontally aligned left with 2 columns
% a=figure('Visible','off');plot(1:10);
% b=figure('Visible','off');plot([1:10].^2);
% c=figure('Visible','off');plot([1:10].^3);
% d=figure('Visible','off');plot([1:10].^4);
% saveppt2('test.ppt','figure',[a b c d],'columns',2,'title','Hello World!','halign','left')
%
% % Create blank title page.
% figure('test.ppt','figure',0,'title','New Section');
%
% % Create blank page.
% figure('test.ppt','figure',0);
%
% % Plot figures in batch mode. Faster than opening a new powerpoint object each time
% ppt=saveppt2('batch.ppt','init');
% for i=1:10
% plot(rand(1,100),rand(1,100),'*');
% saveppt2('ppt',ppt)
% if mod(i,5)==0 % Save half way through incase of crash
% saveppt2('ppt',ppt,'save')
% end
% end
% saveppt2('batch.ppt','ppt',ppt,'close');
%
% More flexibility is built in, but it is impossible to show all possible
% calling combinations, you may check out the source or Test_SavePPT2.m
%
% See also print, saveppt, validateInput
% Ver 2.2, Copyright 2005, Mark W. Brown, [email protected]
% changed slide type to include title.
% added input parameter for title text.
% added support for int32 and single data types for Matlab 6.0
% added comments about changing bitmap resolution (for large images only)
% swapped order of opening PPT and copying to clipboard (thanks to David Abraham)
% made PPT invisible during save operations (thanks to Noah Siegel)
%
% Ver 3.5, Copyright 2010, Jed Frey, [email protected]
% Added template & notes features
% Added multiple calling functions
% Restructured calling sequence
function varargout=saveppt2(varargin)
%% Establish valid save file name:
if nargin<1
[fname, fpath] = uiputfile('*.ppt');
if fpath == 0; return; end
filespec = fullfile(fpath,fname);
elseif strcmp(varargin{1},'ppt')
% If the first input is the Powerpoint COM object
else
% Otherwise the first input is the desired filename.
filespec=varargin{1};
varargin(1)='';
% If the path is empty, use current working directory. If the extension
% is blank, add .ppt then create full windows path.
[fpath,fname,fext] = fileparts(filespec);
if isempty(fpath); fpath = pwd; end
if isempty(fext); fext = '.ppt'; end
filespec = fullfile(fpath,[fname,fext]);
end
%% Process additional parameters
if numel(varargin)>0
% Set up valid parameters list
validParameters={ ...
{'figure','fig','f'}, ... % Figure & driver settings
{'init','i'},'close','save','ppt','visible','template', ... % Power Point Control.
{'notes','n'},{'text','textbox'}, {'comments','comment'}, ... % Notes, textbox & comments settings
{'stretch','st'},{'scale','s','sc'},{'title','t'}, ... % Stretch, Scale & Title settings
{'driver','drivers','d'},{'resolution','res'},{'render','r'},... % Title, Resolution and Render Calls
{'halign','h'},{'valign','v'},{'padding','pad','p'},{'columns','col','c'}}; % Align, padding and column calls.
% Validate additional input
addlParms=validateInput(varargin,validParameters);
else
% Just make addlParms an empty struct so that 'isfield' doesn't error
% out.
addlParms=struct;
end
%% Parameter Sanity Checks
% PowerPoint File & Init cannot both be specified at the same time.
if isfield(addlParms,'init')&&isfield(addlParms,'ppt')
error('Both init and ppt can not be specified at the same time. Call init first, then use ppt');
end
% PowerPoint Close & Init cannot both be specified at the same time
if isfield(addlParms,'init')&&isfield(addlParms,'close')
warning('saveppt2:InitQuit','Both init and quit should not be specified at the same time, ignoring close.');
addlParms=rmfield(addlParms,'close');
end
% If close is specified, force to save the powerpoint.
if isfield(addlParms,'close')
addlParms.save=true;
end
%% Initialize PowerPoint
% If the user has passed a previous PowerPoint session:
if isfield(addlParms,'ppt')
% Validate that the PPT object passed is actually a PPT object
% Try 10 times to get parameters from the ppt object, waiting on
% ActiveX to catch up.
op=-1;
for i=1:10
try
% Make sure it's a valid object.
addlParms.ppt.ReadOnly;
op=addlParms.ppt;
break;
catch
pause(2);
end
end
if op==-1
error('Failed invoking object. Verify that it is a PPT object as returned from a saveppt2(file,''init'') function.');
end
% Otherwise assign it to the 'open presentation' variable and get the
% powerpoint application object.
ppt=op.Application;
% If save or close is set
if checkParm(addlParms,'save')
% Save the file
if ~exist(filespec,'file')
% Save file as new if the file doesn't exist:
invoke(op,'SaveAs',filespec,1);
else
% Save existing file:
invoke(op,'Save');
end
% If close is specified, close the powerpoint.
if checkParm(addlParms,'close')
invoke(op,'Close');
% If there are no more open powerpoint presentations, quit the
% application
if ppt.Presentations.Count==0
invoke(ppt,'Quit');
end
end
return;
end
else
% If a powerpoint object isn't passed, open one.
ppt=-1;
% Try 10 times to open powerpoint ActiveX with a 2 second pause in between.
% Sometimes the OS and ActiveX controls take a few seconds to
% 'catch up'
for i=1:10
try
ppt = actxserver('PowerPoint.Application');
ppt.visible;
break;
catch
pause(2);
end
end
if ppt==-1
error('Error opening PowerPoint');
end
% Check if the savefile exists.
if exist(filespec,'file')
% If the save file already exists, the template cannot be applied.
if isfield(addlParms,'template')
addlParms=rmfield(addlParms,'template');
warning('saveppt2:fileexist','Save file exists, skipping opening template');
end
% Try 10 times to open the file with a 2 second pause in between.
% Sometimes the OS and ActiveX controls take a few seconds to
% 'catch up'
op=-1;
for i=1:10
try
op = invoke(ppt.Presentations,'Open',filespec,[],[],0);
break;
catch
pause(2);
end
end
if op==-1
error('Error opening file: %s',filespec);
end
else
% If a template is specified
if isfield(addlParms,'template')
% Check that the file exists
if ~exist(addlParms.template,'file');
warning('saveppt2:notemplate','Template file does not exist, skipping.');
op = invoke(ppt.Presentations,'Add');
else
% Open the template file
op = invoke(ppt.Presentations,'Open',addlParms.template,[],[],0);
end
else
op = invoke(ppt.Presentations,'Add');
end
end
% If saveppt2 was just called to init the plots, return the PowerPoint
% presentation object.
if isfield(addlParms,'init')&&addlParms.init
varargout{1}=op;
return;
end
end
% Set Visibility.
if checkParm(addlParms,'visible')
ppt.visible=1;
end
%% Additional Parameter Sanity Checks
% Validate that halign is a valid setting
if isfield(addlParms,'halign')&&~any(strcmpi(addlParms.halign,{'left','center','right'}))
warning('saveppt2:InvalidHalign','Invalid horizontal align "%s" specified, ignoring',addlParms.halign);
addlParms=rmfield(addlParms,'halign');
end
% Validate that valign is a valid setting
if isfield(addlParms,'valign')&&~any(strcmpi(addlParms.valign,{'top','center','bottom'}))
warning('saveppt2:InvalidValign','Invalid vertical align "%s" specified, ignoring',addlParms.valign);
addlParms=rmfield(addlParms,'valign');
end
% If there is more than 1 figure, scale must be enabled so that all of the
% figures will fit on a slide.
if isfield(addlParms,'figure')&&length(addlParms.figure)>1
if isfield(addlParms,'scale')&&addlParms.scale==false
warning('saveppt2:ScaleForced','More than one figure given, scaling forced to enable so that the plots will fit');
end
addlParms.scale=true;
end
% Stretch only makes sense when used with scale. Ignore otherwise
if ~checkParm(addlParms,'scale')&&checkParm(addlParms,'stretch')
warning('saveppt2:ScaleForcedStretch','Stretch is enabled, scaling forced to enabled.');
addlParms.scale=true;
end
% Comments only works when the PowerPoint is visible.
if ~checkParm(addlParms,'visible')&&checkParm(addlParms,'comments')
error('Visibility must be enabled to use comments.');
end
% Validate padding input
if isfield(addlParms,'padding')
% Make sure that padding is a number
if ~isnumeric(addlParms.padding)
addlParms=rmfield(addlParms,'padding');
warning('saveppt2:IncorrectPadding','Padding non-numeric. Must be [l, r, t, b] or a single number, ignoring.')
% Validate padding size
elseif ~any(size(addlParms.padding,2)==[1 4])
addlParms=rmfield(addlParms,'padding');
warning('saveppt2:IncorrectPaddingSize','Incorrect Padding Size. Must be [l, r, t, b] or a single number, ignoring.')
% If padding is just one number, fill in so that all of the numbers are
% the same
elseif size(addlParms.padding,2)==1
addlParms.padding=repmat(addlParms.padding,1,4);
end
end
%% Set up defaults
% If no text for title is specified, set it to blank
if checkParm(addlParms,'title');
addlParms.title='';
end
% If no text for textbox is specified, set it to blank
if checkParm(addlParms,'text');
addlParms.text='';
end
% If no text for comment is specified, set it to blank
if checkParm(addlParms,'comments');
addlParms.comments='';
end
% If no note is specified, clear it and give a warning
if checkParm(addlParms,'notes');
warning('saveppt2:NoNoteGiven','No note was specified');
addlParms=rmfield(addlParms,'notes');
end
% Stretch was not specified
if ~isfield(addlParms,'stretch');
addlParms.stretch=true;
end
% Scale was not specified
if ~isfield(addlParms,'scale');
addlParms.scale=true;
end
% Comments only work when the PowerPoint slide is visible.
if ~checkParm(addlParms,'visible')&&isfield(addlParms,'comments')
warning('saveppt2:VisibleComments','Comments are only available if PowerPoint is visible. Removing');
addlParms=rmfield(addlParms,'comments');
end
% Default the number of columns to 2
if ~isfield(addlParms,'columns')||checkParm(addlParms,'columns')
addlParms.columns=2;
end
% If no close is specified, default to close the fields.
if ~isfield(addlParms,'close')&&~isfield(addlParms,'ppt')
addlParms.close=true;
end
%% Configure Print Options
% Validate all of the figures
if isfield(addlParms,'figure')
% Meaning they just put 'Figure', but didn't specify one, default
% behavior for print, just remove the field
if checkParm(addlParms,'figure')
addlParms=rmfield(addlParms,'figure');
else
% More than 4 figures makes it hard to read
if length(addlParms.figure)>4
warning('saveppt2:TooManyFigures','More than 4 figures is not reccomended')
end
end
% Check that the figures actually exist
for i=1:length(addlParms.figure)
try
a=get(addlParms.figure(i));
catch
error('saveppt2:FigureDoesNotExist',['Figure ' addlParms.figure(i) ' does not exist']);
end
end
else
% If no figure is specified, use the current figure.
addlParms.figure=gcf;
end
% Resolution options
if isfield(addlParms,'resolution')
resOpt=['-r ' num2str(addlParms.resolution)];
else
resOpt='';
end
% Driver options
if isfield(addlParms,'driver')
if strmatch(addlParms.driver(1),'d')
addlParms.driver(1)='';
end
switch lower(addlParms.driver)
case 'meta'
addlParms.driver='-dmeta';
case 'bitmap'
addlParms.driver='-dbitmap';
otherwise
warning('saveppt2:UnknownDriver','Unknown Print Driver: %s. Using meta.',addlParms.driver);
addlParms.driver='-dmeta';
end
else
addlParms.driver='-dmeta';
end
% Render schema options
if isfield(addlParms,'render')
switch lower(addlParms.render)
case 'painters'
rendOpt='-painters';
case 'zbuffer'
rendOpt='-zbuffer';
case 'opengl'
rendOpt='-opengl';
case 'render'
rendOpt='';
otherwise
warning('saveppt2:UnknownRenderer','Unknown Renderer: %s',addlParms.render);
addlParms=rmfield(addlParms,'render');
end
else
rendOpt='';
end
%% Slide functions
% Get height and width of slide:
slide_H = op.PageSetup.SlideHeight;
slide_W = op.PageSetup.SlideWidth;
% Get current number of slides:
slide_count = get(op.Slides,'Count');
% Add a new slide (with title object):
slide_count = int32(double(slide_count)+1);
% Create the appropriate slide (w or w/o title)
if isfield(addlParms,'title')
% Slide with Title
if addlParms.figure(1)==0 % Title slide only.
new_slide = invoke(op.Slides,'Add',slide_count,1);
else % Title slide with plots.
new_slide = invoke(op.Slides,'Add',slide_count,11);
% Set the text frame to autosize
new_slide.Shapes.Title.TextFrame.AutoSize=1;
% If padding is specified, use that.
if isfield(addlParms,'padding')
set(new_slide.Shapes.Title,'Top',addlParms.padding(3));
else
% Otherwise move the title up towards the top of the scope
set(new_slide.Shapes.Title,'Top',get(new_slide.Shapes.Title.TextFrame.TextRange.Font,'Size')/4);
end
% Resize the title so that it is the width of the slide
set(new_slide.Shapes.Title,'Left',0);
set(new_slide.Shapes.Title,'Width',slide_W);
% Set the 'top' of where the bottom of the title is.
top=get(new_slide.Shapes.Title,'Top')+get(new_slide.Shapes.Title,'Height');
end
% Set the text in the title to the specified title
set(new_slide.Shapes.Title.TextFrame.TextRange,'Text',addlParms.title);
else
% Slide with No Title
new_slide = invoke(op.Slides,'Add',slide_count,12);
if isfield(addlParms,'padding')
top=addlParms.padding(3);
else
top=0;
end
end
% If padding is given, use that (top is specified above)
if isfield(addlParms,'padding')
left=addlParms.padding(1);
right=addlParms.padding(2);
bottom=addlParms.padding(4);
else
bottom=0;
left=0;
right=0;
end
%% Figure Functions
% Calculate the number of rows and columns
fig.count=length(addlParms.figure);
fig.rows=(floor((fig.count-1)/addlParms.columns))+1;
fig.columns=min(fig.count,addlParms.columns);
% For each figure
for i=1:fig.count
% For title page only, skip.
if addlParms.figure(i)==0
continue;
end
% Determine what row and column the current figure is on
row=floor((i-1)/addlParms.columns);
column=mod(i-1,addlParms.columns);
% Copy the figure to the clipboard
print(addlParms.driver,['-f' num2str(addlParms.figure(i))],rendOpt,resOpt);
% Paste the contents of the Clipboard:
pic1 = invoke(new_slide.Shapes,'Paste');
% Get height and width of picture:
pic_H = get(pic1,'Height');
pic_W = get(pic1,'Width');
% If scale is specified:
if checkParm(addlParms,'scale')
% If stretch is specified, scretch the figure to it's 'box' (full
% page if there is only 1)
if checkParm(addlParms,'stretch')
set(pic1,'LockAspectRatio','msoFalse')
set(pic1,'Width',(slide_W-(left+right))/fig.columns);
set(pic1,'Height',(slide_H-(top+bottom))/fig.rows);
else
% Determine if the height or the width will be the constraint,
% then set the picture height or width accordingly
if ((slide_H)/fig.rows)/((slide_W)/fig.columns)>(pic_H+(top+bottom))/(pic_W+(left+right))
set(pic1,'Width',(slide_W-(left+right))/fig.columns);
else
set(pic1,'Height',(slide_H-(top+bottom))/fig.rows);
end
end
end
% Get the figure height and widths
fig.width=get(pic1,'Width');
fig.height=get(pic1,'Height');
% Do a vertical alignment based on input
if isfield(addlParms,'valign')
if strcmpi(addlParms.valign,'center')
set(pic1,'Top',top+0.5*(slide_H-(fig.height*fig.rows+top+bottom))+fig.height*row);
elseif strcmpi(addlParms.valign,'top')
set(pic1,'Top',top+fig.height*row);
elseif strcmpi(addlParms.valign,'bottom')
set(pic1,'Top',slide_H-(fig.height*fig.rows+bottom)+fig.height*row);
end
else
% Or default to center
set(pic1,'Top',top+0.5*(slide_H-(fig.height*fig.rows+top+bottom))+fig.height*row);
end
% Do a horizontal alignment based on input
if isfield(addlParms,'halign')
if strcmpi(addlParms.halign,'center')
set(pic1,'Left',left+0.5*(slide_W-(fig.width*min(fig.count-fig.columns*row,fig.columns)+left+right))+fig.width*column);
elseif strcmpi(addlParms.halign,'left')
set(pic1,'Left',left+fig.width*column);
elseif strcmpi(addlParms.halign,'right')
set(pic1,'Left',slide_W-(fig.width*min(fig.count-fig.columns*row,fig.columns)+left+right)+fig.width*column);
end
else
% Or default
set(pic1,'Left',left+0.5*(slide_W-(fig.width*min(fig.count-fig.columns*row,fig.columns)+left+right))+fig.width*column);
end
end
% Clean up notes & text box strings.
text={'notes','text','comments'};
for i=1:numel(text)
% If the notes are a number, convert it to text
if isfield(addlParms,text{i})
if isnumeric(addlParms.(text{i}))
addlParms.(text{i})=num2str(addlParms.(text{i}));
else
% Convert \n & \t into characters for powerpoint
warning('off','MATLAB:strrep:InvalidInputType');
addlParms.(text{i})=strrep(addlParms.(text{i}),'\t',9);
addlParms.(text{i})=strrep(addlParms.(text{i}),'\n',13);
% Convert \n into characters for powerpoint, if added via
% sprintf, eg note=sprintf('%s\n%s','Hello','World');
addlParms.(text{i})(addlParms.(text{i})==10)=13;
end
end
end
% Add notes if they are specified
if isfield(addlParms,'notes')
% Taken from this page: http://www.mahipalreddy.com/vba.htm
if get(new_slide.notesPage.Shapes,'Count')==0
% Still haven't figured this Matlab -> VBA out. AddRect returns an
% error
warning('saveppt2:nonoteadded','No note box found, none added');
else
% For each of the shapes, loop through until you find one with a
% text frame.
for i=1:get(new_slide.notesPage.Shapes,'Count')
% If it has a text frame, set the text and break out of the
% loop.
if strcmp(get(new_slide.notesPage.Shape.Item(i),'HasTextFrame'),'msoTrue')
set(new_slide.notesPage.Shape.Item(i).TextFrame.TextRange,'Text',addlParms.notes);
break;
end
end
end
end
% If comment field is specified
if isfield(addlParms,'comments')
new_comment=invoke(new_slide.Shapes,'AddComment');
set(new_comment.TextFrame.TextRange,'Text',addlParms.comments);
end
% Add textbox if it is specified
if isfield(addlParms,'text')
new_text=invoke(new_slide.Shapes,'AddTextbox','msoTextOrientationHorizontal',0,0,720,540/4);
set(new_text.TextFrame.TextRange,'Text',addlParms.text);
end
%% Exit Functions
% If saveppt2 was called after an init as part of a batch process, just
% return
if isfield(addlParms,'ppt');
return;
end
% Save the file
if ~exist(filespec,'file')
% Save file as new:
invoke(op,'SaveAs',filespec,1);
else
% Save existing file:
invoke(op,'Save');
end
% If asked to close the file.
if checkParm(addlParms,'close')
% Check if other presentations are open. If so, only close this
% powerpoint, otherwise quit the application.
if checkParm(addlParms,'close')
invoke(op,'Close');
% Sanity checking for when called from within a script. If saveppt2 are
% called too close together then the file will not be done being written to
% or powerpoint will not have completely closed, causing an error. This
% simply stalls the exit until the ActiveX object has closed. Adds an
% additional 0.001 seconds to execution, but helps prevent failures in
% loops.
% If it doesn't exit by 1000, return anyway
for i=1:1000;
try
% Try to get parameter
op.ReadOnly
catch
% When an error is thrown (the ActiveX object is destroyed), return
return;
end
end
if ppt.Presentations.Count==0
invoke(ppt,'Quit');
for i=1:1000;
try
% Try to get parameter
ppt.visible
catch
% When an error is thrown (the ActiveX object is destroyed), return
return;
end
end
end
end
else
% If the user isn't closing the presentation and is assigning the
% PowerPoint presentation object to a variable, return it.
if nargout==1
varargout{1}=op;
end
end
end
%% Supporting Functions. Here Be Dragons.
% Check to see if the parameters is 'set'
function result=checkParm(addlParms,parm)
result=0;
try
if isfield(addlParms,parm)
if islogical(addlParms.(parm))&&addlParms.(parm)==true
result=1;
end
end
catch
end
return
end
function parameters=validateInput(argsIn,validParameters,force)
%VALIDATEINPUT Validate input for m-files
% parameters - validateInput(varargin,validParameters,[force])
% varargin - passed directly from the parent script.
% validParameters - A cell of strings or cells with valid input arguments
% validParameters = {{'print','p'},{'size','s'},'name'};
% Will accept the following as valid input:
% print, -print, p, -p
% size, -size, s, -s
% name, -name
%
% If the input pararameter is specified as 'yes', 'on', or 'true' then the
% parameter is set as true. If it is 'no', 'off', or 'false' then it
% is returned as false. This is for when calling programs with out
% parenthesis.
%
% force - Force the output parameters struct to have all validParameters,
% even if they are not given. All non-specified input will be set to
% 'false'.
%
% parameters is a structure with each given input argument. In the case
% that there are multiple options, the output is set to the first
% 'option'. 'size' and 's' will both set the 'parameters.size' field.
%
% Example (This is intended to be called from within a function)
% varargin={'p','s',10,'name','john doe'}
% validParameters={{'size','s'},{'print','p'},'name'}
% parameters=validateInput(varargin,validParameters)
%
% varargin={'p','on','s',10,'name','john doe'}
% validParameters={{'size','s'},{'print','p'},'name'}
% parameters=validateInput(varargin,validParameters)
%
% varargin={'p'}
% validParameters={{'size','s'},{'print','p'},'name'}
% parameters=validateInput(varargin,validParameters,true)
%
% Author: Jedediah Frey
% Created: Apr 2010
% Copyright 2010
error(nargchk(1, 3, nargin, 'struct'))
if nargin<3
force=false;
else
force=logical(force);
end
i=1; % Set loop variable
while i<=numel(argsIn) % Do until the end of
% Determine if the current input is a valid parameter.
[validParameter,parmName]=valid(argsIn{i},validParameters);
% If it is not a valid input, die with errror.
if ~validParameter
error('validateInput:UnknownParameter',['Unknown Parameter: ' argsIn{i}]);
end
% If the parameter is the 'last' input or the next argument is a valid
% input.
if i+1>numel(argsIn)||valid(argsIn{i+1},validParameters)
% Set the parameter to true (used for 'optional' calls)
parameters.(parmName)=true;
i=i+1; % Increment counter by 1
else
% Otherwise, use the next 'input' as the parameter's value
parameters.(parmName)=argsIn{i+1};
% If the value is logical and true, sit it to true.
try
if islogical(parameters.(parmName))&¶meters.(parmName)==true
parameters.(parmName)=true;
% If it is 'yes' or 'on', set it to true.
elseif strcmpi(parameters.(parmName),'yes')||strcmpi(parameters.(parmName),'on')||strcmpi(parameters.(parmName),'true')
parameters.(parmName)=true;
elseif strcmpi(parameters.(parmName),'no')||strcmpi(parameters.(parmName),'off')||strcmpi(parameters.(parmName),'false')
parameters.(parmName)=false;
% If it is a number (that may have been passed as a string,
% then convert it to a number
elseif ischar(parameters.(parmName))&&~isnan(str2double(parameters.(parmName)))
parameters.(parmName)=str2double(parameters.(parmName));
end
catch
end
i=i+2; % Increment counter by 2
end
end
if ~force
return;
end
for j=1:numel(validParameters)
% Get the parameter name.
if iscell(validParameters{j})
name=validParameters{j}{1};
else
name=validParameters{j};
end
% If the parameter is not set, set it to false.
if ~isfield(parameters,name)
parameters.(name)=false;
end
end
end
function [validParameter,name] = valid(parameter,validParameters)
% By default the current parameter isn't valid.
validParameter=false;
name=''; % Set the parameter name to something, in case nothing is returned.
% For each of the validParameters
for j=1:numel(validParameters)
% If the parameter is a cell.
if iscell(validParameters{j})
% For each option in the cell
for k=1:numel(validParameters{j})
% If the parameter directly matches OR the first character is a
% '-' and the rest of the string match.
try
if strcmpi(validParameters{j}{k},parameter)||(strcmpi(parameter(1),'-')&&strcmpi(validParameters{j}{k},parameter(2:end)))
validParameter=true; % Set as a valid parameter.
name=validParameters{j}{1}; % Return the first cell as the variable name'
return;
end
catch
end
end
else
% If the validParameter isn't a cell, just directly compare it.
try
if strcmpi(validParameters{j},parameter)||(strcmpi(parameter(1),'-')&&strcmpi(validParameters{j},parameter(2:end)))
name=validParameters{j};
validParameter=true;
return;
end
catch
end
end
end
end
|
github
|
philippboehmsturm/antx-master
|
paste.m
|
.m
|
antx-master/mritools/basic/paste.m
| 9,652 |
utf_8
|
bf7f5acc28513bb7fad714c663a5f5da
|
% PASTE copies the content of the clipboard to a variable; creates a
% string, a cell array, or a numerical array, depending on content.
%
% Usage:
% x = paste;
% x = paste(dec,sep,lf);
%
% The program will try to create an array. For this to succeed, the
% material that is passed from the clipboard must be a tab delimited array,
% such as produced by Excel's copy command. If the content does not have
% this structure, the program simply returns a string. If the content is an
% array, x will be a numerical array if all its components qualify as
% numerical. If not, it will be a cell array.
%
% Optional arguments:
% dec Single character that indicates the decimal separator. Default is
% the period ('.').
% sep Single character that indicates how horizontal neigbors of a
% matrix or cell array are separated. Default is the tabulator code
% (char 9).
% lf Single character that indicates how rows are separated.(lf stands
% for line feed). Default is the line feed code (char 10).
%
% Examples:
%
% 1) If the clipboard contains 'George's job is to chop wood.', then
% x = paste produces x = 'George's job is to chop wood.'
%
% 2) If the content of the clipboard is a simple text with multiple lines
% (copied from Notepad or Word or similar), then x = paste produces a
% cell array with one column and one row per line of the input so each
% line of text will be separated in different cells. For example, if you
% copy the follwing text from some other program,
%
% Manche meinen lechts und rinks kann man nicht velwechsern.
% Werch ein Illtum!
%
% then, in Matlab, x = paste produces a 2x1 cell array with
%
% x{1} = 'Manche meinen lechts und rinks kann man nicht velwechsern.'
% x{2} = 'Werch ein Illtum!'
%
% [Note: x = clipboard('copy') would produce just a string in this case,
% not an array of stringcells, so choose the code that is most useful for
% your purpose.]
%
% 3) However, if your text contains an equal number of tabs on each line,
% for instance because you've copied something like this from Word,
% 1 -> item 1
% 2 -> item 2
% 3 -> item 3
% where -> denotes TABs, then x = paste produces a 3x2 cell array,
% x =
% [1] 'item 1'
% [2] 'item 2'
% [3] 'item 3'
%
% 4) If the clipboard contains an array of cells, e.g.
% 1 2 3
% 4 5 6
% for instance by copying these six cells from an Excel spreadsheet,
% then x = paste makes a 2x3 array of doubles with the same content.
% The same is true if there are NaN cells. So if the Excel excerpt was
% 1 2 3
% 4 #N/A 6
% then x =
% 1 2 3
% 4 NaN 6
%
% 5) If the cell collection in the clipboard is
% A 1.3 NaN
% then x will not be a numerical array, but a 1x3 cell array, with
% x =
% 'A' [1.3000] [NaN]
% so x{1} is a string, but x{2} and x{3} are doubles.
%
% 6) If the clipboard contains '1,2', then x=paste with no arguments will
% be 12 (because Matlabs str2double('1,2') interprets this as the number
% 12). However, x=paste(',') will return 1.2
%
% 7) If the clipboard contains '1,2 & 100', then x=paste with no arguments
% will return just the string '1,2 & 100'. x=paste(',','&'), on the
% other hand, will return a numerical array [1.2, 100].
%
% Here is a practical example:
% ----------------------------
% In Excel, select your data, say, a sample of observations organized in
% a few columns. Place them into the clipboard with Ctrl-C.
% Now switch to Matlab and say
% x = paste;
% This puts the data that you copied in Excel into a variable x in
% Matlab's workspace.
% Next, you can analyze the data. For instance, compute the principal
% components (an analysis that is not readily available in Excel), and
% push the result back into the clipboard,
% [c,s] = princomp(x);
% copy(s)
% Now, back in Excel, you can paste the result into your spreadsheet with
% Ctrl-V.
%
% This program was selected 'Pick of the Week' on March 7, 2014. :-)
%
% Author : Yvan Lengwiler
% Release: 1.51
% Date : 2014-03-19
%
% See also COPY, CLIPBOARD
% History:
% 2010-06-25 correction of a bug that occurred with multiple string
% cells on a single line.
% 2011-06-05 Simplified detection of line feeds.
% 2011-06-22 Removal of an unused variable.
% 2012-02-03 Tries to identify non-conventional decimal and thousand
% separators.
% 2013-03-19 Three optional arguments (dec, sep, and lf).
% 2014-02-21 Corrected a bug found by Jiro Doke. (Thanks, Jiro)
% 2014-03-19 Bug fix, thanks to Soren Preus.
function x = paste(dec,sep,lf)
% handle optional parameters
if nargin < 3
lf = char(10); % default is line feed (char 10)
end
if nargin < 2
sep = char(9); % default is tabulator (char 9)
end
if nargin < 1
dec = '.'; % default is a period '.'
end
% get the material from the clipboard
p = clipboard('paste');
% get out of here if nothing usable is in the clipboard
% (Note: MLs 'clipboard' interface supports only text, not images or
% the like.)
if isempty(p)
x = [];
return;
end
% find linebreaks
if p(end) ~= lf
p = [p,lf]; % append linefeed if missing
end
posLF = find(ismember(p,lf)); % find linefeeds
nLF = numel(posLF); % count linefeeds
% break into separate lines; parse each line by tab
lines = cell(nLF,1);
posTab = cell(nLF,1);
numTab = zeros(nLF,1);
last = 0;
for i = 1:nLF
lines{i} = [p(last+1:posLF(i)-1),sep]; % append a tabulator
last = posLF(i);
tabs = ismember(lines{i},sep); % find tabulators
aux = linspace(1,numel(lines{i}),numel(lines{i}));
posTab{i} = aux(tabs); % positions of tabs
numTab(i) = sum(tabs(:)); % count tabs in line
end
% is it an array (i.e. a rectangle of cells)?
isArray = true;
i = 1;
while isArray && i <= nLF
isArray = (numTab(i) == numTab(1));
i = i+1;
end
if ~isArray
% it's not an array, so just return the raw content of the clipboard
x = p;
% Note: A simple single or multi-line text with no tabs *does*
% qualify as an array, so the program splits such content line-wise
% into a one-column cell array.
else
% it is an array, so put it into a Matlab cell array
isNum = true; % will remain true if it is never switched off below
x = cell(nLF,numTab(1));
for i = 1:nLF
last = 0;
pos = posTab{i};
for j = 1:numTab(1);
x{i,j} = lines{i,1}(last+1:pos(j)-1);
% try to make numerical cells if possible
if ismember(x{i,j},{'NaN','#N/A'})
x{i,j} = NaN;
else
aux = x{i,j}; % copy to work on
% deal with decimal and thousand separators
if dec ~= '.'
aux = strrep(aux,dec,'.'); % replace decimal
% separators with periods
else
if numel(strfind(aux,'''')) > 0
% remove apostrophes
aux = strrep(aux,'''','');
% if it is a number, it is formatted conventionally
else
% determine if decimal separator is comma and
% thousand separator is period
posComma = strfind(aux,',');
posPeriod = strfind(aux,'.');
if numel(posComma) == 1 && numel(posPeriod) > 0
if all(mod(posComma-posPeriod,4) == 0) && ...
posComma > posPeriod(end)
% this is potentially a non-conventionally
% formatted number: remove periods first,
% then replace comma with period
aux = strrep(aux,'.','');
aux = strrep(aux,',','.');
end
end
end
end
% determine if the cell is numerical
aux = str2double(aux); % try to make a double
if isnan(aux)
% this cell is not numerical (turn off switch for
% later)
isNum = false;
else
% str2double has produced a ligit number
x{i,j} = aux;
end
end
last = pos(j);
end
end
if isNum % make a numerical array if possible
x = cell2mat(x);
end
end
% remove cell encapsulation if there is only one cell
if numel(x) == 1
try
x = x{1};
end
end
|
github
|
philippboehmsturm/antx-master
|
explorer.m
|
.m
|
antx-master/mritools/basic/explorer.m
| 587 |
utf_8
|
51c33caf85e473fe358d5135101462b3
|
%%open explorerWindow
% function explorer(paths)
% paths: []points to pwd | singlepath | cell of multiple paths
%% examples
% explorer
% explorer(which('ws.m'))
%explorer({'c:\';'T:\'})
function explorer(paths)
if exist('paths')==1
if ischar(paths);
paths={paths} ;
end
else
paths={pwd} ;
end
for i=1:length(paths)
[pa2 pa ext]=fileparts(paths{i});
if isempty(ext)
% eval(['!start ' paths{i} ]);
eval(['!explorer ' paths{i} ]);
else
% eval(['!start ' pa2 ]) ;
eval(['!explorer ' pa2 ]) ;
end
end
|
github
|
philippboehmsturm/antx-master
|
foo.m
|
.m
|
antx-master/mritools/basic/foo.m
| 368 |
utf_8
|
4b9faa18de94fd280b2356eb1c3e7b30
|
% in the command window
% fh=foo; % load the function handles to the subfunctions
% fh.msub(10,5)
% fh.madd(pi,pi)
function fh=foo
fh.msub=@msub;
fh.madd=@madd;
end
function r=msub(a,b)
r=a-b;
end
function r=madd(a,b)
r=a+b;
end
% % in the command window
% fh=foo; % load the function handles to the subfunctions
% fh.msub(10,5)
% fh.madd(pi,pi)
|
github
|
philippboehmsturm/antx-master
|
copyfilem.m
|
.m
|
antx-master/mritools/basic/copyfilem.m
| 350 |
utf_8
|
a0489299e41cdbba11041a05ab090bf0
|
% mass-copy files ;
% input:
% f1: cell of files =sources (this are copied)
% f2: cell of filenames to create
% f1 and f2 match in size
function copyfilem(f1,f2)
% f1=s.a
% f2=stradd(s.a,'c')
if ischar(f1)
f1=cellstr(f1);
end
if ischar(f2)
f2=cellstr(f2);
end
for i=1:length(f1)
copyfile(f1{i}, f2{i} ,'f');
end
|
github
|
philippboehmsturm/antx-master
|
copyc.m
|
.m
|
antx-master/mritools/basic/copyc.m
| 4,281 |
utf_8
|
88c9009ee763f7ef71ddb03510964860
|
%% copy cell 2d-cell of strings to matlabs -style {',,,' '...' ; ',,,' '...' }
function out = copy2(a, delim)
%MAT2CLIP Copies matrix to system clipboard.
%
% MAT2CLIP(A) copies the contents of 2-D matrix A to the system clipboard.
% A can be a numeric array (floats, integers, logicals), character array,
% or a cell array. The cell array can have mixture of data types.
%
% Each element of the matrix will be separated by tabs, and each row will
% be separated by a NEWLINE character. For numeric elements, it tries to
% preserve the current FORMAT. The copied matrix can be pasted into
% spreadsheets.
%
% OUT = MAT2CLIP(A) returns the actual string that was copied to the
% clipboard.
%
% MAT2CLIP(A, DELIM) uses DELIM as the delimiter between columns. The
% default is tab (\t).
%
% Example:
% format long g
% a = {'hello', 123;pi, 'bye'}
% mat2clip(a);
% % paste into a spreadsheet
%
% format short
% data = {
% 'YPL-320', 'Male', 38, true, uint8(176);
% 'GLI-532', 'Male', 43, false, uint8(163);
% 'PNI-258', 'Female', 38, true, uint8(131);
% 'MIJ-579', 'Female', 40, false, uint8(133) }
% mat2clip(data);
% % paste into a spreadsheet
%
% mat2clip(data, '|'); % using | as delimiter
%
% See also CLIPBOARD.
% VERSIONS:
% v1.0 - First version
% v1.1 - Now works with all numeric data types. Added option to specify
% delimiter character.
%
% Copyright 2009 The MathWorks, Inc.
%
% Inspired by NUM2CLIP by Grigor Browning (File ID: 8472) Matlab FEX.
error(nargchk(1, 2, nargin, 'struct'));
if ndims(a) ~= 2
error('mat2clip:Only2D', 'Only 2-D matrices are allowed.');
end
% each element is separated by tabs and each row is separated by a NEWLINE
% character.
sep = {'\t', '\n', ''};
if nargin == 2
if ischar(delim)
sep{1} = delim;
else
error('mat2clip:CharacterDelimiter', ...
'Only character array for delimiters');
end
end
% try to determine the format of the numeric elements.
switch get(0, 'Format')
case 'short'
fmt = {'%s', '%0.5f' , '%d'};
case 'shortE'
fmt = {'%s', '%0.5e' , '%d'};
case 'shortG'
fmt = {'%s', '%0.5g' , '%d'};
case 'long'
fmt = {'%s', '%0.15f', '%d'};
case 'longE'
fmt = {'%s', '%0.15e', '%d'};
case 'longG'
fmt = {'%s', '%0.15g', '%d'};
otherwise
fmt = {'%s', '%0.5f' , '%d'};
end
if iscell(a) % cell array
a = a';
floattypes = cellfun(@isfloat, a);
inttypes = cellfun(@isinteger, a);
logicaltypes = cellfun(@islogical, a);
strtypes = cellfun(@ischar, a);
classType = zeros(size(a));
classType(strtypes) = 1;
classType(floattypes) = 2;
classType(inttypes) = 3;
classType(logicaltypes) = 3;
if any(~classType(:))
error('mat2clip:InvalidDataTypeInCell', ...
['Invalid data type in the cell array. ', ...
'Only strings and numeric data types are allowed.']);
end
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=[ '{' sprintf(sprintf('''%s''%s', tmp{:}), a{:}) '}']
elseif isfloat(a) % floating point number
a = a';
classType = repmat(2, size(a));
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=sprintf(sprintf('%s%s', tmp{:}), a(:));
elseif isinteger(a) || islogical(a) % integer types and logical
a = a';
classType = repmat(3, size(a));
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=sprintf(sprintf('%s%s', tmp{:}), a(:));
elseif ischar(a) % character array
% if multiple rows, convert to a single line with line breaks
if size(a, 1) > 1
b = cellstr(a);
b = ['{' sprintf('''%s''\n', b{1:end-1}) , sprintf('''%s''\n', b{1:end}) '}' ]
else
b = a;
end
else
error('mat2clip:InvalidDataType', ...
['Invalid data type. ', ...
'Only cells, strings, and numeric data types are allowed.']);
end
clipboard('copy', b);
if nargout
out = b;
end
|
github
|
philippboehmsturm/antx-master
|
cprintf2.m
|
.m
|
antx-master/mritools/basic/cprintf2.m
| 1,834 |
utf_8
|
812361e55a2246989fbc2d1aa09082cc
|
function count = cprintf2(style,format,header,varargin)
% for cellarry
% cprintf2([1 0 1], z.pp ,'DONE' );
% cprintf2([1 0 0], {'affe','mensch','klopapier'} ,'DONE' );
% cprintf2({[1 0 0] ;[0 .5 0] },{z.pp z.pp2} ,{'toDO' 'DONE'} );
if ~iscell(style)
if exist('header')~=0
if ~isempty(header)
cprintf(-style, [ ' ' header '\n'] );
end
end
for i=1:length(format);
dum=[char(format{i})];
% dum=strrep(dum,'.','/.')
cprintf(style, [ ' ' dum '\n'] );
end
else %multiTable
% cprintf2({[1 0 1] ;[0 1 0] },{z.pp2 z.pp} ,{'DONE' 'notDone'} );
isheader=0;
if exist('header')~=0
if ~isempty(header)
% for i=1:length(header)
% cprintf(-style{i}, [ ' ' header{i} '\t'] );
% end
% cprintf(-style{i}, [ '\n'] );
isheader=1;
for i=1:length(format)
format{i}=[ header{i}; format{i}(:) ];
end
end
else
% header= repmat({''},[1 length(format)]);
end
len= (cellfun(@length, (format)));
imax=max(len);
for j=1:imax
for i=1:length(format)
dum=repmat(' ',[1 ...
size(char([format{:,i} ]),2) ] );
if j>len(i)
dum2='';
else
dum2=char(format{i}(j));
end
dum(1:length(dum2))=dum2;
if j==1
if isheader==1
cprintf(-style{i}, [ ' ' dum '\t'] );
else
cprintf(style{i}, [ ' ' dum '\t'] );
end
else
cprintf(style{i}, [ ' ' dum '\t'] );
end
end
cprintf(-style{i}, [ '\n'] );
end
cprintf(-style{i}, [ '\n'] );
end
|
github
|
philippboehmsturm/antx-master
|
pdir.m
|
.m
|
antx-master/mritools/basic/pdir.m
| 1,389 |
utf_8
|
c88a30f31ea56bc9fdb66a7bb691c488
|
%% get files/dirs/all from path
% [files FPfiles]=pdir(pathx, modex, flt )
%% IN
% pathx :path to search (optional), default pwd
% modex :type to search (optional), default 'file' use['file' |'dir' |'all']
% flt :window filter (optional),default '*.*'
% %% OUT
% files elements (files and or folders)
% FPfiles] fullpath elements
%% EXAMPLES
% [files FPfiles]=pdir(pwd,'dir')
% [files FPfiles]=pdir(pwd,'file')
% [files FPfiles]=pdir(pwd,'all')
% [files FPfiles]=pdir('c:\','all')
% [files FPfiles]=pdir('c:\','file','*.sys')
%
function [files FPfiles]=pdir(pathx, modex,flt )
% pathx=pa
% flt='*.*'
% modex='file'
if exist('pathx')==0; pathx=[]; end
if exist('flt')==0; flt =[]; end
if exist('modex')==0; modex=[]; end
if isempty(pathx); pathx=pwd; end
if isempty(flt); flt='*.*'; end
if isempty(modex); modex=2; end
% pathx
% flt
% modex
k=dir(fullfile(pathx,flt));
if isempty(k)
[ files FPfiles]=deal([]);
return
end
d=[{k(:).isdir}'];
n={k(:).name}';
n(:,2)=[{k(:).isdir}'];
%delete ./..
try; n(strcmp(n(:,1),'.'),:)=[]; end
try; n(strcmp(n(:,1),'..'),:)=[]; end
if strcmp(modex,'file')
n(cell2mat(n(:,2))==1,:)=[];
elseif strcmp(modex,'dir')
n(cell2mat(n(:,2))==0,:)=[];
end
files =n(:,1);
FPfiles=cellfun(@(files)[fullfile(pathx, files )],files,'UniformOutput',0);
|
github
|
philippboehmsturm/antx-master
|
copy.m
|
.m
|
antx-master/mritools/basic/copy.m
| 6,238 |
utf_8
|
06fe29236a1db0782c1d2bc8a53db0ac
|
% COPY puts a string, cell array, or numerical array into the clipboard,
% from where it can easily be imported by other programs.
%
% Usage:
% copy(x)
% copy(...,dec,sep,lf)
%
% x can be a numerical array (one or two dimensional), a cell array, a
% string, or a handle to a figure. The program does not handle other
% variable classes, such as struct etc. and also is not suitable for arrays
% with more than two dimensions.
%
% Optional arguments:
% dec Single character that indicates the decimal separator. Default is
% the period ('.').
% sep Single character that indicates how horizontal neigbors of a
% matrix or cell array are separated. Default is the tabulator code
% (char 9).
% lf Single character that indicates how rows are separated. (lf
% stands for line feed). Default is the line feed code (char 10).
%
% Examples:
% copy('One small step for a man.') pushes just this string to the
% clipboard.
% copy([1.2,-500]) pushes '1.2 -> -500' to the clipboard
% (-> is the tabulator code).
% copy([1.2,-500],',','&') pushes '1,2 & -500' to the clipboard.
% f = figure; surf(membrane); copy(f) copies the figure to the clipboard.
%
% Note: This program was inspired by NUM2CLIP on the Mathworks file
% exchange, see http://www.mathworks.com/matlabcentral/fileexchange/8472
%
% This program was selected 'Pick of the Week' on March 7, 2014. :-)
%
% Author : Yvan Lengwiler
% Release: 1.52
% Date : 2014-11-30
%
% See also PASTE, CLIPBOARD, HGEXPORT
% History:
% 2010-06-25 First version.
% 2010-07-10 Now also covers multiline character arrays.
% 2011-06-05 Using strrep instead of regexprep.
% 2011-06-22 Special treatment of empty cells (Thank you, Joseph Burgel).
% 2013-03-19 Added dec, sep, and lf options.
% 2014-02-20 Support for tables (ML R2013b), suggested by Greg.
% 2014-02-21 Support for logical variables. Also, two small bug fixes.
% 2014-03-19 Bug fix, thanks to Soren Preus.
% 2014-11-30 Support for copying figures.
function copy(x,dec,sep,lf)
% *** separators *****************************************************
if nargin < 4
lf = char(10); % default is line feed (char 10)
end
if nargin < 3
sep = char(9); % default is tabulator (char 9)
end
if nargin < 2
dec = '.'; % default is a period '.'
end
% *** figure *********************************************************
if ishghandle(x,'figure');
if nargin > 1
warning('COPY:unused_parameters', ...
['Object is a figure, ignoring all parameters after ', ...
'the first one.']);
end
hgexport(x,'-clipboard');
% *** string argument ************************************************
elseif isa(x,'char')
[r,c] = size(x);
if r == 1 % not a multi-line character array ...
clipboard('copy',x); % ... so just push the string into the
% clipboard
else
x = [x, repmat(lf,r,1)]; % append linefeed to each line
x = reshape(x',1,r*(c+1)); % make it a single line
clipboard('copy',x); % push this to the clipboard
end
% *** numeric argument ***********************************************
elseif isa(x,'numeric') || isa(x,'logical')
s = mat2str(x); % write as [.. .. ..;.. .. ..]
s = strrep(s,'.',dec); % replace decimal separators
if s(1)=='[' % it's a proper array
s = s(2:end-1); % remove '[' and ']'
end
s = strrep(s,' ',sep); % replace spaces with tabs
s = strrep(s,';',lf); % replace semicolons with linefeeds
s(end+1) = lf; % append a linefeed
clipboard('copy',s); % place resulting string in clipboard
% *** cell argument **************************************************
elseif isa(x,'cell')
[nrow, ncol] = size(x);
str = '';
for r = 1:nrow
for c = 1:ncol-1
str = onecell(str, x{r,c}, sep, dec); % treat cell, append a tab
end
str = onecell(str, x{r,end}, lf, dec); % treat cell, append a linefeed
end
clipboard('copy',str); % copy to clipboard
% *** table (This is Greg's contribution. Thank you, Greg!) **********
elseif isa(x,'table') % table is a feature of R2013b
if nargin > 1
warning('COPY:unused_parameters', ...
'Object is a table, ignoring all parameters after the first one.');
end
xheaders = x.Properties.VariableNames;
xrownames = x.Properties.RowNames;
xdescr = {x.Properties.Description};
xt = table2cell(x);
if ~isempty(xt) % it's an empty table
if isempty(xrownames)
xrownames = repmat({''},height(x),1);
end
xt = [xdescr,xheaders;xrownames,xt];
if isempty(cat(2,xt{:,1}))
xt(:,1) = [];
end
end
copy(xt); % recursive call of copy.m
% *** anything else **************************************************
else
warning('COPY:unsupported_content', ...
'Cannot copy this kind of object.');
end
% *** convert one cell into a string; append it to str and append a special
% character (ch = tab or linefeed)
function str = onecell(str,e,ch,dec)
if isempty(e)
str = [str, ch]; % copy nothing if cell is empty
elseif isa(e,'char')
if size(e,1) == 1 % not a multi-line char array?
str = [str, e, ch];
else
str = [str, mat2str(e), ch];
end
elseif isa(e,'numeric') || isa(e,'logical')
str = [str, strrep(mat2str(e),'.',dec), ch];
else
str = [str, '(cannot copy component)', ch];
end
|
github
|
philippboehmsturm/antx-master
|
strsplit2.m
|
.m
|
antx-master/mritools/basic/strsplit2.m
| 429 |
utf_8
|
3dd0486ba38026bd1112df1217f41d76
|
% split string into tokens separated by delim
% if no delimiter is given, white space characters are used as delimiters
% syntax: Tokens = strsplit(Delim, String)
function Tokens = strsplit2(String, Delim)
Tokens = [];
while (size(String,2) > 0)
if isempty(Delim)
[Tok, String] = strtok(String);
else
[Tok, String] = strtok(String, Delim);
end
Tokens{end+1} = Tok;
end
|
github
|
philippboehmsturm/antx-master
|
timestr.m
|
.m
|
antx-master/mritools/basic/timestr.m
| 279 |
utf_8
|
259e40678e8c60267fa0a221588a8ea0
|
% get formated current time , used as filePrefix
% function str=timestr
function str=timestr(sep)
if exist('sep')==1
str=regexprep(datestr(now),{'-' ' ' ':'},{'' '_' ,'-'}) ; %with - between HH:MM:SS
else
str=regexprep(datestr(now),{'-' ' ' ':'},{'' '_' ,''});
end
|
github
|
philippboehmsturm/antx-master
|
psavefigs.m
|
.m
|
antx-master/mritools/basic/psavefigs.m
| 1,172 |
utf_8
|
85c61faf27e42d6d9bd83fd99eb4872d
|
function psavefigs(folder)
% function psavefigs(folder)
%
o=regexprep(datestr(now),{':' ' ' },'_');
ch=flipud(get(0,'children'));
mkdir(folder);
for i=1:length(ch)
tx=['save Image "' num2str(i) '" to folder "' folder '"' ];
try
cprintf(rand(1,3),[tx '\n']);
catch
disp(tx);
end
chi=ch(i);
set(chi,'InvertHardcopy','off');
name=[ num2str(chi) '_' get(chi,'name') '_' o];
if strcmp(get(chi,'tag'),'uhelp')
%saveas(chi,fullfile(pwd,folder,name),'fig');
try
x=get(chi,'userdata');
dataX=(x.e0);
clas=class(dataX);
fid = fopen(fullfile(pwd,folder,[name '.txt' ]),'w','n');
if ( strcmp(clas,'cell')==1 | strcmp(clas,'char')==1)
for i=1:size(dataX,1)
dumh=char( (dataX(i,:)) );
fprintf(fid,'%s\n',dumh);
end
end
fclose(fid);
catch
try; fclose(fid);end
end
else
%saveas(chi,fullfile(pwd,folder,name),'jpg');
print(chi,'-djpeg','-r200',fullfile(pwd,folder,name));
end
end
|
github
|
philippboehmsturm/antx-master
|
xlsindex.m
|
.m
|
antx-master/mritools/basic/xlsindex.m
| 242 |
utf_8
|
26e17c2ce9f33ee338f1c1114215886f
|
%get excelindex (Az,BB...)
function xls_idx = xlsindex(idx)
xls_idx = [];
while idx>0
xls_idx = [char(mod(idx-1,26)+65), xls_idx];
if mod(idx,26)
idx = fix(idx/26);
else
idx = fix(idx/26)-1;
end
end
|
github
|
philippboehmsturm/antx-master
|
cell2str.m
|
.m
|
antx-master/mritools/basic/cell2str.m
| 357 |
utf_8
|
1409b98cede395a89c17f1afe3d29c24
|
%% concatenate cells to a string
% function b=cell2str(a,sep)
% cell2str({'aa' 'bb' 'cc' 'dd'} , '_');
% cell2str({'aa' 'bb' 'cc' 'dd'});
function b=cell2str(a,sep)
if ~exist('sep') ; sep=''; end
if length(a)==1
b=char(a);
else
b='';
for i=1:length(a)-1
b=[b a{i} sep ];
end
b=[b a{i+1} ];
end
|
github
|
philippboehmsturm/antx-master
|
preadfile.m
|
.m
|
antx-master/mritools/basic/preadfile.m
| 4,083 |
utf_8
|
df20068c8d598f5bb802667faa02903a
|
function [dat]=preadfile(fil,varargin);
%___________________________________________________________________________
% % function [dat ]=preadfile(fil,varargin);
%___________________________________________________________________________
% Rread file (e.g *.vmrk/*.m/*.txt)
% ##optional##
% function [mark,infmrk]=preadfile(fil,FSheadend,FSfileend);
% with 'characters' to find for HEADER-END & FILE-END
% IN__
% fil- inputfile with format-end
% OUT__
% strukt with...
% dat.all -all in file;
% with options also [dat.header & dat.txt =header and below header;
%
% expl:
% fil='C:\NP3\visionanalyzer\marker_files\108_1_eeg.vmrk';
% [mark,infmrk]=pEEGreadVMRK(fil);
% _________________________________________________________________________
% see also preadfile pwrite2file
%___________________________________________________________________________
% paul,BNIC, mar.2007
%___________________________________________________________________________
% fil=('F:\NIRS\NIRS_newborn\01\01_nirs.txt'); %DELETE this
%======================1.1 READ=====================================================
fid=fopen(fil);
j=1;
while 1
% d{j,1} = fgetl(fid);
% % if ~ischar(tline), break, end
% % d{j,1}=tline;
% j=j+1;
tline = fgetl(fid);
if ~ischar(tline), break, end
d{j,1}=tline;
j=j+1;
end
fclose(fid);
if exist('d')==0
d=' ';
end
%=====================1.2 separate header and real markers (no 'new segments')=================================================
if nargin==3
FSheadend=varargin{1};
FSfileend=varargin{2};
% FSheadend='#DATA BEGINS'; clear HTIS;
% FSfileend='#DATA ENDS'
Fadditheadline=2;
FSline=' ' ;
markALL=char(d);
% markALL(100:7400,:)=[];
%==========================================================================
% llinewise check
%==========================================================================
%=
h=1; k=1;
for j=1:size(markALL)
if h==1 %HEADER
if isempty(findstr(markALL(j,:),FSheadend))==1
header(j,:)=markALL(j,:);
else
h=0;T=j;
end
elseif h==0 %MARKER
if isempty(findstr(markALL(j,:),FSline))==0 &...
isempty(findstr(markALL(j,:),FSfileend))==1;
% disp(markALL(j,:));
mrk{k,:}=markALL(j,:); %
k=k+1;
else
% part=mrk(k,:);
% part
h=999;
end
end
end
%=====================%=====================
% out- 2
%=====================%=====================
dat.header=(header);
dat.dat= (mrk);
% dat.header=char(header);
% dat.dat=char(markALL);
end
%=====================%=====================
% out- 2
%=====================%=====================
dat.all=(d);
% dat.all=char(d);
%#############################################
% if 1
%
% % infmrk.mrktyp=unique(mark(:,1));
% end
% %
% %
% % % BK
% %
% % h=1; k=1;
% % for j=1:size(markALL)
% % if h==1 %HEADER
% % if isempty(findstr(markALL(j,:),'Mk1'))==1
% % header(j,:)=markALL(j,:);
% % else
% % h=0;
% % end
% % elseif h==0 %MARKER
% % if isempty(findstr(markALL(j,:),'Stimulus'))==0; %select ONLY STIMULUS nothing else
% % mrk(k,:)=markALL(j,:); %'no NEW SEGMENTS or RESPONSE'
% % k=k+1;
% % end
% % end
% % end
% %
% %
% % %===================== 1.3 extract mrk and timecolumn as double =================================================
% % for j=1:size(mrk)
% % dum=findstr(mrk(j,:),',');
% % mark(j,:)=[ str2num(mrk(j,dum(1)+2:dum(2)-1)) str2num(mrk(j,dum(2)+1:dum(3)-1)) ];
% % end
% %
% %
% % infmrk.header=header;
% % infmrk.mrkALL=markALL;
% % infmrk.mrktyp=unique(mark(:,1));
|
github
|
philippboehmsturm/antx-master
|
documentthis.m
|
.m
|
antx-master/mritools/basic/documentthis.m
| 1,088 |
utf_8
|
e0f2ea9a73f6100a7a68c681aee40438
|
function documentthis(pa, fi,figs)
% documentthis([path.res], 'test2')
% documentthis('test.ppt', 'test2',[1 2 3])
if 0
pa=path.res
fi='muell'
end
if ~exist('figs'); figs=[]; end
if isempty(figs);
figs=sort(findobj(0,'type','figure'));
end
if ~exist('fi'); fi=[]; end
if isempty(fi);
save_file=pa;
else
save_file=fullfile(pa,fi );
end
save_file=[regexprep(save_file,{'.ppt','.PPT'},{'',''}) '.ppt'];
ppt=saveppt2(save_file,'init');
for i=1:length(figs)
set(0,'currentfigure',figs(i)); figure(i); drawnow;
% pause(.1);
% saveppt2('ppt',ppt)
saveppt2('ppt',ppt,'driver','bitmap', 'res',150);%,'driver','bitmap','scale','stretch');
% saveppt2('ppt',ppt,'driver','bitmap','scale','stretch');
% if mod(i,5)==0 % Save half way through incase of crash
% saveppt2('ppt',ppt,'save');
% end
end
saveppt2(save_file,'ppt',ppt,'close');
%
% saveppt2('test.ppt','driver','meta','scale','stretch');
% saveppt2('test.ppt','driver','bitmap','scale','stretch');
|
github
|
philippboehmsturm/antx-master
|
logMessage.m
|
.m
|
antx-master/mritools/snips/logMessage.m
| 1,909 |
utf_8
|
032080759d77c4301449d314377fcd43
|
function logMessage(jEditbox,text,severity)
if 0
fg
hEditbox=uicontrol('style','edit','units','normalized','position',[0 0 1 1])
jEditbox=findjobj(hEditbox)
e=hEditbox
% jEditbox.setEditorKit(javax.swing.text.html.HTMLEditorKit);
% % alternative: jEditbox.setContentType('text/html');
htmlStr = ['<b><div style="font-family:impact;color:green">'...
'Matlab</div></b> GUI is <i>' ...
'<font color="red">highly</font></i> customizable'];
% jEditbox.setText(htmlStr)
logMessage(jEditbox, 'a regular info message...');
logMessage(jEditbox, 'a warning message...', 'warn');
logMessage(jEditbox, 'an error message!!!', 'error');
logMessage(jEditbox, 'a regular message again...', 'info');
end
% Ensure we have an HTML-ready editbox
HTMLclassname = 'javax.swing.text.html.HTMLEditorKit';
if ~isa(jEditbox.getEditorKit,HTMLclassname)
jEditbox.setContentType('text/html');
end
% Parse the severity and prepare the HTML message segment
if nargin<3, severity='info'; end
switch lower(severity(1))
case 'i', icon = 'greenarrowicon.gif'; color='gray';
case 'w', icon = 'demoicon.gif'; color='black';
otherwise, icon = 'warning.gif'; color='red';
end
icon = fullfile(matlabroot,'toolbox/matlab/icons',icon);
iconTxt =['<img src="file:///',icon,'" height=16 width=16>'];
msgTxt = [' <font color=',color,'>',text,'</font>'];
newText = [iconTxt,msgTxt];
endPosition = jEditbox.getDocument.getLength;
if endPosition>0, newText=['<br/>' newText]; end
% Place the HTML message segment at the bottom of the editbox
currentHTML = char(jEditbox.getText);
jEditbox.setText(strrep(currentHTML,'</body>',newText));
endPosition = jEditbox.getDocument.getLength;
jEditbox.setCaretPosition(endPosition); % end of content
end
|
github
|
philippboehmsturm/antx-master
|
snip_contour.m
|
.m
|
antx-master/mritools/snips/snip_contour.m
| 4,559 |
utf_8
|
dc3d6b94d65624d09220dbf531ae2c61
|
function bla
% aa='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\_Atpl_mouseatlasNew_left.nii'
% bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\elx_T2_left-0.nii'
bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\_Atpl_mouseatlasNew.nii'
% bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\hx_T2.nii'
% aa='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\elx_T2-0.nii'
aa='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\hx_T2.nii'
[haa a]=rgetnii(aa);
[hbb b]=rgetnii(bb);
[pas f1 ext]=fileparts(aa);
[pas f2 ext]=fileparts(bb);
a=a-min(a(:)); a=a./max(a(:));
b=b-min(b(:)); b=b./max(b(:));
siz=size(a);
% fg,imagesc(nanmean(cat(3,a1.*c1,b1.*c2),3))
% fg,imagesc(nanmean(cat(3,imadjust(a1).*c1,imadjust(b1).*c2),3))
dim=2
slices=[ 60 100 120 150]
slices=[50:5:200]
slices=[ 40:5:80]
slices=('5')
slices=('12 10'); %first is stepsize ,2nd is start/stop
ncontours=4;
rot=1;
flipd=1;
crop=[0 0 0 0] ;%unten oben links rechts
% crop=[ 0.3 0 0.1 0.1 ] ;%unten oben links rechts
crop=[ 0.15 0 0.05 0.05 ] ;%unten oben links rechts
crop=[ 0 0 0.05 0.3 ]
%MNI
% slices=1:siz(dim)
if dim==1
a=permute(a,[2 3 1]);
b=permute(b,[2 3 1]);
elseif dim==2
a=permute(a,[1 3 2]);
b=permute(b,[1 3 2]);
end
if ischar(slices)
if length(str2num(slices))==1
slices=1:str2num(slices):size(a,3)
slices(find(slices==1))=[];
else
dum=str2num(slices)
slices=dum(2):dum(1):size(a,3)-dum(2)
end
end
co=zeros(length(slices),3); co(:,dim)=slices;
mm=mni2idx( co' , haa, 'idx2mni' );
mm=mm(:,dim);
nb=length(slices);
[p,n]=numSubplots(nb);
figure;
set(gcf,'color','k','units','normalized');
ha = tight_subplot(p(1),p(2),[0 0],[0 .025],[.01 .01]);
set(ha,'color','k');
for i=1:length(slices)
axes(ha(i));
nn=slices(i);
a1=(squeeze(a(:,:,nn)));
b1=(squeeze(b(:,:,nn)));
a1=a1-min(a1(:)); a1=a1./max(a1(:));
b1=b1-min(b1(:)); b1=b1./max(b1(:));
if rot==1; a1=a1'; b1=b1'; end
if flipd==1; a1=flipud(a1); b1=flipud(b1);end
% if ~isempty(crop)
si=size(a1);
bord1=[ round(si(1)*crop(2))+1 si(1)-round(si(1)*crop(1)) ];
bord2=[ round(si(2)*crop(3))+1 si(2)-round(si(2)*crop(4)) ];
bord=[bord1;bord2];
a1=a1(bord(1,1):bord(1,2),bord(2,1):bord(2,2));
b1=b1(bord(1,1):bord(1,2),bord(2,1):bord(2,2));
% dd= a1(bord(1,1):bord(1,2),bord(2,1):bord(2,2))
% fg,subplot(2,2,1);imagesc(a1);subplot(2,2,2);imagesc(dd)
% end
a1=imadjust(a1);
b1=imadjust(b1);
image(cat(3,a1,a1,a1)); hold on;
contour(b1,ncontours,'linewidth',1.5,'linestyle',':');
te=text(0,1,['' num2str(slices(i)) '\color[rgb]{0.7569 0.8667 0.7765}' sprintf(' [%2.2f]',mm(i))],...
'tag','txt','color','r','units','normalized',...
'fontunits','normalized','fontsize',.05,'fontweight','bold','verticalalignment','top');
axis off;
end
ptitle([f1 ' - ' f2]);
set(gcf,'color','k','InvertHardcopy','off');
if 0
print(gcf,'-djpeg','-r300',fullfile(pwd,'test3.jpg'));
end
function [p,n]=numSubplots(n)
while isprime(n) & n>4,
n=n+1;
end
p=factor(n);
if length(p)==1
p=[1,p];
return
end
while length(p)>2
if length(p)>=4
p(1)=p(1)*p(end-1);
p(2)=p(2)*p(end);
p(end-1:end)=[];
else
p(1)=p(1)*p(2);
p(2)=[];
end
p=sort(p);
end
%Reformat if the column/row ratio is too large: we want a roughly
%square design
while p(2)/p(1)>2.5
N=n+1;
[p,n]=numSubplots(N); %Recursive!
end
function ptitle(tex,varargin)
% tex='abssdffdde'
ha=axes('position',[0 0 1 1],'color','none',...
'visible','off','HitTest','off','tag','subtitle');
te=text(0,1,tex,...
'tag','txt2','color','w','units','normalized',...
'fontunits','normalized','fontsize',.02,'fontweight','bold','verticalalignment','top',...
'horizontalalignment','left');
set(te,'interpreter','none');
% h=text(.5,.97,tex,'horizontalalignment','center','fontsize',20,'tag','txt2');
% uistack(ha,'bottom');
% set(ha,'visible','off','HitTest','off','tag','subtitle')
if ~isempty(varargin)
set(h,varargin{:}) ;
end
|
github
|
philippboehmsturm/antx-master
|
snip_test_table.m
|
.m
|
antx-master/mritools/snips/snip_test_table.m
| 5,693 |
utf_8
|
7318335f079ff9d81732894b6a6be12d
|
function test_table(tb)
if 1
% colortag='<html><div style="background:yellow;">Panel 1'
colortag='<html><div style="color:red;"> '
% % colortag='<html><TD BGCOLOR=#40FF68>'
tbsel=cellfun(@(tb) [ colortag tb],tb,'UniformOutput',0)
end
if 0
colergen = @(color,text) ['<html><table border=0 width=1000 bgcolor=',color,'><TR><TD>',text,'</TD></TR> </table></html>'];
% % colergen = @(color,text) ['<html><table border=0 width=1400 bgcolor=',color,'><TR><TD>',text,'</TD></TR> </table></html>'];
for i=1:size(tb,1)
for j=1:size(tb,2)
tbsel{i,j}=colergen('#00FF00',tb{i,j});
end
end
end
% data = { 2.7183 , colergen('#FF0000','Red')
% 'dummy text' , colergen('#00FF00','Green')
% 3.1416 , colergen('#0000FF','Blue')
% }
% uitable('data',data)
us.tb=tb;
us.tb0=tb;
us.tbsel=tbsel;
us.sel=zeros(size(tb,1),1);
% tb=us.tbsel;
cf
fg; set(gcf,'units','norm','position', [0.3212 0.0561 0.4271 0.8644]);
set(gcf,'userdata',us);
headers = {['Filename ' repmat(' ' ,[1 size(char(tb(:,1)),2)])], ...
'<html><center>Sizw<br />MB</center></html>', ...
'<html><center>Date recorded <br />recordkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</center></html>', ...
'<html><center>Seqeunce<br />---</center></html>'};
t = uitable('Data',tb, 'ColumnEditable',false, ...
'ColumnName',headers, 'RowName',[], ...
'ColumnFormat',[repmat({'char'},1,size(tb,2))], ...
'ColumnWidth','auto')%, ...
% 'Units','norm', 'Position',[0,.75,1,.25]);
set(t,'Units','norm');
set(t,'Position',[0.0,0,1,1]);
set(t,'fontsize',15)
% jScroll = findjobj(t);
% jTable = jScroll.getViewport.getView;
% jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
% tableextent = get(t,'Extent');
% oldposition = get(t,'Position');
% newposition = [oldposition(1) oldposition(2) tableextent(3) tableextent(4)];
% set(t, 'Position', newposition);
lb=uicontrol('Style','pushbutton','units','normalized', 'Position',[.7 .5 .1 .1])
set(t,'CellSelectionCallback',@dothis)
% uu=findjobj(t)
% rows=uu.getComponent(0).getComponent(0).getSelectedRows+1
% cols=uu.getComponent(0).getComponent(0).getSelectedColumns+1
function dothis(t,id)
methodjava(t,id) %function to use java updata
%convent(t,id) ;%conventional method
function methodjava(t,id)
us=get(gcf,'userdata');
jscroll = findjobj(t);
try
% ---------remember scrolling-I--------------------
% http://www.mathworks.com/matlabcentral/newsreader/view_thread/307912
% jTable = findjobj(t); % hTable is the handle to the uitable object
jScrollPane = jscroll.getComponent(0);
javaObjectEDT(jScrollPane); % honestly not sure if this line matters at all
currentViewPos = jScrollPane.getViewPosition; % save current position
end
jtable = jscroll.getViewport.getComponent(0);
% jtable.setValueAt(java.lang.String('This value will be inserted'),0,0); % to insert this value in cell (1,1)
idx=id.Indices;
for i=1:size(idx)
this=idx(i);
if us.sel(this)==0 %selected for process NOW
us.sel(this)=1;
%us.tb(this,:)=us.tbsel(this,:);
for j=1:size(us.tb,2)
jtable.setValueAt(java.lang.String(us.tbsel{this,j}),this-1,j-1);
end
else%deSelect
us.sel(this)=0;
for j=1:size(us.tb,2)
jtable.setValueAt(java.lang.String(us.tb0{this,j}),this-1,j-1);
end
end
end
% ---------remember scrolling-II--------------------
try
drawnow; % without this drawnow the following line appeared to do nothing
jScrollPane.setViewPosition(currentViewPos);% reset the scroll bar to original position
end
set(gcf,'userdata',us);
return
function convent(t,id)
%% slow way
us=get(gcf,'userdata');
idx=id.Indices;
for i=1:size(idx)
this=idx(i);
if us.sel(this)==0 %selected for process NOW
us.sel(this)=1;
us.tb(this,:)=us.tbsel(this,:);
else%deSelect
us.sel(this)=0;
us.tb(this,:)=us.tb0(this,:);
end
end
if 1
% ---------remember scrolling-I--------------------
% http://www.mathworks.com/matlabcentral/newsreader/view_thread/307912
try
hTable=t;
jTable = findjobj(hTable); % hTable is the handle to the uitable object
jScrollPane = jTable.getComponent(0);
javaObjectEDT(jScrollPane); % honestly not sure if this line matters at all
currentViewPos = jScrollPane.getViewPosition; % save current position
end
set(gcf,'userdata',us);
set(t,'data',us.tb);
% ---------remember scrolling-II--------------------
try
drawnow; % without this drawnow the following line appeared to do nothing
jScrollPane.setViewPosition(currentViewPos);% reset the scroll bar to original position
end
% -----------------------------
% jScrollpane = findjobj(t); % get the handle of the table
% scrollMax = jScrollpane.getVerticalScrollBar.getMaximum; % get the end position of the scroll
% AddNRows(handles,1); % appending 1 new row
% jScrollpane.getVerticalScrollBar.setValue(scrollMax);
end
if 0
t = uitable;
set(t,'Data',data);
jscroll = findjobj(t);
jtable = jscroll.getViewport.getComponent(0);
jtable.setValueAt(java.lang.String('This value will be inserted'),0,0); % to insert this value in cell (1,1)
end
|
github
|
philippboehmsturm/antx-master
|
snip_mosaic.m
|
.m
|
antx-master/mritools/snips/snip_mosaic.m
| 4,072 |
utf_8
|
7fe5de7de9b100ea89196719a005b2f5
|
function bla
% aa='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\_Atpl_mouseatlasNew_left.nii'
% bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\elx_T2_left-0.nii'
aa='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\_Atpl_mouseatlasNew.nii'
% bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\hx_T2.nii'
bb='V:\projects\atlasRegEdemaCorr\nii32\s20150908_FK_C1M01_1_3_1_1\elx_T2-0.nii'
%
% aa='C:\Users\skoch\Desktop\overlay\hx_c2T2.nii'
% bb='C:\Users\skoch\Desktop\overlay\hx_c1T2.nii'
aa='C:\Users\skoch\Desktop\overlay\_Atpl_mouseatlasNew.nii'
bb='C:\Users\skoch\Desktop\overlay\T2.nii'
aa='O:\harms1\koeln\dat\s20150701_AA1\sAVGT.nii'
bb='O:\harms1\koeln\dat\s20150701_AA1\x_t2.nii'
[ha a]=rgetnii(aa);
[hb b]=rgetnii(bb);
% [hb b]=rreslice2target(hb,b,ha);
[hb b]=rreslice2target(hb,ha);
a=a-min(a(:)); a=a./max(a(:));
b=b-min(b(:)); b=b./max(b(:));
nn=12
a1=(squeeze(a(:,nn,:)));
b1=(squeeze(b(:,nn,:)));
npix=50; %number of voxels within puzzle
nrep=ceil(size(a1)./(2*npix))
cb=checkerboard(npix,nrep( 1 ),nrep(2));
cb=cb(1:size(a1,1),1:size(a1,2));
cb(cb<.5)=0;cb(cb>=.5)=1;
c1=cb; c1(c1==0)=nan;
c2=cb; c2(c2==1)=nan;c2(c2==0)=1;
% fg,imagesc(nanmean(cat(3,a1.*c1,b1.*c2),3))
% fg,imagesc(nanmean(cat(3,imadjust(a1).*c1,imadjust(b1).*c2),3))
% c1
% fg,imagesc(c1)
% return
% slic=[30 60 100 120 150]
ns=30 %nslices
bord=15; %start top from border
slic=round(linspace(bord,size(a,2)-bord,ns));
dum2=[];
for i=1:length(slic)
nn=slic(i);
a1=(squeeze(a(:,nn,:)));
b1=(squeeze(b(:,nn,:)));
% a1=a1-min(a1(:)); a1=a1./max(a1(:));
% b1=b1-min(b1(:)); b1=b1./max(b1(:));
a1=imadjust(a1);
b1=imadjust(b1);
% as=cat(3,a1,a1,a1);bs=cat(3,b1,b1,b1);
% fg,image(bs); hold on;c=contour(a1,3,'linewidth',2,'linestyle','--')
%
% v=contourc(a1,3)'
%
% continue
npix=5;
nrep=ceil(size(a1)./(2*npix));
cb=checkerboard(npix,nrep( 1 ),nrep(2));
cb=cb(1:size(a1,1),1:size(a1,2));
cb(cb<.5)=0;cb(cb>=.5)=1;
c1=cb; c1(c1==0)=nan;
c2=cb; c2(c2==1)=nan;c2(c2==0)=1;
% fg,imagesc(nanmean(cat(3,a1.*c1,b1.*c2),3))
% fg,imagesc(nanmean(cat(3,imadjust(a1).*c1,imadjust(b1).*c2),3))
dum=nanmean(cat(3,imadjust(a1).*c1,imadjust(b1).*c2),3);
dum2(:,:,i)=dum;
end
% fg,imagesc(reshape(dum2,[ 165 135*size(dum2,3) ]))
% r=reshape(dum2,[ 165 135*4 ])
% vb=[2 4]
[vb ,n]=numSubplots(ns);
si=size(dum2)
e=[];n=1
for i=1:vb(1)
for j=1:vb(2)
if n<=size(dum2,3)
e(si(1)*i-si(1)+1:si(1)*i-si(1)+si(1), si(2)*j-si(2)+1:si(2)*j-si(2)+si(2) )=dum2(:,:,n);
n=n+1;
end
end
end
e=flipud(e');
fg,imagesc(e)
function [p,n]=numSubplots(n)
% function [p,n]=numSubplots(n)
%
% Purpose
% Calculate how many rows and columns of sub-plots are needed to
% neatly display n subplots.
%
% Inputs
% n - the desired number of subplots.
%
% Outputs
% p - a vector length 2 defining the number of rows and number of
% columns required to show n plots.
% [ n - the current number of subplots. This output is used only by
% this function for a recursive call.]
%
%
%
% Example: neatly lay out 13 sub-plots
% >> p=numSubplots(13)
% p =
% 3 5
% for i=1:13; subplot(p(1),p(2),i), pcolor(rand(10)), end
%
%
% Rob Campbell - January 2010
while isprime(n) & n>4,
n=n+1;
end
p=factor(n);
if length(p)==1
p=[1,p];
return
end
while length(p)>2
if length(p)>=4
p(1)=p(1)*p(end-1);
p(2)=p(2)*p(end);
p(end-1:end)=[];
else
p(1)=p(1)*p(2);
p(2)=[];
end
p=sort(p);
end
%Reformat if the column/row ratio is too large: we want a roughly
%square design
while p(2)/p(1)>2.5
N=n+1;
[p,n]=numSubplots(N); %Recursive!
end
|
github
|
philippboehmsturm/antx-master
|
snipp_uitable1.m
|
.m
|
antx-master/mritools/snips/snipp_uitable1.m
| 707 |
utf_8
|
7330f0d367d0abdde9ee2317e67e78a3
|
function snipp_uitable1
raw={'p1'; 'p2'; 'p3'}; %points id %COLUMN not row
column1=[200;250;300]; %distances
column1=num2cell(column1);
checked=false(size(raw,1),1); %is it checked?
cellArray=[raw,column1,checked];
set(handles.uitable1, 'Data', cellArray);
set(handles.uitable1, 'ColumnFormat', {'string', 'numeric', 'logical'});
set(handles.uitable1, 'CellEditCallback', @check_checked);
function check_checked(src, eventdata);
% cur_data = get(src, 'Data');
% where_changed = eventdata.Indices;
% row_changed = where_changed(1);
% id_affected = cur_data{row_changed, 1);
% dist_affected = cur_data(row_changed, 2);
% %now do something with the information ...
|
github
|
philippboehmsturm/antx-master
|
starttimer.m
|
.m
|
antx-master/mritools/snips/starttimer.m
| 583 |
utf_8
|
efa88d642eaaa939cf583dd0ac2355b4
|
function starttimer
try; delete(timerfind('tag','xboxtimer')); end
t = timer('TimerFcn',@timercallback, 'Period', 1,'tag','xboxtimer','ExecutionMode', 'FixedRate');
start(t);
function timercallback(u1,u2)
try
txt=evalin('base','msgtxt');
hfig=findobj(0,'tag','xbox');
% set(findobj(hfig,'tag','status'),'string',[txt ' ' datestr(now,'HH:MM:SS (dd-mmm)')]);
set(findobj(hfig,'tag','status'),'string',[txt.tag ' ' sprintf('dt %2.2fs', etime(clock, txt.time)) ]);
% assignin('base','msgtxt',msgtxt)
disp('#####################################')
end
|
github
|
philippboehmsturm/antx-master
|
param2struct.m
|
.m
|
antx-master/mritools/paramgui/param2struct.m
| 1,625 |
utf_8
|
d79dfda1c2921c5dfd699ee91da2615a
|
%convert paramarray(p) to structur, and delete infoTags
function x=param2struct(p)
%% EXAMPLE
if 0
p={...
'inf98' '*** ALLEN LABELING ' '' ''
'inf99' 'USE EITHER APPROACH-1 OR APPROACH-2' '' ''
'inf100' '===================================' '' ''
'inf1' '% APPROACH-1 (fullpathfiles: file/mask) ' '' ''
'files' '' 'files used for calculation' ,'mf'
'masks' '' '<optional>maskfiles (order is irrelevant)' ,'mf' ...
%
'inf2' '% APPROACH-2 (use filetags)' '' ''
'filetag' '' 'matching stringpattern of filename' ,''
'masktag' '' '<optional> matching stringpattern of masksname (value=1 is usef for inclusion)' ,''
'hemisphere' 'both' 'calculation over [left,right,both]' {'left','right','both'}
%
'inf3' '% PARAMETERS' '' ''
'frequency' 1 'paramter to extract' 'b'
'mean' 1 'paramter to extract' 'b'
'std' 1 'paramter to extract' 'b'
'median' 1 'paramter to extract' 'b'
'min' 1 'paramter to extract' 'b'
'max' 1 'paramter to extract' 'b'
}
z=param2struct(p);
end
idel=regexpi2(p(:,1),'^inf\d');
p(idel,:)=[];
x=cell2struct(p(:,2)',p(:,1)',2);
|
github
|
philippboehmsturm/antx-master
|
pickatlas.m
|
.m
|
antx-master/mritools/labs/pickatlas.m
| 2,394 |
utf_8
|
3d8ecb5286f9ec1095851b84ffb6fa36
|
function tx=pickatlas(cordsMNI)
global Atlas
if length(Atlas) ==0;%isglobal(Atlas)
pax=regexprep(which('pickatlas.m'),'pickatlas.m','');
err=exist(fullfile(pax,'Atlas.mat'));
if err==0
LookUpFilePath='MNI_atlas_templates_from_wfu_pickatlas' ;%'MNI_atlas_templates'
LookUpFileName='master_lookup.txt';
ImageName='MNI_T1.nii';
% [Atlas] = wfu_get_atlas_list(LookUpFilePath, LookUpFileName, ImageName)
[Atlas] = get_atlas_list(LookUpFilePath, LookUpFileName, ImageName)
save(fullfile(pax,'Atlas.mat'),'Atlas');
else
load(fullfile(pax,'Atlas.mat'))
end
end
replacem={'Lobe' 'Lo'; 'Left' 'L'; 'Right' 'R'; 'Gyrus' 'Gyr';...
'White Matter' 'WM';'Gray Matter' 'GM'; 'Occipital' 'Occip'; 'Frontal' 'Front';...
'lateral' 'lat'; 'Temporal' 'Temp';...
'posterior' 'post' ;'parietal' 'par' ;'region' 'reg';'medial' 'med';...
'anterior' 'ant';'Superior' 'sup' ; 'Inferior' 'inf';...
'Cerebro-Spinal Fluid' 'CSF'; 'inter-hemispheric' 'interHem' ; '_' '-';...
'Brodmann area' 'BA';'Cerebrum' 'C.' ;'interHem' 'iHem'; 'Hemispheres' 'Hem.';...
'Brainstem' 'BS.'};
Natlas=length(Atlas);
tx=repmat({''},[length(Atlas) 2]);
for atlasNo=1:Natlas;%8%length(Atlas)
cordsCube =round( inv( Atlas(atlasNo).Iheader.mat )*[cordsMNI(1) cordsMNI(2) cordsMNI(3) 1]');
value=Atlas(atlasNo).Offset;
sel_atlas=Atlas(atlasNo).Atlas;
try
value = value + sel_atlas(cordsCube(1), cordsCube(2), cordsCube(3));
catch
value=nan;
end
found = 0;
for j=1 : length(Atlas(atlasNo).Region)
for i =1 : length(Atlas(atlasNo).Region(j).SubregionValues)
if ((Atlas(atlasNo).Region(j).SubregionValues(i)+Atlas(atlasNo).Offset) == value)
found =1;
break;
end
end
end
if found==1
lab=deblank(Atlas(atlasNo).Region(j).SubregionNames(i));
else
lab={''};
end
lab=regexprep(lab,'brodmann area','BA');
lab=regexprep(lab,replacem(:,1),replacem(:,2),'ignorecase');
atlasname={Atlas(atlasNo).Name};
atlasname=regexprep(atlasname,'brodmann area','BA');
atlasname=regexprep(atlasname,'TD','');
if isempty(lab); lab={' '};end
tx(atlasNo,:)=[atlasname lab] ;% {Atlas(9).Name lab }
end %atlasNo
|
github
|
philippboehmsturm/antx-master
|
vc2nc_spm.m
|
.m
|
antx-master/mritools/labs/vc2nc_spm.m
| 1,456 |
utf_8
|
f7657c14caf6595c0011e2362b960080
|
function nc=vc2nc_spm(v2,hb)
% volume coords to normalized cords
% xSPM.M
% ----------------------------------
s_x=hb(1,:);%hb.hdr.hist.srow_x;
s_y=hb(2,:);%hb.hdr.hist.srow_y;
s_z=hb(3,:);%hb.hdr.hist.srow_z;
% s_x(find(s_x(1:3)==0))=1;
% s_y(find(s_y(1:3)==0))=1;
% s_z(find(s_z(1:3)==0))=1;
nc(:,1) = s_x(1).* v2(:,1) + s_x(2).* v2(:,2) + s_x(3).* v2(:,3) + s_x(4);
nc(:,2) = s_y(1).* v2(:,1) + s_y(2).* v2(:,2) + s_y(3).* v2(:,3) + s_y(4);
nc(:,3) = s_z(1).* v2(:,1) + s_z(2).* v2(:,2) + s_z(3).* v2(:,3) + s_z(4);
% %
% %
% % % The (x,y,z) coordinates are given by a general affine transformation
% % % of the (i,j,k) indexes:
% % %
% % % x = srow_x[0] * i + srow_x[1] * j + srow_x[2] * k + srow_x[3]
% % % y = srow_y[0] * i + srow_y[1] * j + srow_y[2] * k + srow_y[3]
% % % z = srow_z[0] * i + srow_z[1] * j + srow_z[2] * k + srow_z[3]
% % %
% % % The srow_* vectors are in the NIFTI_1 header. Note that no use is
% % % made of pixdim[] in this method.
% %
% %
% % srow_x=g.hdr.hist.srow_x
% % srow_y=g.hdr.hist.srow_y
% % srow_z=g.hdr.hist.srow_z
% %
% % % a=[27 30 40]
% % a=[78 112 50]
% % i=a(1);j=a(2);k=a(3);
% % disp([i j k])
% %
% % x = srow_x(1) * i + srow_x(2) * j + srow_x(3) * k + srow_x(4);
% % y = srow_y(1)* i + srow_y(2) * j + srow_y(3) * k + srow_y(4);
% % z = srow_z(1) * i + srow_z(2) * j + srow_z(3) * k + srow_z(4);
|
github
|
philippboehmsturm/antx-master
|
pclustermaxima.m
|
.m
|
antx-master/mritools/labs/pclustermaxima.m
| 1,578 |
utf_8
|
c6a242932b996b9057310548de28cb4b
|
function [s]=pclustermaxima(Z,xyz,hdr)
% Sizes, maxima and locations of clusters
%
% function [s]=pclustermaxima(Z,xyz,hdr)
%
% IN:
% Z : values (Accuracies,t,Z... but not p-values)
% XYZ: locations [x y x]' {in voxels} [3 x nvox]
%
% OUT:
% hdr: [1x1 struct] header
% XYZmm: [3x254 double] locations [x y x]' {in mm}
% XYZ: [3x254 double] locations [x y x]' {in voxels}
% nvox: [254x1 double] size of region {in voxels)
% regnr: [254x1 double] region number
% Z: [1x254 double] values
% example:
% [s]=pclustermaxima(st.Z,st.XYZ,st.hdr)
%
% regnr(i) identifies the ith maximum with a region. Region regnr(i) contains nvox(i) voxels.
%
%from [spmlist.m -line 418]
% Includes Darren Gitelman's code for working around
% spm_max for conjunctions with negative thresholds
%----------------------------------------------------------------------
minz = abs(min(min(Z)));
zscores = 1 + minz + Z;
[N Z xyz2 A] = spm_max(zscores,xyz);
Z = Z - minz - 1;
% %-Convert maxima locations from voxels to mm
% %----------------------------------------------------------------------
M=hdr.mat;
xyzmm = M(1:3,:)*[xyz2; ones(1,size(xyz2,2))];
s.hdr =hdr;
s.XYZmm=xyzmm;
s.XYZ =xyz2;
s.nvox =N;
s.regnr=A;
s.Z =Z;
% X - values of 3-D field
% L - locations [x y x]' {in voxels}
% N - size of region {in voxels)
% Z - Z values of maxima
% M - location of maxima {in voxels}
% A - region number
|
github
|
philippboehmsturm/antx-master
|
pick_wrapper.m
|
.m
|
antx-master/mritools/labs/pick_wrapper.m
| 1,206 |
utf_8
|
9dea0177def61738e725b8227053d065
|
function [labelx header s]=pick_wrapper(XYZmni, show,varargin)
% example: add 1st column 'title: cluster'
% [labelx header labelcell]=pick_wrapper(XYZmm', 'show',{'cluster',num2cell(num2str(A))});
% example2
% [labelx header labelcell]=pick_wrapper(XYZmm', 'show',{ {'cluster' 'maxAC' 'Zval'},tmp3} );
% example3 add one colum 'STATISTIC' with name 'STAT' and datavector 'val'
% [labelx header labelcell]=pick_wrapper(p', 'Noshow');
% showtable3([0 0 1 1],[ ['STAT' header ];[ num2str(val) labelx ]]','fontsize',8);
if isempty(XYZmni)
state='empty';
XYZmni=[nan nan nan]
end
co=XYZmni;
for i=1:size(co,1)
tx=pickatlas(co(i,:))';
if i==1
labelx=repmat({''}, [ size(co,1) 2+size(tx,2) ]);
end
dp= [{sprintf('%3.0f',i)} {sprintf('%4.0f%4.0f%4.0f',co(i,:))} tx(2,:) ];
labelx(i,:)=dp;
end
% if exist('tx')==0
% return
% end
header=[' N' 'xyzMNI' tx(1,:)];
if nargin>2
addheader= varargin{1}(1)
header=[addheader{:} header ];
addcol=varargin{1}(2);
labelx=[addcol{:} labelx];
end
[s hist]=plog({},{[] header labelx }, 1,'LABELING','s=0','d=0');
if strcmp(show,'show');
uhelp(s);
end
|
github
|
philippboehmsturm/antx-master
|
slice_overlay2.m
|
.m
|
antx-master/mritools/labs/slice_overlay2.m
| 31,151 |
utf_8
|
fdac67cf84b3f2a9379b6690de640d8d
|
function varargout = slice_overlay2(action, varargin);
% Function to display + manage slice display
% Slice display works on a global structure SO
% with fields
% - img - array of images to display
% - img structs contain fields
% vol - vol struct info (see spm_vol)
% can also be vol containing image as 3d matrix
% set with slice_overlay2('AddBlobs'...) call
% cmap - colormap for this image
% nancol - color for NaN. If scalar, this is an index into
% the image cmap. If 1x3 vector, it's a colour
% prop - proportion of intensity for this cmap/img
% if = Inf, gives split cmap effect where values of
% this cmap override previous image cmap values
% func - function to apply to image before scaling to cmap
% (and therefore before min/max thresholding. E.g. a func of
% 'i1(i1==0)=NaN' would convert zeros to NaNs
% range - 2x1 vector of values for image to distribute colormap across
% the first row of the colormap applies to the first
% value in 'range', and the last value to the second
% value in 'range'
% outofrange - behavior for image values to the left and
% right of image limits in 'range'. Left means
% colormap values < 1, i.e for image values <
% range(1), if (range(1)<range(2)), and image values >
% range(1) where (range(1)>range(2)). If missing,
% display min (for Left) and max (for Right) value from colormap.
% Otherwise should be a 2 element cell array, where
% the first element is the colour value for image values
% left of 'range', and the second is for image values
% right of 'range'. Scalar values for
% colour index the colormap, 3x1 vectors are colour
% values. An empty array attracts default settings
% appropriate to the mode - i.e. transparent colour (where
% SO.prop ~= Inf), or split colour. Empty cells
% default to 0. 0 specifies that voxels with this
% colour do not influence the image (split =
% background, true = black)
% hold - resampling order for image (see spm_sample_vol) -
% default 1
% background - value when resampling outside image - default
% NaN
%
% - transform - either - 4x4 transformation to apply to image slice position,
% relative to mm given by slicedef, before display
% or - text string, one of axial, coronal, sagittal
% These orientations assume the image is currently
% (after its mat file has been applied) axially
% oriented
% - slicedef - 2x3 array specifying dimensions for slice images in mm
% where rows are x,and y of slice image, and cols are neg max dim,
% slice separation and pos max dim
% - slices - vector of slice positions in mm in z (of transformed image)
% - figure - figure handle for slice display figure
% - refreshf - flag - if set or empty, refresh axis info for figure
% else assume this is OK
% - clf - flag, non zero -> clear figure before display. Redundant
% if refreshf == 0
% - area struct with fields
% position - bottom left, x size y size 1x4 vector of
% area in which to display slices
% units - one of
% inches,centimeters,normalized,points,{pixels}
% halign - one of left,{center},right
% valign - one of top,{middle},bottom
% - xslices - no of slices to display across figure (defaults to an optimum)
% - cbar - if empty, missing, no colourbar. If an array of integers, then
% indexes img array, and makes colourbar for each cmap for
% that img. Cbars specified in order of appearance L->R
% - labels - struct can be absent (-> default numerical labels)
% empty (SO.labels = []) (no labels) or contain fields
% colour - colour for label text
% size - font size in units normalized to slice axes
% format - if = cell array of strings =
% labels for each slice in Z. If is string, specifies
% sprintf format string for labelling in distance of the
% origin (Xmm=0, Ymm=0) of each slice from plane containing
% the AC, in mm, in the space of the transformed image
% - callback - callback string for button down on image panels. E.g.
% setting SO.callback to 'slice_overlay2(''getpos'')' prints to
% the matlab window the equivalent position in mm of the
% position of a mouse click on one of the image slices
% - printstr - string for printing slice overlay figure window, e.g.
% 'print -dpsc -painters -noui' (the default)
% - printfile - name of file to print output to; default 'slices.ps'
%
% FORMAT slice_overlay2
% Checks, fills SO struct (slice_overlay2('checkso')), and
% displays slice overlay (slice_overlay2('display'))
%
% FORMAT slice_overlay2('checkso')
% Checks SO structure and sets defaults
%
% FORMAT cmap = slice_overlay2('getcmap',cmapname)
% Gets colormap named in cmapname string
%
% FORMAT [mx mn] = slice_overlay2('volmaxmin', vol)
% Returns maximum and minimum finite values from vol struct 'vol'
%
% FORMAT slice_overlay2('addspm',SPM,dispf)
% Adds SPM blobs as new img to SO struct, split effect, 'hot' colormap,
% SPM structure is generated by calls to SPM results
% if not passed, it is fetched from the workspace
% If dispf is not passed, or nonzero, displays resulting SO figure also
%
% FORMAT slice_overlay2('addblobs', imgno, XYZ, vals, mat)
% adds SPM blobs to img no 'imgno', as specified in
% XYZ - 3xN voxel coordinates of N blob values
% vals - N blob intensity values
% mat - 4x4 matrix specifying voxels -> mm
%
% FORMAT vol = slice_overlay2('blobs2vol', XYZ, vals, mat)
% returns (pseudo) vol struct for 3d blob volume specified
% in matrices as above
%
% FORMAT slice_overlay2('addmatrix', imgno, mat3d, mat)
% adds 3d matrix image vol to img imgno. Optionally
% mat - 4x4 matrix specifying voxels -> mm
%
% FORMAT vol = slice_overlay2('matrix2vol', mat3d, mat)
% returns (pseudo) vol struct for 3d matrix
% input matrices as above
%
% FORMAT mmpos = slice_overlay2('getpos')
% returns equivalent position in mm of last click on current axes (gca)
% if the axes contain an image slice (empty otherwise)
%
% FORMAT vals = slice_overlay2('pointvals', XYZmm, holdlist)
% returns IxN matrix with values of each image 1..I, at each
% point 1..N specified in 3xN mm coordinate matrix XYZmm
% If specified, 'holdlist' contains I values giving hold
% values for resampling for each image (see spm_sample_vol)
%
% FORMAT slice_overlay2('display')
% Displays slice overlay from SO struct
%
% FORMAT slice_overlay2('print', filename, printstr)
% Prints slice overlay figure, usually to file. If filename is not
% passed/empty gets filename from SO.printfile. If printstr is not
% passed/empty gets printstr from SO.printstr
%
% V 0.8 2/8/00
% More or less beta - take care. Please report problems to
% Matthew Brett [email protected]
global SO
if nargin < 1
checkso;
action = 'display';
else
action = lower(action);
end
switch action
case 'checkso'
checkso;
case 'getcmap'
varargout = {getcmap(varargin{1})};
case 'volmaxmin'
[mx mn] = volmaxmin(varargin{1});
varargout = {mx, mn};
case 'addspm'
if nargin < 2
varargin{1} = [];
end
if nargin < 3
varargin{2} = 1;
end
if isempty(varargin{1})
% Fetch from workspace
errstr = sprintf(['Cannot find SPM variables in the workspace\n'...
'Please run SPM results GUI']);
V = spm('ver')
switch V(4:end)
case '99'
xSPM = evalin('base', 'SPM', ['error(' errstr ')']);
xSPM.M = evalin('base', 'VOL.M', ['error(' errstr ')']);
case '2'
xSPM = evalin('base', 'xSPM', ['error(' errstr ')']);
otherwise
error(['Strange SPM version ' V]);
end
else
xSPM = varargin{1};
end
newimg = length(SO.img)+1;
SO.img(newimg).vol = blobs2vol(xSPM.XYZ,xSPM.Z, xSPM.M);
SO.img(newimg).prop = Inf;
SO.img(newimg).cmap = hot;
SO.img(newimg).range = [0 max(xSPM.Z)];
SO.cbar = [SO.cbar newimg];
if varargin{2}
checkso;
slice_overlay2('display');
end
case 'addblobs'
addblobs(varargin{1},varargin{2},varargin{3},varargin{4});
case 'blobs2vol'
varargout = {blobs2vol(varargin{1},varargin{2},varargin{3})};
case 'addmatrix'
if nargin<3,varargin{2}='';end
if nargin<4,varargin{3}='';end
addmatrix(varargin{1},varargin{2},varargin{3});
case 'matrix2vol'
if nargin<3,varargin{2}=[];end
varargout = {matrix2vol(varargin{1},varargin{2})};
case 'getpos'
varargout = {getpos};
case 'pointvals'
varargout = {pointvals(varargin{1})};
case 'print'
if nargin<2,varargin{1}='';end
if nargin<3,varargin{2}='';end
printfig(varargin{1}, varargin{2});
case 'display'
% get coordinates for plane
X=1;Y=2;Z=3;
dims = SO.slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = SO.slices;
[y x] = meshgrid(ymm,xmm');
vdims = [length(xmm),length(ymm),length(zmm)];
% no of slices, and panels (an extra for colorbars)
nslices = vdims(Z);
minnpanels = nslices;
cbars = 0;
if is_there(SO,'cbar')
cbars = length(SO.cbar);
minnpanels = minnpanels+cbars;
end
% get figure data
% if written to, the axes may be specified already
figno = figure(SO.figure);
% (re)initialize axes and stuff
% check if the figure is set up correctly
try
if ~SO.refreshf
axisd = flipud(findobj(SO.figure, 'Type','axes','Tag', 'slice overlay panel'));
npanels = length(axisd);
if npanels < vdims(Z)+cbars;
SO.refreshf = 1;
end
end
end
if SO.refreshf
% clear figure, axis store
if SO.clf, clf; end
axisd = [];
% prevent print inversion problems
set(figno,'InvertHardCopy','off');
% calculate area of display in pixels
parea = SO.area.position;
if ~strcmp(SO.area.units, 'pixels')
ubu = get(SO.figure, 'units');
set(SO.figure, 'units','pixels');
tmp = get(SO.figure, 'Position');
ascf = tmp(3:4);
if ~strcmp(SO.area.units, 'normalized')
set(SO.figure, 'units',SO.area.units);
tmp = get(SO.figure, 'Position');
ascf = ascf ./ tmp(3:4);
end
set(figno, 'Units', ubu);
parea = parea .* repmat(ascf, 1, 2);
end
asz = parea(3:4);
% by default, make most parsimonious fit to figure
yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));
if ~is_there(SO, 'xslices')
% iteration needed to optimize, surprisingly. Thanks to Ian NS
axlen(X,:)=asz(1):-1:1;
axlen(Y,:)=yxratio*axlen(X,:);
panels = floor(asz'*ones(1,size(axlen,2))./axlen);
estnpanels = prod(panels);
tmp = find(estnpanels >= minnpanels);
if isempty(tmp)
error('Whoops, cannot fit panels onto figure');
end
b = tmp(1); % best fitting scaling
panels = panels(:,b);
axlen = axlen(:, b);
else
% if xslices is specified, assume X is flush with X figure dimensions
panels([X:Y],1) = [SO.xslices; 0];
axlen([X:Y],1) = [asz(X)/panels(X); 0];
end
% Axis dimensions are in pixels. This prevents aspect ratio rescaling
panels(Y) = ceil(minnpanels/panels(X));
axlen(Y) = axlen(X)*yxratio;
% centre (etc) panels in display area as required
divs = [Inf 2 1];the_ds = [0;0];
the_ds(X) = divs(strcmp(SO.area.halign, {'left','center','right'}));
the_ds(Y) = divs(strcmp(SO.area.valign, {'bottom','middle','top'}));
startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;
% make axes for panels
r=0;c=1;
npanels = prod(panels);
lastempty = npanels-cbars;
for i = 1:npanels
% panel userdata
if i<=nslices
u.type = 'slice';
u.no = zmm(i);
elseif i > lastempty
u.type = 'cbar';
u.no = i - lastempty;
else
u.type = 'empty';
u.no = i - nslices;
end
axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];
axisd(i) = axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'YTick',[],...
'YTickLabel',[],...
'Box','on',...
'XLim',[1 vdims(X)],...
'YLim',[1 vdims(Y)],...
'Units', 'pixels',...
'Position',axpos,...
'Tag','slice overlay panel',...
'UserData',u);
r = r+1;
if r >= panels(X)
r = 0;
c = c+1;
end
end
end
% sort out labels
if is_there(SO,'labels')
labels = SO.labels;
if iscell(labels.format)
if length(labels.format)~=vdims(Z)
error(...
sprintf('Oh dear, expecting %d labels, but found %d',...
vdims(Z), length(labels.contents)));
end
else
% format string for mm from AC labelling
fstr = labels.format;
labels.format = cell(vdims(Z),1);
acpt = SO.transform * [0 0 0 1]';
for i = 1:vdims(Z)
labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};
end
end
end
% modify colormaps with any new colours
nimgs = length(SO.img);
lrn = zeros(nimgs,3);
cmaps = cell(nimgs);
for i = 1:nimgs
cmaps(i)={SO.img(i).cmap};
lrnv = {SO.img(i).outofrange{:}, SO.img(i).nancol};
for j = 1:length(lrnv)
if prod(size(lrnv{j}))==1
lrn(i,j) = lrnv{j};
else
cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};
lrn(i,j) = size(cmaps{i},1);
end
end
end
% #######################################
us=get(gcf,'userdata');
try
transparencX=us.transparency;
catch
transparencX=0;
end
% #######################################
% cycle through slices displaying images
nvox = prod(vdims(1:2));
pandims = [vdims([2 1]) 3]; % NB XY transpose for display
zimg = zeros(pandims);
for i = 1:nslices
ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];
img = zimg;
for j = 1:nimgs
thisimg = SO.img(j);
% to voxel space of image
vixyz = inv(SO.transform*thisimg.vol.mat)*ixyzmm;
% raw data
if is_there(thisimg.vol, 'imgdata')
V = thisimg.vol.imgdata;
else
V = thisimg.vol;
end
if i==1
try
Vmax(j)=max(V(:));
catch
Vmax(j)= thisimg.range(2);
end
end
i1 = spm_sample_vol(V,vixyz(X,:),vixyz(Y,:),vixyz(Z,:), ...
[thisimg.hold thisimg.background]);
if is_there(thisimg, 'func')
eval(thisimg.func);
end
% transpose to reverse X and Y for figure
i1 = reshape(i1, vdims(1:2))';
% rescale to colormap
[csdata badvals]= scaletocmap(...
i1,...
thisimg.range(1),...
thisimg.range(2),...
cmaps{j},...
lrn(j,:));
% take indices from colormap to make true colour image
iimg = reshape(cmaps{j}(csdata(:),:),pandims);
tmp = repmat(logical(~badvals),[1 1 3]);
if thisimg.prop ~= Inf % truecolor overlay
img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;
% img(tmp) = (img(tmp) + iimg(tmp))/2;%*thisimg.prop;
else % split colormap effect
img(tmp) = iimg(tmp);
end
%%TRANSPARENCY
% us=get(gcf,'userdata'), SO.transparency=us.transparency
if transparencX~=0
if j==1
% ana=img-.05;%-.05;%-0.0159;%orig
ana=img;
ana(ana<0) = 0;
% ana=img-repmat( cat(3,mean(mean(img,1),2)), [size(img,1) size(img,2) 1] );
% ana
% ana(ana<0) = 0;
elseif j==2%%paul
% if 0
% fun=iimg;
% fun(repmat(badvals,[1 1 3])==1)=nan;
% fac=1;
% fac=transparencX;
% % dp=cat(4,ana.*(1-fac), fun.*(fac) );
% dp=cat(4,ana.*(.8) , fun.*(fac) );
% fun2=nansum(dp,4);
% fun2(fun2>1) = 1;
% % fg,image(fun2)
% img=fun2;
% end
% alphaFactor=transparencX;
% bgImg = double(ana);
% fgImg = double(iimg);
if 0 %OLD CODE
fgImgAlpha = transparencX .* iimg ;
bgImgAlpha = (1 - transparencX) .* ana;
fusedImg = fgImgAlpha + bgImgAlpha;
img=fusedImg;
end
% ana=ana./max(ana(:)) ;
% iimg=iimg./max(iimg(:)) ;
% ana=ana./Vmax(1) ;
% iimg=iimg./Vmax(2) ;
alpha=transparencX;
% alpha = .8; % this can be dynamically adjusted by a slider
O1 = ana + iimg.*alpha; % overlay
% figure(3)
% imshow(O1)
img=O1;
end
else
if j==2
if ~isempty(strfind(SO.img(1).vol.fname,'mni_icbm152'))
img=img-.08;
img(img<0)=0;
% img(img>0.02)=1;
end
end
end
end
% if 0
% [img]=smoothimage(img, 3 );%ks=kernelsize
% end
% threshold out of range values
img(img>1) = 1;
% img=img./max(img(:));
image('Parent', axisd(i),...
'ButtonDownFcn', SO.callback,...
'CData',img);
%####################### boundary
% ####
if ~isempty(SO.boundary)
bb=[];
bound=SO.boundary;
bb.mat=bound.mat;
bb.dim=bound.dim;
% SO.img(3).imgdata=bound.imgdata;
bb.hold =1;
bb.background=0;
bb.range=[0 1];
bb.cmap=SO.img(2).cmap;
bb.vol.mat=bound.mat;
bb.vol.dim=bound.dim;
bb.vol.imgdata=bound.imgdata;
thisimg2 = bb;
% to voxel space of image
vixyz = inv(SO.transform*thisimg2.vol.mat)*ixyzmm;
% raw data
if is_there(bb.vol, 'imgdata')
V2 = thisimg2.vol.imgdata;
else
V2 = thisimg2.vol;
end
i1 = spm_sample_vol(V2,vixyz(X,:),vixyz(Y,:),vixyz(Z,:), ...
[thisimg2.hold thisimg2.background]);
% if is_there(thisimg, 'func')
% eval(thisimg.func);
% end
% transpose to reverse X and Y for figure
bo = reshape(i1, vdims(1:2))';
% ============================================================
set(gcf,'CurrentAxes',axisd(i));
se3 = strel('square', 2 ) ;
b2 = imdilate(bo, se3);
[B,L] = bwboundaries(b2,4);
if isfield(bound,'linewidth')==0; bound.linewidth=1; end
if isfield(bound,'color')==0; bound.color=[1 1 1]; end
% fg; imagesc(bo)
hold on
for k = 1:length(B)
bf = B{k};
% if 0
% mb=mean(bf)
% bx=bf-repmat(mb,[size(bf,1) 1])
% % bx= [bx.*1.5 ] +repmat(mb,[size(bx,1) 1]) ;
% % bx= [(min(bf)+1)./min(bf) ] +repmat(mb,[size(bx,1) 1]) ;
% bx=bx.*repmat( [(min(bf)+4)./min(bf) ] ,[size(bx,1) 1])+repmat(mb,[size(bx,1) 1]) ;
% plot(bx(:,2), bx(:,1), 'w', 'LineWidth', 2)
% end
% plot(bf(:,2), bf(:,1), 'm', 'LineWidth', 1,'color',[ 0.8000 0 0.8000]);
plot(bf(:,2), bf(:,1), 'm', 'LineWidth', bound.linewidth,'color',bound.color);
end
end
% #################################% ##########
if is_there(SO,'labels')
text('Parent',axisd(i),...
'Color', labels.colour,...
'FontUnits', 'normalized',...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Position', [1 1],...
'FontSize',labels.size,...
'ButtonDownFcn', SO.callback,...
'String', labels.format{i},...
'tag','txtxslice');
end
end
for i = (nslices+1):npanels
set(axisd(i),'Color',[0 0 0]);
end
% add colorbar(s)
for i = 1:cbars
axno = axisd(end-cbars+i);
cbari = SO.img(SO.cbar(i));
cml = size(cbari.cmap,1);
p = get(axno, 'Position');; % position of last axis
cw = p(3)*0.2;
ch = p(4)*0.75;
pc = p(3:4)/2;
[axlims idxs] = sort(cbari.range);
a=axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'Units', 'pixels',...
'YLim', axlims,...
'FontUnits', 'normalized',...
'FontSize', 0.075,...
'YColor',[1 1 1],...
'Tag', 'cbar',...
'Box', 'off',...
'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...
);
ih = image('Parent', a,...
'YData', axlims(idxs),...
'CData', reshape(cbari.cmap,[cml,1,3]));
end
otherwise
error(sprintf('Unrecognized action string %s', action));
% end switch action
end
return
function checkso
% checks and fills SO structure
global SO
% figure
if is_there(SO, 'figure')
try
if ~strcmp(get(SO.figure,'Type'),'figure')
error('Figure handle is not a figure')
end
catch
error('Figure handle is not a valid figure')
end
else
% no figure handle. Try spm figure, then gcf
% SO.figure = spm_figure('FindWin', 'Graphics');
SO.figure=findobj(gcf,'tag','pslices');%###paul
if isempty(SO.figure)
SO.figure = gcf;
end
end
% set defaults for SPM figure
if strcmp(get(SO.figure, 'Tag'),'Graphics')
% position figure nicely for SPM
defstruct = struct('position', [0 0 1 0.92], 'units', 'normalized', ...
'valign', 'top');
SO = set_def(SO, 'area', defstruct);
SO.area = set_def(SO.area, 'position', defstruct.position);
SO.area = set_def(SO.area, 'units', defstruct.units);
SO.area = set_def(SO.area, 'valign', defstruct.valign);
end
SO = set_def(SO, 'clf', 1);
% orientation; string or 4x4 matrix
orientn = [];
SO = set_def(SO, 'transform', 'axial');
if ischar(SO.transform)
orientn = find(strcmpi(SO.transform, {'axial','coronal','sagittal'}));
if isempty(orientn)
error(sprintf('Unexpected orientation %s', SO.transform));
end
ts = [0 0 0 0 0 0 1 1 1;...
0 0 0 pi/2 0 0 1 -1 1;...
0 0 0 pi/2 0 -pi/2 -1 1 1];
SO.transform = spm_matrix(ts(orientn,:));
end
% default slice size, slice matrix depends on orientation
if ~is_there(SO,'slicedef' | ~is_there(SO, 'slices'))
% take image sizes from first image
V = SO.img(1).vol;
D = V.dim(1:3);
T = SO.transform * V.mat;
vcorners = [1 1 1; D(1) 1 1; 1 D(2) 1; D(1:2) 1; ...
1 1 D(3); D(1) 1 D(3); 1 D(2:3) ; D(1:3)]';
corners = T * [vcorners; ones(1,8)];
SC = sort(corners');
vxsz = sqrt(sum(T(1:3,1:3).^2));
SO = set_def(SO, 'slicedef',...
[SC(1,1) vxsz(1) SC(8,1);SC(1,2) vxsz(2) SC(8,2)]);
SO = set_def(SO, 'slices',[SC(1,3):vxsz(3):SC(8,3)]);
end
% no colourbars by default
SO = set_def(SO, 'cbars', []);
% always refresh figure window, by default
SO = set_def(SO, 'refreshf', 1);
% labels
defstruct = struct('colour',[1 1 1],'size',0.075,'format', '%+3.0f');
if ~isfield(SO, 'labels') % no field, -> default
SO.labels = defstruct;
elseif ~isempty(SO.labels) % empty -> no labels
% colour for slice labels
SO.labels = set_def(SO.labels, 'colour', defstruct.colour);
% font size normalized to image axis
SO.labels = set_def(SO.labels, 'size', defstruct.size);
% format string for slice labels
SO.labels = set_def(SO.labels, 'format', defstruct.format);
end
% callback
SO = set_def(SO, 'callback', ';');
% figure area stuff
defarea = struct('position',[0 0 1 1],'units','normalized');
SO = set_def(SO, 'area', defarea);
if ~is_there(SO.area, 'position')
SO.area = defarea;
end
if ~is_there(SO.area,'units')
if (all(SO.area.position>=0 & SO.area.position<=1))
SO.area.units = 'normalized';
else
SO.area.units = 'pixels';
end
end
SO.area = set_def(SO.area,'halign', 'center');
SO.area = set_def(SO.area,'valign', 'middle');
% printing
SO = set_def(SO, 'printstr', 'print -dpsc -painters -noui');
SO = set_def(SO, 'printfile', 'slices.ps');
% fill various img arguments
% would be nice to use set_def, but we can't
% set colour intensities as we go
remcol = 1;
for i = 1:length(SO.img)
if ~is_there(SO.img(i),'hold')
if ~is_there(SO.img(i).vol,'imgdata')
% normal file vol struct
SO.img(i).hold = 1;
else
% 3d matrix vol struct
SO.img(i).hold = 0;
end
end
if ~is_there(SO.img(i),'background')
SO.img(i).background = NaN;
end
if ~is_there(SO.img(i),'prop')
% default is true colour
SO.img(i).prop = remcol/(length(SO.img)-i+1);
remcol = remcol - SO.img(i).prop;
end
if ~is_there(SO.img(i),'range')
[mx mn] = volmaxmin(SO.img(i).vol);
SO.img(i).range = [mn mx];
end
if ~is_there(SO.img(i),'cmap')
if SO.img(i).prop == Inf; % split map
if SO.range(1)<SO.range(2)
SO.img(i).cmap = getcmap('hot');
else
SO.img(i).cmap = getcmap('winter');
end
else % true colour
SO.img(i).cmap = getcmap('actc');
end
end
if ~is_there(SO.img(i),'outofrange')
% this can be complex, and depends on split/true colour
if SO.img(i).prop == Inf % split colour
if xor(SO.img(i).range(1) < SO.img(i).range(2), ...
SO.img(i).range(2) < 0)
SO.img(i).outofrange = {[0],size(SO.img(i).cmap,1)};
else
SO.img(imgno).outofrange={[1], [0]};
end
else % true colour
SO.img(i).outofrange = {1,size(SO.img(i).cmap,1)};
end
end
for j=1:2
if isempty(SO.img(i).outofrange{j})
SO.img(i).outofrange(j) = {0};
end
end
if ~is_there(SO.img(i),'nancol')
SO.img(i).nancol = 0;
end
end
return
function tf = is_there(a, fname)
% returns true if field fname is present in struct a, and not empty
tf = isfield(a, fname);
if tf
tf = ~isempty(getfield(a, fname));
end
return
function [img, badvals]=scaletocmap(inpimg,mn,mx,cmap,lrn)
img = (inpimg-mn)/(mx-mn); % img normalized to mn=0,mx=1
cml = size(cmap,1);
if cml==1 % values between 0 and 1 -> 1
img(img>=0 & img<=1)=1;
else
img = img*(cml-1)+1;
end
outvals = {img<1, img>cml, isnan(img)};
img= round(img);
badvals = zeros(size(img));
for i = 1:length(lrn)
if lrn(i)
img(outvals{i}) = lrn(i);
else
badvals = badvals | outvals{i};
img(outvals{i}) = 1;
end
end
return
function st = set_def(st, fld, def)
if ~is_there(st, fld)
st = setfield(st, fld, def);
end
return
function addblobs(imgno, xyz,vals,mat)
global SO
if isempty(imgno)
imgno = length(SO.img);
end
if ~isempty(xyz)
SO.img(imgno).vol = blobs2vol(xyz,vals,mat);
end
function vol = blobs2vol(xyz,vals,mat)
vol = [];
if ~isempty(xyz),
rcp = round(xyz);
vol.dim = max(rcp,[],2)';
off = rcp(1,:) + vol.dim(1)*(rcp(2,:)-1+vol.dim(2)*(rcp(3,:)-1));
vol.imgdata = zeros(vol.dim)+NaN;
vol.imgdata(off) = vals;
vol.imgdata = reshape(vol.imgdata,vol.dim);
vol.mat = mat;
end
return
function addmatrix(imgno,mat3d,mat)
global SO
if isempty(imgno)
imgno = length(SO.img);
end
if nargin<3
mat = [];
end
if ~isempty(mat3d)
SO.img(imgno).vol = matrix2vol(mat3d,mat);
end
function vol = matrix2vol(mat3d,mat)
if nargin < 2
mat = spm_matrix([]);
end
if isempty(mat)
mat = spm_matrix([]);
end
vol = [];
if ~isempty(mat3d)
vol.imgdata = mat3d;
vol.mat = mat;
vol.dim = size(mat3d);
end
return
function [mx,mn] = volmaxmin(vol)
if is_there(vol, 'imgdata')
try
tmp = vol.imgdata(finite(vol.imgdata));
catch
tmp = vol.imgdata(isfinite(vol.imgdata));
end
mx = max(tmp);
mn = min(tmp);
else
mx = -Inf;mn=Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),[0 NaN]);
try
tmp = tmp(find(finite(tmp(:))));
catch
tmp = tmp(find(isfinite(tmp(:))));
end
if ~isempty(tmp)
mx = max([mx; tmp]);
mn = min([mn; tmp]);
end
end
end
return
function cmap = getcmap(acmapname)
% get colormap of name acmapname
if ~isempty(acmapname)
cmap = evalin('base',acmapname,'[]');
if isempty(cmap) % not a matrix, is it...
% a colour name?
tmp = strcmp(acmapname, {'red','green','blue'});
if any(tmp)
cmap = zeros(64,3);
cmap(:,tmp) = ((0:63)/63)';
else
% a .mat file?
[p f e] = fileparts(acmapname);
acmat = fullfile(p, [f '.mat']);
if exist(acmat, 'file')
s = struct2cell(load(acmat));
cmap = s{1};
end
end
end
end
if size(cmap, 2)~=3
warning('Colormap was not an N by 3 matrix')
cmap = [];
end
return
function mmpos = getpos
% returns point location from last click, in mm
global SO
mmpos=[];
pos = get(gca, 'CurrentPoint');
u = get(gca, 'UserData');
if is_there(u, 'type')
if strcmp(u.type, 'slice') % is slice panel
mmpos = (pos(1,1:2)'-1).*SO.slicedef(:,2)+SO.slicedef(:,1);
mmpos = inv(SO.transform) * [mmpos; u.no; 1];
mmpos = mmpos(1:3,1);
end
end
return
function vals = pointvals(XYZmm, holdlist)
% returns values from all the images at points given in XYZmm
global SO
if nargin < 2
holdlist = [SO.img(:).hold];
end
X=1;Y=2;Z=3;
nimgs = length(SO.img);
nvals = size(XYZmm,2);
vals = zeros(nimgs,nvals)+NaN;
if size(XYZmm,1)~=4
XYZmm = [XYZmm(X:Z,:); ones(1,nvals)];
end
for i = 1:nimgs
I = SO.img(i);
XYZ = I.vol.mat\XYZmm;
if ~is_there(I.vol, 'imgdata')
vol = I.vol;
else
vol = I.vol.imgdata;
end
vals(i,:) = spm_sample_vol(vol, XYZ(X,:), XYZ(Y,:),XYZ(Z,:),[holdlist(i) ...
I.background]);
end
return
function printfig(filename,printstr)
% print slice overlay figure
% based on spm_figure print, and including fix from thence for ps printing
global SO;
if nargin < 1
filename = [];
end
if isempty(filename)
filename = SO.printfile;
end
if nargin < 2
printstr = '';
end
if isempty(printstr)
printstr = SO.printstr;
end
%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',SO.figure)
%-Temporarily change all units to normalized prior to printing
% (Fixes bizarre problem with stuff jumping around!)
%-----------------------------------------------------------------------
H = findobj(get(SO.figure,'Children'),'flat','Type','axes');
un = cellstr(get(H,'Units'));
set(H,'Units','normalized')
%-Print
%-----------------------------------------------------------------------
err = 0;
try, eval([printstr ' ' filename]), catch, err=1; end
if err
errstr = lasterr;
tmp = [find(abs(errstr)==10),length(errstr)+1];
str = {errstr(1:tmp(1)-1)};
for i = 1:length(tmp)-1
if tmp(i)+1 < tmp(i+1)
str = [str, {errstr(tmp(i)+1:tmp(i+1)-1)}];
end
end
str = {str{:}, '','- print command is:',[' ',printstr ' ' filename],...
'','- current directory is:',[' ',pwd],...
'',' * nothing has been printed *'};
for i=1:length(str)
disp(str{i});end
end
set(H,{'Units'},un)
set(0,'CurrentFigure',cF)
return
function [gg]=smoothimage(dum, ks )
%dum=img
% dum=iimg
% ks=5;
skernel=ones(ks,ks) ; %3,3 meankearnel
skernel=skernel/numel(skernel);
gg=dum.*0;
h =fspecial('average',2);
for ii=1:3
gg(:,:,ii)= conv2(dum(:,:,ii),skernel,'same');
%gg(:,:,ii)= imfilter(dum(:,:,ii),h);
end
a1=[min(dum(:)) max(dum(:))];
a2=[min(gg(:)) max(gg(:))];
gg=gg-a2(1); gg=gg/max(gg(:));
gg=[gg*(a1(2)-a1(1))+a1(1) ] ;
% [min(gg(:)) max(gg(:))];
|
github
|
philippboehmsturm/antx-master
|
labs.m
|
.m
|
antx-master/mritools/labs/labs.m
| 21,991 |
utf_8
|
e43df7fd66d4c63ecfc0b11a05e7b8b7
|
function outw=labs(varargin)
% -labs: instant labeling and more
% examples
% labs([-33 -44 43])
% labs(XYZmm(:,ix),{'addcolpre',{'R' 'p'} rp(ix,:)})
% labs(XYZmm(:,ix),{'addcolpost',{'R' 'p'} rp(ix,:)})
if nargin==1 | nargin==2
cords=varargin{1};
if size(cords,1)==3
cords=cords';
end
if numel(cords)~=1
[labelx header labelcell]=pick_wrapper(cords, 'Noshow');%
elseif ishandle(cords)
delete(timerfindall);
if findobj(0,'tag','Graphics')& findobj(0,'tag','Menu') & findobj(0,'tag','Interactive')
t = timer('TimerFcn','labs;Fgraph = spm_figure(''GetWin'',''Graphics'');', 'executionmode', 'singleShot','StartDelay',.2);
start(t);
end
return
end
if nargin==1
showtable3([0 0 1 1],[header;labelx],'fontsize',8);
else%ADD COLUMNS addcolpre|addcolpost
add= varargin{2};
addheader=add{2};
addata =num2cell(add{3});
addata =cellfun(@(addata) {num2str(addata)},addata);
if strcmp(add{1},'addcolpre')
labelx=[ addata labelx];
header=[ addheader header];
elseif strcmp(add{1},'addcolpost')
labelx=[ labelx addata ];
header=[ header addheader ];
end
showtable3([0 0 1 1],[header;labelx],'fontsize',8);
end
try
% ihan=findobj(0,'tag','tabelz2');
ihan=gcf;
us=get(ihan,'userdata');
outw.table =us.table;
outw.tablec=us.tablec;
% varargout{1}=out;
catch
ihan= findobj(0,'tag','tabelz2');
ihan=ihan(1);
us=get(ihan,'userdata');
outw.table =us.table;
outw.tablec=us.tablec;
end
return
end
fix=sort(findall(0,'tag','menu_brodm'));
% if length(fix)>1
set(fix,'DeleteFcn','');
delete(fix);
% end
% fix2=sort(findall(0,'tag','menu_brodm0'));
% set(fix2,'DeleteFcn','');
% delete(fix2);
% --------------------------------------
fig3=findobj(0,'tag','Interactive');
set(0,'currentfigure',fig3);
delete(findobj(0,'tag','menu_brodm0'));%resultspanel
% f2 = uimenu('Label','LABS','tag','menu_brodm0','Callback','labs');
% set(f2,'DeleteFcn',@labs) ;
% --------------------------------------
% fig1=findobj(0,'tag','Graphics');
fig1=findobj(0,'tag','Interactive');
set(0,'currentfigure',fig1);
delete(findobj(0,'tag','menu_brodm'));
f = uimenu('Label','LABS','tag','menu_brodm');
uimenu(f,'Label','update LABS [u]','Callback', @labs );
uimenu(f,'Label','TABLE whole brain [t]','Callback', 'batab(1)' ,'Separator','on');
uimenu(f,'Label','TABLE current cluster [z]','Callback', 'batab(2)' ,'Separator','on');
% uimenu(f,'Label','hide TABLE [h]','Callback', 'batab(0)' ,'Separator','on');
% uimenu(f,'Label','change ATLAS','Callback', @changeAtlas );
% uimenu(f,'Label','show Brodman','Callback',@showbrodmann,'Separator','on');
% for i=1:4
% uimenu(f,'Label',[' ' upper(atlasname{i}) ' ...Mwheel'],'Callback',{@changeAtlas ,i} );
% end
% uimenu(f,'Label','synchronize slices & sections [s]','Callback', 'basyncsection' ,'Separator','on');
% uimenu(f,'Label','info ','Callback', @pinfo ,'Separator','on');
uimenu(f,'Label','show sections [s]','Callback', 'fun2_sections' ,'Separator','on');
uimenu(f,'Label','show slices [e]','Callback', 'pslices' ,'Separator','on');
uimenu(f,'Label','render surface [r]','Callback', 'renderer' ,'Separator','on');
uimenu(f,'Label','show 3D brain [b]','Callback', @fun2_showbrain ,'Separator','on');
uimenu(f,'Label','contrast estimate [c]','Callback', @contrastestimate ,'Separator','on');
% uimenu(f,'Label','contrast estimate II [v]','Callback', @contrastestimate ,'Separator','on');
uimenu(f,'Label','smallVolumeCorrection (using MASK image(s)) [m]','Callback', @svc ,'Separator','on');
% uimenu(f,'Label','previous Contrast [<-]','Callback', 'changeContrast(1)' ,'Separator','on');
% uimenu(f,'Label','next Contrast [->]','Callback', 'changeContrast(2)' ,'Separator','on');
uimenu(f,'Label','..pause..[p]','Callback',@jadiccaller,'Separator','on','tag','jadic');%'Checked','on'
uimenu(f,'Label','..info..','Callback',@info,'Separator','on','tag','pinfo');%'Checked','on'
uimenu(f,'Label','close labs ','Callback', @pclose ,'Separator','on');
% uimenu(f,'Label','close [q]','Callback', 'batab(''close'')' ,'Separator','on');
set(f,'DeleteFcn',@labs) ;
% uimenu(f,'Label','Quit','Callback','exit',...
% 'Separator','on','Accelerator','Q');
txt1 = '<html><b><u><i>Info</i></u>';
txt2 = '<font color="red"><sup>for this toolbox</sup></font></b></html>';
txt3 = '<br />this file as...';
set(findall(fig1,'tag','pinfo'), 'Label',[txt1,txt2]);
pause(0.1);drawnow
% try
jFrame = get(handle(fig1),'JavaFrame');
try % R2008a and later
jMenuBar = jFrame.fHG1Client.getMenuBar;
catch % R2007b and earlier
jMenuBar = jFrame.fFigureClient.getMenuBar;
end
% jFrame = get(handle(gcf),'JavaFrame');
% jMenuBar = jFrame.fFigureClient.getMenuBar;
compN =0;
for i=0:5
try
jFileMenu = jMenuBar.getComponent(i);
if strcmp(jFileMenu.getLabel ,'LABS')
compN=i;
break
end
end
end
jFileMenu = jMenuBar.getComponent(compN);
% jFileMenu.getMenuComponents,
% jFileMenu.getMenuComponentCount
icon=strrep(which('labs.m'),'labs.m','monkey.png');
if 0
% jFileMenu.getLabel
jFileMenu = jMenuBar.getComponent(compN) ;
jSave = jFileMenu.getMenuComponent(jFileMenu.getMenuComponentCount-2); %Java indexes start with 0!
% jSave.getText
% myIcon = 'C:\Yair\save.gif';
jSave.setIcon(javax.swing.ImageIcon(icon));
end
jFileMenu.setIcon(javax.swing.ImageIcon(icon));
% end
global Atlas;
keyboardactivate;
try; showbrodmann; end
try
% ihan=findobj(0,'tag','tabelz2');
ihan=gcf;
us=get(ihan,'userdata');
outw.table =us.table;
outw.tablec=us.tablec;
% varargout{1}=out;
end
function info(w,ww)
% disp('*** BAUSTELLE ***');
% disp('hit [u] to update LABS');
% disp('hit [t] to update table');
% disp('hit [s] to show overlay/SECTIONS [change labs_config.m for another overlay]');
warning off;
labsinfo;
anima;
warning on;
function jadiccaller(w,ww)
jadic;
function contrastestimate(w,ww)
xSPM=evalin('base','xSPM');
SPM=evalin('base','SPM');
hReg=evalin('base','hReg');
if isempty(xSPM.Z); return; end
fig=findobj(0,'tag','EOIbar');
if isempty(fig)
[Y,y,beta,Bcov] = pspm_graph(xSPM,SPM,hReg);
else
us=get(fig,'userdata');
ic=us.definedIC;
[Y,y,beta,Bcov] = pspm_graph(xSPM,SPM,hReg, [ic] );
end
assignin('base','Y',Y);
assignin('base','y',y);
assignin('base','beta',beta);
assignin('base','Bcov',Bcov);
% fig=findobj(0,'tag','EOIbar');
% labely=get(get(gca,'ylabel'),'string');
% str2num(char((regexp(labely,'\[.*\]','match'))))
% s1=[regexp(labely,'\[') regexp(labely,'\]') ]
% strct=labs(str2num(labely(s1(1):s1(2))))
% currentLabel=char(strct.tablec(2,3))
% string=labely(1:s1(1)-1)
try
ax1=findobj(fig,'type','axes');
labely=get(get(ax1,'ylabel'),'string');
cordinate=str2num(char((regexp(labely,'\[.*\]','match'))));
strct=labs(cordinate);
currentLabel=char(strct.tablec(2,3));
set(get(ax1,'xlabel'),'string',{'contrast',['\color{blue}' currentLabel ] });
end
fig=findobj(0,'tag','EOIbar');
figure(fig)
list={SPM.xCon(:).name}';
hpop = uicontrol('Style', 'popup',...
'String',list,'units','normalized',... 'hsv|hot|cool|gray'
'Position', [.16 .9 .8 .1],...
'Callback', @callchangecontrast2plot);
set(hpop,'BackgroundColor','w');
set(hpop,'HorizontalAlignment','right');
set(hpop,'fontsize',10,'fontweight','bold');
set(hpop,'tag','hpopcontrast','tooltip','chose contrast to plot');
fig=findobj(0,'tag','EOIbar');
us= get(fig,'userdata');
if isfield(us,'definedIC')==0 %never used before
us.definedIC=xSPM.Ic;
set(fig,'userdata',us);
end
set(hpop,'value',us.definedIC);
% Fgraph = spm_figure('GetWin','Graphics');
figure(findobj(0,'tag','Graphics'));
function CEstack
fig0=get(0,'currentfigure');
fig=findobj(0,'tag','EOIbar');
% us2=get(fig,'userdata');
fig2=findobj(0,'tag','EOIbarstack');
if isempty(fig2);
fig2=figure(1123);
set(fig2,'color','w','units','normalized','tag','EOIbarstack');
%fig2=findobj(0,'tag','EOIbarstack');
set(fig2,'KeyPressFcn',@keyboardCEstack,...
'position',[ 0.7174 0.1422 0.2639 0.3867]);
uv.figsize=get(fig2,'position');
set(fig2,'userdata',uv);
end
set(0,'currentfigure',fig2);
ax2cop=findobj(fig,'type','axes');
set(ax2cop,'tag','barce');
copyobj(ax2cop, fig2);
ax=findobj(fig2,'type','axes','-and','tag','barce');
% usax.title=us2.title;
% set(max(ax),'userdata',usax);
% pos0=get(min(ax),'position');%firstaxis
% if length(ax)<=1;
% return;
% end
try
pos=cell2mat(get(ax,'position'));
catch
pos= (get(ax,'position'));
end
% pbas=linspace(0.13,.93,length(ax)+1)
pbas=linspace(0,.9,length(ax)+1);
pbas=pbas+0.07;
phig=abs(diff(pbas(1:2)))*0.9;
pos2=pos;
pos2(:,2)=pbas(1:size(pos,1));
pos2(:,4)=phig;
pos2(:,1)=.13;
pos0=pos2(end,:);
if size(pos2,1)==1
pos2(:,3)=.25;
else
pos2(:,3)=pos0(3);%.25;
end
tit={};
for i=1:length(ax)
set(fig2,'currentaxes',ax(i));
xlim([get(ax(i),'xlim')]);
ylim([get(ax(i),'ylim')]);
set(ax(i),'position',pos2(i,:));
%set dot-to invivsible
l=findobj(gca,'type','line');
set(l(1),'visible','off');
try
ih=get(ax(i),'ylabel');
strCORD=regexprep(get(ih,'string'), 'contrast estimate at ','');
set(ih,'visible','off');
end
% try
% ih=get(ax(i),'xlabel')
% str= get(ih,'string');
% try
% set(ih,'string',str{2});
% end
% set(ih,'fontsize',8);
% end
try
ih=get(ax(i),'title');
set(ih,'visible','off');
txCE=findobj(ax(i),'tag','txCE');
if ~isempty(txCE);
delete(txCE);
end
str= get(ih,'string');
%txpos=[ mean(get(ax(i),'xlim')) max(get(ax(i),'ylim')) ];
% txpos=[ max(get(ax(i),'xlim')) 0 ];
yl=get(ax(i),'ylim');
txpos=[ max(get(ax(i),'xlim')) (mean(yl)) ];
%xlabel
ih2=get(ax(i),'xlabel');
str2= get(ih2,'string');
try ;
str2=[str2{1} str2{2}];
end
str2=regexprep(str2,'contrast' ,'' );
set(ih2,'visible','off');
try
% str0=regexprep(str{1},'Contrast estimates and ' ,'CE & ' );
str0='';
try
info= getappdata(ax(i),'info');
tit(end+1,1)= {info.title};
%[' ' '\color{red}' info.title '\color[rgb]{.5 .5 .5}' ]
% msg={ [' ' '\fontsize{6}' str{2} ' ' strCORD ' ' str0 ' ' ...
% '\fontsize{8}' str2 ]};
strCORD=sprintf('[%4.0f %4.0f %4.0f]',round(str2num(strCORD)));
msg={ [' ' '\fontsize{6}' strCORD ' ' str0 ' ' ...
'\fontsize{8}' str2 ]};
catch
msg=[' ' str{2} ' ' strCORD ' ' str0 ' ' str2 ];
end
te=text(txpos(1),txpos(2), msg);
catch
str0=regexprep(str,'Contrast estimates and ' ,'CE & ' );
te=text(txpos(1),txpos(2), str0 );
end
set(te,'verticalalignment','middle','horizontalalignment','left','tag','txCE');
set(te ,'fontsize',8,'fontweight','bold');
end
set(ax(i),'fontsize',6);
if i>1 & length(ax)>1
set(gca,'xtick',[])
end
end
fig0=get(0,'currentfigure');
set(0,'currentfigure',fig2);
delete(findobj(fig2,'type','axes','-and','tag','contrastname'));
% tituni=unique(tit);
titcmp=tit{1};
tituni{1}=titcmp;
clas=[1];clasno=1;
for i=2:length(tit);
if strcmp(titcmp,tit{i})==0;
clasno=clasno+1;
titcmp=tit{i} ;
tituni(end+1,1)={titcmp};
end
clas(i,1)=clasno ;
end
for i=1:clasno;%length(tituni)
% ix= find(strcmp(tit,tituni{i}));
ix=find(clas==i);
ly= [min(pos2(ix,2)) max(pos2(ix,2)+pos2(ix,4))-min(pos2(ix,2)) ];
% ly= [min(pos2(ix,2)) max(pos2(ix,4)) ];
% lys=diff(ly)/50;
% ly=[ly(1)+lys ly(2)-lys];
% ly= [min(pos2(ix,2))+.05 max(pos2(ix,2)+pos2(ix,4))-.05];
ax2=axes( 'position',[0.0 ly(1) pos2(ix(1),1)*0.4 ly(2) ]);
% te2=text(.5,0, [' ' tituni{i}]);
% set(te2,'Rotation',90,'horizontalalignment','left','fontsize',7,'fontweight','bold');
te2=text(.5,.5, [' ' tituni{i}]);
set(te2,'Rotation',90,'horizontalalignment','center','fontsize',7,'fontweight','bold');
set(ax2,'xtick',[],'ytick',[],'tag', 'contrastname');
if mod(i,2)==0
col=[0.9922 0.9176 0.7961];
else
col=[0.8039 0.8784 0.9686] ;
end
set(ax2,'color',col)
set(ax2,'ycolor','w','xcolor','w');
end
set(0,'currentfigure',fig0);
% set(0,'currentfigure',fig2);
% allfigs=findobj(0,'type','figure')
% set(0,'currentfigure',findobj(0,'tag','EOIbarstack'))
function keyboardCEstack(src,event)
if strcmp(event.Key,'leftarrow')
ax=findobj(gcf,'type','axes','-and','tag','barce');
if length(ax)==1; pos= (get(ax,'position'));
else; pos=cell2mat(get(ax,'position'));
end
pos2=pos;
pos2(:,3)=pos2(:,3)-.05;
if pos2(1,1)<pos2(1,3)
for i=1:length(ax)
set(ax(i),'position',pos2(i,:))
end
end
elseif strcmp(event.Key,'rightarrow')
ax=findobj(gcf,'type','axes','-and','tag','barce');
if length(ax)==1; pos= (get(ax,'position'));
else; pos=cell2mat(get(ax,'position'));
end
pos2=pos;
pos2(:,3)=pos2(:,3)+.05;
if pos2(1,1)<pos2(1,3)
for i=1:length(ax)
set(ax(i),'position',pos2(i,:));
end
end
elseif strcmp(event.Key,'uparrow')
% uv=get(gcf,'userdata');
% posf=uv.figsize;
posf=get(gcf,'position');
posf([2 4])=[ 0.0356 0.8878];
set(gcf,'position',posf);
elseif strcmp(event.Key,'downarrow')
uv=get(gcf,'userdata');
posf0=uv.figsize;
posf=get(gcf,'position');
posf([2 4])=[posf0([2 4])];
set(gcf,'position',posf);
end
function callchangecontrast2plot(ro,ra)
fig=findobj(0,'tag','EOIbar');
us=get(fig,'userdata');
us.definedIC=get(ro,'value');
set(fig,'userdata',us);
contrastestimate([],[]);
function pclose(ro,ra)
% 's'
close(findobj(0,'tag','tabelz'));
set(findall(0,'tag','menu_brodm'),'DeleteFcn',[]);
% fig3=findobj(0,'tag','Interactive');
% set(0,'currentfigure',fig3);
% delete(findobj(0,'tag','menu_brodm0'));%r
fig1=findobj(0,'tag','Interactive');
set(0,'currentfigure',fig1);
delete(findobj(0,'tag','menu_brodm'));
fig=findobj(0, 'Tag','Graphics');
% filecallback='fun2_activateResults';
for i=1:3
c=findobj(fig, 'Tag',['hX' num2str(i) 'r' ]);
str=get(c,'ButtonDownFcn');
orig='spm_mip_ui(''MoveStart'')';
set(c,'ButtonDownFcn',[ orig ]);
end
fig3=findobj(0,'Tag','Graphics'); %SECTIONS
ch=findobj(fig3,'type','image','tag','Transverse');
for i=1:length(ch)
ax =get(ch(i),'parent');
r=get(ax,'ButtonDownFcn');
% if size(r,1)<2
set(ax,'ButtonDownFcn',r(2));
% end
end
fig=findobj(0,'Tag','Graphics');
set(fig,'KeyPressFcn',[]);
function keyboardactivate
fig=findobj(0,'Tag','Graphics');
if ~isempty(fig)
set(fig,'KeyPressFcn',@keyboardx);
% set(fig,'WindowButtonUpFcn',@showbrodmann);
% dum=['delete(timerfindall);t = timer(''TimerFcn'',@showbrodmann,''startdelay'',.3);start(t)' ]
% set(fig,'WindowButtonUpFcn',dum);
try
im=findobj(fig,'type','image');
im= (im(end));
ch=sort(get(get(im,'UIContextMenu'),'children'));
idx=find(~cellfun('isempty',regexpi(get(ch,'label'),'goto ')));
for i=1:length(idx)
id=ch(idx(i));
co=getappdata(id,'funs');
if isempty(co)
code= get(id ,'callback') ;
setappdata(id,'funs',code) ;
end
co=getappdata(id,'funs');
co=[co ';showbrodmann'];
set(id ,'callback',co);
end
end
% set(fig, 'WindowScrollWheelFcn',@figScroll);
end
% function figScroll(src,event)
% dire=event.VerticalScrollCount ;
% fig=findobj(0,'Tag','Menu');
% us=getappdata(fig,'atlas');
% us.atlas=us.atlas+dire;
% if us.atlas>4; us.atlas=1;end
% if us.atlas<1; us.atlas=4;end
% setappdata(fig,'atlas','us');
% fig2=findobj(0,'Tag','Graphics');
% loadatlas(0,0,us.atlas);
% if ~isempty(findobj(fig2,'tag','brodtab'))
% batab;
% end
% showbrodmann;
function keyboardx(src,event)
if strcmp(event.Key,'u')
labs;
% fig=findobj(0,'Tag','Graphics')
elseif strcmp(event.Key,'t')
batab(1);% showtable;
elseif strcmp(event.Key,'z')
batab(2);% showtable;
% elseif strcmp(event.Key,'h')
% batab(0);% showtable;
elseif strcmp(event.Key,'s')
fun2_sections;
elseif strcmp(event.Key,'e')
pslices;
elseif strcmp(event.Key,'b')
fun2_showbrain;
elseif strcmp(event.Key,'c')
if strcmp(event.Modifier, 'control')
contrastestimate([],[]) ;
CEstack;
figure(findobj(0,'tag','EOIbarstack'));
elseif strcmp(event.Modifier, 'alt')
% vv=batab(1);
fig=findobj(0,'Tag','Graphics');
axtab=get(findobj(fig,'string','mm mm mm'),'parent');%table
hl=sort(findobj(axtab,'Tag','ListXYZ')) ;%mmText mm mm mm
% return
if isempty(axtab)
disp('there is no table');
return
end
cords=str2num(char([get(hl,'string')]));
for ii=1:size(cords,1)
%set MIPpointer
spm_mip_ui('SetCoords',cords(ii,:),findobj(findobj(0,'tag','Graphics'),...
'tag','hMIPax'));
drawnow
contrastestimate([],[]) ;
CEstack;
end
figure(findobj(0,'tag','EOIbarstack'));
else
contrastestimate([],[]) ;
end
elseif strcmp(event.Key,'r')
renderer ;
renderer('finflate',1);
elseif strcmp(event.Key,'m')
svc;
% elseif strcmp(event.Key,'q');%quit
% batab('close');
elseif strcmp(event.Key,'rightarrow')
changeContrast(1);
elseif strcmp(event.Key,'leftarrow')
changeContrast(2);
% elseif strcmp(event.Key,'p')
% jadiccaller
end
function changeContrast(direction)
state=0;
if ~isempty(findobj(findobj(0,'tag','Graphics'),'tag','Transverse')) ;
state=1; %show slices
end
if state~=1
fig=findobj(0,'tag','Graphics');
ch=findobj(fig,'type','text');
for i=1:length(ch)
try
tx=get(ch(i),'string');
if ischar(tx)
if ~isempty(regexpi(tx,'Statistics:'));
state=2;%%show wholebrainTable
end
end
end
end
end
fig=findobj(0,'tag','Interactive');
c=findobj(fig,'label','Contrasts');
c2=get(c,'children');
names=get(c2,'Label');
if direction==1
id=find(cellfun('isempty',strfind(names,'Next'))==0);
elseif direction==2
id=find(cellfun('isempty',strfind(names,'Previous'))==0);
end
if strcmp(get(c2(id),'Enable'),'on')
busy;
callbackCell =get(c2(id),'callback');
callbackCell{1}(c2(id),[],callbackCell{2:end});
fig=findobj(0,'tag','Graphics');
figure(fig);
busy(1);
end
%%update table/image
if state==1 %show slices
fun2_sections;
% return
elseif state==2 %show wholebrainTable
cb=get(findobj(findobj(0,'tag','Interactive'),'string','whole brain'),'callback');
hgfeval(cb);
% eval(cb);
end
% function batab %showtable
% function showbrodmann(src,evt)
%
% %
% fig1=findobj(0,'tag','Menu');
% atlas=getappdata(fig1,'atlas');
% tc=atlas.tc;
% area=atlas.area;
%
% %%
% fig2=findobj(0,'Tag','Interactive');
% axpar= get(findobj(0,'tag','hX2r'),'parent');
% xyz=spm_mip_ui('GetCoords',axpar);
% disp(xyz);
% cox=xyz(:)';
% tc2=tc(:,2:end);
% siz=size(tc);
%
%
% tab=single(zeros(size(cox,1) ,4 ));
% for i=1:size(cox,1)
% ci=cox(i,:);
% ci2=repmat(ci,[siz(1) 1]);
% ssq=sum((tc2-ci2).^2,2);
% imin=find(ssq==min(ssq));
% imin=imin(1);%check this: arbitrary take first idx
% tab(i,:)=tc(imin,:);
% end
%
%
% idlabel=tab(:,1);
% % area(idlabel)';
%
% ax=findobj(0,'tag','hX2r');
% ax= (get(ax,'parent'));
% set(gcf,'currentaxes',ax);
% yl=get(ax,'ylim');
% delete(findobj(0,'tag','brot'));
% tx=[area{idlabel} ' [' num2str(cox) ']'];
% te=text(0,yl(1),tx,'fontsize',14,'color','b','tag','brot','fontweight','bold');
% % te=text(0,yl(1),'wurst','fontsize',14,'color','b','tag','brot','fontweight','bold');
%
%
% % ######################################
% fig=findobj(0, 'Tag','Graphics');
%
% for i=1:3
% % c=findobj(fig, 'Tag','hX3r')
% c=findobj(fig, 'Tag',['hX' num2str(i) 'r' ]);
%
% str=get(c,'ButtonDownFcn');
% orig='spm_mip_ui(''MoveStart'')';
% set(c,'ButtonDownFcn',[ orig ';' 'fun2_activateResults']);
%
% end
%
% set(fig,'WindowButtonUpFcn',@showbrodmann);
|
github
|
philippboehmsturm/antx-master
|
getclustertable.m
|
.m
|
antx-master/mritools/labs/getclustertable.m
| 10,359 |
utf_8
|
a0366a31e247943486349aff661a214c
|
function table=getclustertable(vol,mat,dim,tresh)
% get clustertable for statistical fMRI-volume
% usage type
% type [1]: function table=getclustertable(vol,mat,dim,tresh)
% type [2]: function table=getclustertable([Num Dis]) -->for SPM
% type [2]: function table=getclustertable -->for SPM default
%============================================================================
% TYPE [1]: *** NON-SPM ***
% _____INPUT
% vol.. 3d-volume
% mat.. use hdr.mat
% dim.. use dim.mat
% thresh.. 4 threshold values -->see below
% _____[4 threshold values]_________________');
% vector with 4 values (separated with space) or use nans for specific default parameter, or viewer values if only the first ordered values have to be specified : [4 5 nan nan] equals[4 5]
% [1]HeightTResh 'HT' ...voxel with values above HT considered (MAgnitude threshold)
% [2]nvox/cluster 'NVC' ...nvoxels above NVC consideres as cluster (clutersize threshold)
% [3]NMaxima/Cluster to report 'NMC' ... number of maxima peaks within a cluster to report
% [4]distance between Clusters 'DC' ...distance between neighbouring clusters [mm]
% example: [4 10 4 5 ] ;MEANING:statistical Threshold >=[4];each cluster must have >=[10] adjacent voxels; give me [4] peakLabebels for each cluster; clusters must be separated by at least[5]mm
% example: [4 10 nan nan ];MEANING:same with SPM default settings [3]peaks per cluster, [8]mm cluster-separation
% example: [4 10 ] ;MEANING:same as previous example
% example: [4 nan 4 5 ] ;MEANING: as as 1st.example but report all clusters (no contraints regarding the size of cluster)
% _____OUTPUT
% struct with table
% ____EXAMPLE
% getclustertable(vol,img.mat,img.dim,[.4 10]); %HT=4 , NVC=10, (NMC & DC are feault: NMC=3, DC=8)
% getclustertable(vol,img.mat,img.dim); %HT=min magnitude in volume , NVC=1, (NMC & DC are feault: NMC=3, DC=8)
% getclustertable(vol,img.mat,img.dim,[.4 10, 5 2]); %HT=4 , NVC=10, NMC=5 , DC=5
%============================================================================
% TYPE [2]: *** SPM ***
% using SPM-data/struct
% function table=getclustertable -->for SPM with defaults [# cluster] & [# cluster distance]
% function table=getclustertable([Num Dis]) -->for SPM
% ...args:
% Num - number of maxima per cluster [3]
% Dis - distance among clusters {mm} [8]
% [1]HeightTResh,[2]nvox/cluster,[3]NMaxima/Cluster,[4]distance between Clusters
% vol
% dim
% us.functionalImg.mat
% hdr.mat=us.functionalImg.mat;
% hdr.dim=us.functionalImg.dim;
% us=get(gcf,'userdata');
% dim=us.functionalImg.dim;
if exist('tresh')==0; tresh=[];end
if exist('vol')==0; vol=[];end
if isempty(vol) |length(vol)==2 & isnumeric(vol)
% if strcmp(lower(vol),'spm')
% xSPM=evalin('base','xSPM');
% dim = xSPM.DIM;
% mat = xSPM.M;
% XYZ = xSPM.XYZ;
% XYZmm = xSPM.XYZmm;
% ts = xSPM.Z(:);
% end
xSPM=evalin('base','xSPM');
if isempty(vol)
k=spm_list( 'List' ,xSPM, findobj(0,'Tag','hReg'));
else
k=spm_list( 'List' ,xSPM, findobj(0,'Tag','hReg'),vol(1),vol(2));
end
iT =find(strcmp(k.hdr(2,:),'T' ) & strcmp(k.hdr(1,:),'peak' ));
ipuncor=find(strcmp(k.hdr(2,:),'p(unc)' ) & strcmp(k.hdr(1,:),'peak' ));
ivox =find(strcmp(k.hdr(2,:),'equivk' ) & strcmp(k.hdr(1,:),'cluster' ));
nvox=k.dat(:,ivox);nvox=cellfun(@(x){ sprintf('[%5.0f]',x) },nvox);
nvox=cellfun(@(x){regexprep(x,{'[' ']'},'')},nvox);
T =k.dat(:,[iT]);T=cellfun(@(x){ sprintf('%5.2f',x) },T);
p =k.dat(:,[ipuncor]); p=cellfun(@(x){ num2str(x)},p);
xyz = k.dat(:,[end]);
cords=round(cell2mat(cellfun(@(x){ x(:)'},xyz)));
% cellfun(@(x){ sprintf('[%4.0f %4.0f %4.0f]',x) },xyz)
addhead ={'N' 'T' 'p' };
add =[nvox T p ];
try
[labelx header labelcell]=pick_wrapper(cords, 'Noshow');
showtable3([0 0 1 1],[...
[ header(1:2) addhead header(3:end) ];...
[ labelx(:,1:2) add labelx(:,3:end) ],...
] ,'fontsize',8);
end
us=get(gcf,'userdata');
us.SPMgrap=0;
set(gcf,'userdata',us);
% table= labs(cords,{'addcolpre',{'CL-idx' 'stats' 'NvxClust'} ...
% [sv.A(ix_surv) sv.Z(ix_surv) sm.nvox(sv.idx(ix_surv)) ]});
return
else %IMG-struct
%from spm_read_vols (line: 53)
[R,C,P] = ndgrid(1:dim(1),1:dim(2),1:dim(3));
RCP = [R(:)';C(:)';P(:)'];
XYZ =RCP;
clear R C P
RCP(4,:) = 1;
% XYZmm = us.functionalImg.mat(1:3,:)*RCP;
XYZmm = mat(1:3,:)*RCP;
% vol=us.functionalImg.imgdata;
ts =vol(:)';
end
tr_magnitude =0.1;
tr_nvoxClust =1;
tr_npeakClust =3;
tr_clustDist =8;
ist= [tr_magnitude tr_nvoxClust tr_npeakClust tr_clustDist];
% is=find(ts>tr_magnitude);
% tresh=input('select MAGNITUDE threshold (select a number or let it empty): ','s')
% tresh=input('MAGNITUDE threshold and clustersize (2 values or empty (default), or nan): ','s')
% tresh=input('4 values: [1]HeightTResh,[2]clustersize,[3]Npeaks/Cluster,[4]distance between clusters (2 values or empty (default), or nan): ','s')
% disp('_____INPUTS_________________');
% disp('press enter for default, otherwise specify...');
% disp('4 values (separated with space) or use nans for specific default parameter, or viewer values if only the first ordered values have to be specified : [4 5 nan nan] equals[4 5] ');
% disp('[1]HeightTResh,[2]nvox/cluster,[3]Npeaks/Cluster,[4]distance between Clusters');
% disp('example: "4 10 4 5 ";MEANING:statistical Threshold >=[4];each cluster must have >=[10] adjacent voxels; give me [4] peakLabebels for each cluster; clusters must be separated by at least[5]mm ' );
% disp('example: "4 10 nan nan ";MEANING:same with SPM default settings [3]peaks per cluster, [8]mm cluster-separation' );
% disp('example: "4 10 ";MEANING:same as previous example' );
% disp('example: "4 nan 4 5 ";MEANING: as as 1st.example but report all clusters (no contraints regarding the size of cluster)' );
% tresh=input('4 values: ' ,'s');
if ~isempty(tresh)
% val=str2num(tresh);
val= (tresh);
soll=[tr_magnitude tr_nvoxClust tr_npeakClust tr_clustDist] ;
% val=[4 0 8 ]
val(size(val,2)+1:size(soll,2))=nan;
val(isnan(val))= soll(isnan(val));
tr_magnitude =val(1);
tr_nvoxClust =val(2);
tr_npeakClust =val(3);
tr_clustDist =val(4);
ist= [tr_magnitude tr_nvoxClust tr_npeakClust tr_clustDist];
end
is=find(ts>=tr_magnitude);
%% tester idx Values match with XYZ-VOLUME
% % % % % if 0
% % % % % itest=252;
% % % % % ts(is(itest));
% % % % % % XYZ(:,is(itest))
% % % % % vol(XYZ(1,is(itest)),XYZ(2,is(itest)),XYZ(3,is(itest)));
% % % % % end
Z=ts(is);
XYZsurv=XYZ(:,is);
% hdr.mat=us.functionalImg.mat;
% hdr.dim=us.functionalImg.dim;
hdr.mat=mat;
hdr.dim=dim;
[sm]=pclustermaxima(Z,XYZsurv,hdr) ; %get MAX of clusters
try
[sv]=pclustermaximaContraint(sm.Z,sm.regnr,sm.XYZ,sm.hdr,tr_npeakClust,tr_clustDist);
catch
[sv]=pclustermaximaContraint(sm.Z,sm.regnr,sm.XYZ,sm.hdr,3,8);
% disp('use SPM-defaults for NpeaksPerCluster[3] and distance between clusters[8mm]-->there was an error in parameter specification');
end
%[sv]=pclustermaximaContraint(sm.Z,sm.regnr,sm.XYZ,sm.hdr,10,4);
% hdr.mat=us.functionalImg.mat;
% hdr.dim=us.functionalImg.dim;
% [ st ]=pclustertreshIMG('Accuracies', ts, tr_magnitude,tr_nvoxClust, XYZ,hdr,1 )
% [ st ]=pclustertreshIMG('Accuracies', ts, 3,30, XYZ,hdr,1 )
%
% [ st ]=pclustertreshIMG('Accuracies',Z, 0, 0, XYZsurv,hdr,1 )
if 0
%sm.Z
% [ st ]=pclustertreshIMG('Accuracies', sm.Z,70,30,c.XYZ,c.hdr,0 )
a.hdr.mat=us.functionalImg.mat;
a.hdr.dim=dim;
[ st ]=pclustertreshIMG('Accuracies', ts, 70,40, XYZ,a.hdr,1 )
% acc3=acc2;
% acc3(acc3<50)=50;
x.mask='D:\relapse_TWU\mask.nii'
x.pa_out='D:\relapse_TWU\results'
strct=spm_vol(x.mask);
vol3=makevol( st.Z, st.XYZ, strct,nan);
pwritevol2vol(fullfile(x.pa_out, 'acc_tr70_tr40voxClst'),vol3,strct,'acc_tr');
Z=st.Z;
XYZsurv=st.XYZ;
hdr.mat=us.functionalImg.mat;
hdr.dim=us.functionalImg.dim;
[sm]=pclustermaxima(Z,XYZsurv,hdr) ; %get MAX of clusters
[sv]=pclustermaximaContraint(sm.Z,sm.regnr,sm.XYZ,sm.hdr,3,8);
end
% if 0 % magnitude and clustersize treshold
% end
clustsize=sm.nvox(sv.idx);
% if tr_nvoxClust==0
% labs(sv.XYZmm,{'addcolpre',{'CL-idx' 'stats' 'NvxClust'} ...
% [sv.A sv.Z sm.nvox(sv.idx) ]});
% else %cklustertreshold
ix_surv=find(clustsize>=tr_nvoxClust) ;
table= labs(sv.XYZmm(:,ix_surv),{'addcolpre',{'CL-idx' 'stats' 'NvxClust'} ...
[sv.A(ix_surv) sv.Z(ix_surv) sm.nvox(sv.idx(ix_surv)) ]});
% labs(sv.XYZmm(:,ix_surv),{'addcolpre',{'CL-idx' 'stats' 'NvxClust'} ...
% [sv.A(ix_surv) sv.Z(ix_surv) sm.nvox(sv.idx(ix_surv)) ]});
% end
%ADDON
% us=get(gcf,'userdata');
% us.addlab=
% [1]HeightTResh,[2]nvox/cluster,[3]Npeaks/Cluster,[4]distance between Clusters
disp(['[1]HeightTResh: ' num2str(ist(1)) ]);
disp(['[2]nvox/cluster: ' num2str(ist(2)) ]);
disp(['[3]Nmaxima(Peaks)/Cluster: ' num2str(ist(3)) ]);
disp(['[4]distance between Clusters : ' num2str(ist(4)) ]);
set(gcf,'tag','');
% disp('params');
% disp(num2str(ist));
|
github
|
philippboehmsturm/antx-master
|
pwrite2file.m
|
.m
|
antx-master/mritools/labs/pwrite2file.m
| 1,903 |
utf_8
|
ef4698616f9af2dada7a256479c962f6
|
function pwrite2file(name2wr, info,varargin );
%___________________________________________________________________________
% function pwrite2file(name2wr, info );
% function pwrite2file(name2wr, info,1 ); %OPENS WITH GUI
%___________________________________________________________________________
% pwrite2file(name2wr, info );:
% IN____
% pathRT :path (with endeslash)
% name2wr :filename
% info : -writes info/data (must be a cell)
% -can be empty,[];
% -if info is 'VMRK', it writes the standard BA-VMRK-info
% _________________________________________________________________________
% see also preadfile pwrite2file,pwrite2file2
%___________________________________________________________________________
% paul,BNIC, mar.2007
%___________________________________________________________________________
% 'l'
if nargin==3
[fi pa]= uiputfile;
name2wr=[pa fi];
end
a=whos('info');
clas=a.class;
% 'a'
%############################################# double2char
if strcmp(clas,'double')==1 | strcmp(clas,'single')==1
for i=1:size(info,1)
info2(i,:)={num2str(info(i,:))};
end
info=info2;
a=whos('info');
clas=a.class;
end
%#############################################
fid = fopen([ name2wr ],'w','n');
%------info
if prod(size(info))==1 & ( strcmp(clas,'cell')==1 | strcmp(clas,'char')==1)
i=1;
dumh=char( (info(i,:)) );
fprintf(fid,'%s',dumh);
elseif prod(size(info))~=1 & ( strcmp(clas,'cell')==1 | strcmp(clas,'char')==1)
for i=1:size(info,1)
dumh=char( (info(i,:)) );
fprintf(fid,'%s\n',dumh);
end
elseif prod(size(info))~=1 & (strcmp(clas,'double')==1 | strcmp(clas,'single')==1)
for i=1:size(info,1)
dumh=sprintf('%s', num2str((info(i,:))));
fprintf(fid,'%s\n',num2str(dumh));
end
end
fclose(fid);
|
github
|
philippboehmsturm/antx-master
|
pclustermaximaContraint.m
|
.m
|
antx-master/mritools/labs/pclustermaximaContraint.m
| 9,793 |
utf_8
|
69cf55d2404e3c6d881f77f0cf4216fe
|
function [sv]=pclustermaximaContraint(Z,A,XYZ,hdr,Num,Dis,invertZ)
%number of maxima pr cluster and distance among cluster copy of [spm_list ~line 204]
%
% function [sv]=pclustermaximaContraint(Z,A,XYZ,hdr,Num,Dis)
% NOTE: usage after applying [pclustermaxima]
% IN
% Z [vector] (Z,T but not p!)
% A [vector]regnr: [254x1 double] region number
% XYZ [3xNvox double] locations [x y x]' {in voxels}
% hdr header
% Num default(3) % number of maxima per cluster
% Dis default(8) % distance among clusters (mm)
% OUT
% idx: [33x1 double] indices
% tb: [33x6 double] table [xyzmm(3cols) clusterIndex Zvector idx]
% Z: [1x33 double] survived Zvector
% A: [33x1 double] survived region number
% XYZ: [33x1 double] ..
% XYZmm: [33x1 double] ..
% hdr: [1x1 struct] ...
% EXAMPLE: contrainscluster with max N<=3 max per cluster with distance of 8mm
% [sv]=pclustermaximaContraint(sm.Z,sm.regnr,sm.XYZ,sm.hdr,3,8)
if 0
Z =sm.Z ;
A =sm.regnr ;
XYZ=sm.XYZ ;
hdr=sm.hdr;
Num=3
Dis=8
end
if 1 strcmp(invertZ,'invert')
Z=-Z;
end
Z2=Z;%copy to be used later
% XYZmm2=sm.XYZmm
M=hdr.mat;
XYZmm = M(1:3,:)*[XYZ; ones(1,size(XYZ,2))];
test=sortrows([XYZmm' A Z(:)],4);
%-Local maxima p-values & statistics
%----------------------------------------------------------------------
% HlistXYZ = [];
tb=[];
while numel(find(isfinite(Z)))
%-Find largest remaining local maximum
%------------------------------------------------------------------
[U,i] = max(Z); % largest maxima
j = find(A == A(i)); % maxima in cluster
% %-Compute cluster {k} and peak-level {u} p values for this cluster
% %------------------------------------------------------------------
% if STAT ~= 'P'
% Nv = N(i)/v2r; % extent {voxels}
%
% Pz = spm_P(1,0, U,df,STAT,1,n,S); % uncorrected p value
% Pu = spm_P(1,0, U,df,STAT,R,n,S); % FWE-corrected {based on Z}
% [Pk Pn] = spm_P(1,N(i),u,df,STAT,R,n,S); % [un]corrected {based on k}
% if topoFDR
% Qc = spm_P_clusterFDR(N(i),df,STAT,R,n,u,QPc); % cluster FDR-corrected {based on k}
% Qp = spm_P_peakFDR(U,df,STAT,R,n,u,QPp); % peak FDR-corrected {based on Z}
% Qu = [];
% else
% Qu = spm_P_FDR( U,df,STAT,n,QPs); % voxel FDR-corrected {based on Z}
% Qc = [];
% Qp = [];
% end
%
% if Pz < tol % Equivalent Z-variate
% Ze = Inf; % (underflow => can't compute)
% else
% Ze = spm_invNcdf(1 - Pz);
% end
% else
% Nv = N(i);
%
% Pz = [];
% Pu = [];
% Qu = [];
% Pk = [];
% Pn = [];
% Qc = [];
% Qp = [];
% Ze = spm_invNcdf(U);
% end
%
% Specifically changed so it properly finds hMIPax
%------------------------------------------------------------------
tXYZmm = XYZmm(:,i);
% HlistXYZ = [HlistXYZ, h];
% if spm_XYZreg('Edist',xyzmm,XYZmm(:,i))<tol && ~isempty(hReg)
% set(h,'Color','r')
% end
% hPage = [hPage, h];
% y = y - dy;
%
% if topoFDR
% [TabDat.dat{TabLin,3:12}] = deal(Pk,Qc,Nv,Pn,Pu,Qp,U,Ze,Pz,XYZmm(:,i));
% else
% [TabDat.dat{TabLin,3:12}] = deal(Pk,Qc,Nv,Pn,Pu,Qu,U,Ze,Pz,XYZmm(:,i));
% end
% TabLin = TabLin + 1;
%-Print Num secondary maxima (> Dis mm apart)
%------------------------------------------------------------------
[l q] = sort(-Z(j)); % sort on Z value
D = i;
% disp([XYZmm(:,D)' A(D) Z(D)]);
tb(end+1,:)=[XYZmm(:,D)' A(D) Z(D) D];
for i = 1:length(q)
d = j(q(i));
if min(sqrt(sum((XYZmm(:,D)-XYZmm(:,d)*ones(1,size(D,2))).^2)))>Dis;
if length(D) < Num
% % Paginate if necessary
% %------------------------------------------------------
% if y < dy
% h = text(0.5,-5*dy,sprintf('Page %d',...
% spm_figure('#page',Fgraph)),...
% 'FontName',PF.helvetica,...
% 'FontAngle','Italic',...
% 'FontSize',FS(8));
%
% spm_figure('NewPage',[hPage,h])
% hPage = [];
% y = y0;
% end
% voxel-level p values {Z}
%------------------------------------------------------
% if STAT ~= 'P'
% Pz = spm_P(1,0,Z(d),df,STAT,1,n,S);
% Pu = spm_P(1,0,Z(d),df,STAT,R,n,S);
% if topoFDR
% Qp = spm_P_peakFDR(Z(d),df,STAT,R,n,u,QPp);
% Qu = [];
% else
% Qu = spm_P_FDR(Z(d),df,STAT,n,QPs);
% Qp = [];
% end
% if Pz < tol
% Ze = Inf;
% else
% Ze = spm_invNcdf(1 - Pz);
% end
% else
% Pz = [];
% Pu = [];
% Qu = [];
% Qp = [];
% Ze = spm_invNcdf(Z(d));
% end
% h = text(tCol(7),y,sprintf(TabDat.fmt{7},Pu),...
% 'UserData',Pu,...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% hPage = [hPage, h];
%
% if topoFDR
% h = text(tCol(8),y,sprintf(TabDat.fmt{8},Qp),...
% 'UserData',Qp,...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% else
% h = text(tCol(8),y,sprintf(TabDat.fmt{8},Qu),...
% 'UserData',Qu,...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% end
% hPage = [hPage, h];
% h = text(tCol(9),y,sprintf(TabDat.fmt{9},Z(d)),...
% 'UserData',Z(d),...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% hPage = [hPage, h];
% h = text(tCol(10),y,sprintf(TabDat.fmt{10},Ze),...
% 'UserData',Ze,...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% hPage = [hPage, h];
% h = text(tCol(11),y,sprintf(TabDat.fmt{11},Pz),...
% 'UserData',Pz,...
% 'ButtonDownFcn','get(gcbo,''UserData'')');
% hPage = [hPage, h];
% specifically modified line to use hMIPax
%------------------------------------------------------
tXYZmm = XYZmm(:,d);
% h = text(tCol(12),y,...
% sprintf(TabDat.fmt{12},tXYZmm),...
% 'Tag','ListXYZ',...
% 'ButtonDownFcn',[...
% 'hMIPax = findobj(''tag'',''hMIPax'');',...
% 'spm_mip_ui(''SetCoords'',',...
% 'get(gcbo,''UserData''),hMIPax);'],...
% 'Interruptible','off','BusyAction','Cancel',...
% 'UserData',XYZmm(:,d));
% HlistXYZ = [HlistXYZ, h];
% if spm_XYZreg('Edist',xyzmm,XYZmm(:,d))<tol && ...
% ~isempty(hReg)
% set(h,'Color','r')
% end
% hPage = [hPage, h];
D = [D d];
% y = y - dy;
% if topoFDR
% [TabDat.dat{TabLin,7:12}] = ...
% deal(Pu,Qp,Z(d),Ze,Pz,XYZmm(:,d));
% else
% [TabDat.dat{TabLin,7:12}] = ...
% deal(Pu,Qu,Z(d),Ze,Pz,XYZmm(:,d));
% end
% TabLin = TabLin+1;
% disp( [XYZmm(:,d)' A(d) Z(d)]);
tb(end+1,:)=[XYZmm(:,d)' A(d) Z(d) d];
end
end
end
Z(j) = NaN; % Set local maxima to NaN
end % end region
idx=tb(:,6);
sv.idx= tb(:,6);
sv.tb=tb;
if 1 strcmp(invertZ,'invert')
sv.Z =-[Z2(idx)];
else
sv.Z =[Z2(idx)];
end
sv.A =A(idx);
sv.XYZ =XYZ(:,idx);
sv.XYZmm =XYZmm(:,idx);
sv.hdr =hdr;
if 1 strcmp(invertZ,'invert')
sv.Z =sv.Z(:);
else
sv.Z =-sv.Z(:);
end
sv.A =sv.A(:);
% [sv]=pclustermaximaContraint(Z,A,XYZ,hdr,Num,Dis)
|
github
|
philippboehmsturm/antx-master
|
conmanhook.m
|
.m
|
antx-master/mritools/labs/conmanhook.m
| 8,679 |
utf_8
|
45692d6801449f4c645f38ab4371be28
|
function conmanhook(ra,r0,val)
% hook in the spm_contrastmanager
% [1] conmanhook('hook') ;%hook & modify spm_conman
% [2] conmanhook('unhook') ; %remove modification in spm_conman
%============================================================================
% hook to spm_conman
%============================================================================
if ~exist('ra')
help conmanhook;
return
end
if strcmp(ra,'hook')|| strcmp(ra,'unhook') %hook to spm_conman
file=which('spm_conman.m') ;
fid=fopen(file);
j=1;
while 1
tline = fgetl(fid);
if ~ischar(tline), break, end
v{j,1}=tline;
j=j+1;
end
fclose(fid);
del=[];
%check existence of [conmanhook]
ixcheck=find(~cellfun('isempty',regexpi(v,...
{'conmanhook\(hh,\[\],0\)'} ))==1);
for i=1:length(ixcheck)
i1=min(regexpi(v{ixcheck(i)},'%'));
i2=min(regexpi(v{ixcheck(i)},'conmanhook'));
if i2>i1; del(i)=1; end
end
ixcheck(del==1)=[];
% ixcheck
if strcmp(ra,'hook')
% '\sconmanhook\(hh,\[\],0\)|
if ~isempty(ixcheck)
disp(['conmanhook: in [spm_conman.m] line ' num2str(ixcheck) ' already exists']);
return;
end
ix1=find(~cellfun('isempty',regexpi(v,'hh = uicontextmenu'))==1);
ix2=find(strcmp(v,''));
ix2=ix2(min(find(ix2>ix1)));
v2=[v(1:ix2); {'conmanhook(hh,[],0);'} ; v(ix2+1:end) ];
disp(['conmanhook: in [spm_conman.m] line ' num2str(ix2+1) ' created']);
else
if isempty(ixcheck); return ; end
v2=v;
v2(ixcheck)=[];
disp(['conmanhook: in [spm_conman.m] line ' num2str(ixcheck(:)') ' removed']);
end
fid = fopen([ file ],'w','n');% 'muell.m'
for i=1:size(v2,1)
dumh=char( (v2(i,:)) );
fprintf(fid,'%s\n',dumh);
end
fclose(fid);
return
end
%============================================================================
% initialize during spm_results ui
%============================================================================
if val==0 %initialize
hh=ra;
uimenu(hh,'Label','delete contrast...',...
'Tag','deleteC',...
'CallBack', {@conmanhook,1},...
'Interruptible','off','BusyAction','Cancel');
uimenu(hh,'Label','move to TOP...',...
'Tag','moveupC',...
'CallBack', {@conmanhook,2},...
'Interruptible','off','BusyAction','Cancel');
uimenu(hh,'Label','move to BOTTOM...',...
'Tag','movedownC',...
'CallBack', {@conmanhook,3},...
'Interruptible','off','BusyAction','Cancel');
return
end
F = gcbf;
hConList = findobj(F,'Tag','ConList');
Q = get(hConList,'UserData');
i = get(hConList,'Value');
%-Make sure there's only one selected contrast
%------------------------------------------------------------------
% if length(i)~=1
% msgbox('Can only rename a single contrast!',...
% sprintf('%s%s: %s...',spm('ver'),...
% spm('GetUser',' (%s)'),mfilename),'error','modal')
% return
% end
%-Get contrast structure array and indicies of current contrast
%------------------------------------------------------------------
SPM = get(F,'UserData');
xCon = SPM.xCon;
I = Q(i);
%-Get new name
%------------------------------------------------------------------
% str = sprintf('Enter new name for contrast %d (currently "%s"):',I,xCon(I).name);
% nname = inputdlg(str,'SPM: Rename contrast',1,{xCon(I).name},'off');
% if isempty(nname), return, end
if val==1 %delete
%-Change name in ConList
%------------------------------------------------------------------
tmp = get(hConList,'String');
tmp(i) =[];% strrep(tmp{i},xCon(I).name,nname{1});
set(hConList,'Value',1);
try
sep=regexpi(tmp,'{');
for j=1:size(tmp,1)
str=repmat('0',[1 3]);
str(end-length(num2str(j))+1:end)=num2str(j);
tmp{j}=[str tmp{j}(sep{j}-1:end)];
end
end
set(hConList,'String',tmp)
%-Change name in contrast structure
%------------------------------------------------------------------
% xCon(I).name = nname{1};
for c=1:length(I)
con=xCon(I(c));
try; delete( con.Vcon.fname); catch; 'a';end
try; delete(regexprep(con.Vcon.fname,'.img','.hdr')); catch; 'a';end
try; delete( con.Vspm.fname); catch; 'a';end
try; delete(regexprep(con.Vspm.fname,'.img','.hdr')); catch; 'a';end
end
%....rename files and contrast-linkage
ds={};
del=zeros(length(xCon),1);
del(I)=1;
newnum=zeros(length(xCon),1);
newnum(find(del==0))=[1:length(find(del==0))];
for d=1:length(xCon);
try; d1=xCon(d).Vcon.fname; catch; d1='';end
try; d2=xCon(d).Vspm.fname; catch; d2='';end
ds(end+1,:)={del(d) newnum(d) d1 d2 };
end
ds
id=min(find(del==1))
id=id+1:length(xCon)
for d=1 :length(id)
this=id(d)
if ~isempty(ds{this,3})
newID=ds{this,2}
img=ds{this,3}
lim=[strfind(img,'_') strfind(img,'.')]
str=repmat('0',[1 4]);
str(end-length(num2str(newID))+1:end)=num2str(newID) ;
ds{this,5}= [img(1:lim(1)) str img(lim(2):end) ]
img=ds{this,4}
lim=[strfind(img,'_') strfind(img,'.')]
str=repmat('0',[1 4]);
str(end-length(num2str(newID))+1:end)=num2str(newID) ;
ds{this,6}= [img(1:lim(1)) str img(lim(2):end) ]
try; movefile( ds{this,3} , ds{this,5});end
try; movefile(strrep(ds{this,3},'.img','.hdr') ,strrep(ds{this,5},'.img','.hdr'));end
try; movefile( ds{this,4} , ds{this,6});end
try; movefile(strrep(ds{this,4},'.img','.hdr') ,strrep(ds{this,6},'.img','.hdr'));end
xCon(this).Vcon.fname= ds{this,5};
xCon(this).Vspm.fname= ds{this,6};
xCon(this).Vcon.descrip=regexprep(xCon(this).Vcon.descrip,...
[num2str(this) ':'],[num2str(newID) ':'])
xCon(this).Vspm.descrip=regexprep(xCon(this).Vspm.descrip,...
[num2str(this) ':'],[num2str(newID) ':'])
end
end
xCon(I)=[];
SPM.xCon = xCon;
elseif val==2 | val==3 %on top | down
tmp = get(hConList,'String');
if val==2
ord=[ i setdiff(1:size(tmp,1) , i ) ];
pointer=1;
else
ord=[ setdiff(1:size(tmp,1) , i ) i ];
pointer=length(ord);
end
tmp=tmp(ord);
% sep=regexpi(tmp,'{');
% for i=1:size(tmp,1)
% str=repmat('0',[1 3]);
% str(end-length(num2str(i))+1:end)=num2str(i);
% tmp{i}=[str tmp{i}(sep{i}-1:end)];
% end
set(hConList,'String',tmp);
xCon=reorder(xCon,ord);
;
SPM.xCon = xCon;
set(hConList,'Value',pointer);
% set(hConList,'Value',1);
end
% ord
% val
set(F,'UserData',SPM);
function xCon=reorder(xCon,ord)
list={};
xCon2=xCon(ord);
for i=1:length(xCon2)
newID= (i);
if ~isempty(xCon2(i).Vcon);
img=xCon2(i).Vcon.fname;
lim=[strfind(img,'_') strfind(img,'.')];
str=repmat('0',[1 4]);
str(end-length(num2str(newID))+1:end)=num2str(newID) ;
img2= [img(1:lim(1)) str img(lim(2):end) ];
xCon2(i).Vcon.fname =img2;
img3=xCon2(i).Vspm.fname;
lim=[strfind(img3,'_') strfind(img3,'.')];
str=repmat('0',[1 4]);
str(end-length(num2str(newID))+1:end)=num2str(newID) ;
img4= [img3(1:lim(1)) str img3(lim(2):end) ];
xCon2(i).Vspm.fname =img4;
xCon2(i).Vcon.descrip=regexprep(xCon2(i).Vcon.descrip,...
[num2str(i) ':'],[num2str(newID) ':']);
xCon2(i).Vspm.descrip=regexprep(xCon2(i).Vspm.descrip,...
[num2str(i) ':'],[num2str(newID) ':']);
list(end+1,:)= {img img2 img3 img4} ;
end
end
list2=[list(:,1:2);list(:,3:4);];
list2=[list2; regexprep(list2,'.img','.hdr')];
%rename
for i=1:size(list2,1)
movefile( [ list2{i,1} ],['TPM_' list2{i,2} ]);
end
for i=1:size(list2,1)
movefile( [ 'TPM_' list2{i,2} ],[ list2{i,2} ]);
end
xCon=xCon2;%(ord);
|
github
|
philippboehmsturm/antx-master
|
showtable2.m
|
.m
|
antx-master/mritools/labs/showtable2.m
| 8,329 |
utf_8
|
9827e3822a85cb1d20e80bad5cfc0824
|
function showtable2(pos,tab,varargin)
if 0
showtable2([0 0 1 1],tab,'fontsize',9,'fontweight','normal','backgroundcolor','w')
if ~exist('fontsize','var'); fontsize=8;end
if ~exist('color','var'); color='k';end
end
colbg=[1 1 1; 1 1 .8;];
for i=1:size(colbg,1);
colbghex(i,:) = reshape(dec2hex( round( colbg(i,:).*255))' ,[6 1])';
end
colbghead= reshape(dec2hex( round( [1 .7 .4] .*255))' ,[6 1])';
colfont= reshape(dec2hex( round( [0 0 1] .*255))' ,[6 1])';
for i=1:size(tab,2)
kn=char([tab(:,i); ]);
for j=1:size(tab(:,i),1)
dum= tab{j,i};
if isempty(regexpi(dum,'#['))
% labely{j,i}= [repmat(' ' ,[1 1+size(kn,2)-length(dum)]) dum ' ' ];
labely{j,i}= [repmat(' ' ,[1 size(kn,2)-length(dum)]) dum ' ' ];
else %color
delcol=length(strfind(dum,'#[') : strfind(dum,']') );
labely{j,i}= [repmat(' ' ,[1 size(kn,2)-length(dum)+delcol]) dum ' ' ];
end
end
end
dx=labely;
dz={};dz2={};
% colf= 'black';
for i=1:size(dx,1)
dy='';dy2='';
for j=1:size(dx,2)
df=dx{i,j};
if ~isempty(strfind(df,'#['));
icol1 =strfind(df,'#[')+1;
icol2=strfind(df,'] ');
dfcol=df(icol1:icol2);
df=df([1:icol1-2 icol2+1:end]);
eval(['mycolor=' dfcol ';']);
mycolor=reshape(dec2hex( round( mycolor.*255))' ,[6 1])';
doMycol=1;
else
doMycol=0;
end
if i==1
df=[ '<b><u><font color="black" bgcolor="' colbghex(rem(j,2)+1,:) '">' df '</b>' '</font>' ];
else
if j~=2
colf= 'black';
bold='';
else
colf= colfont;
bold='<b>';
end
% if i==3%%i==3;
if doMycol==1%%i==3;
colf= mycolor;% 'FF00FF';
bold='<b>';
end
if rem(i-1,5)==0 | i==size(dx,1)
underline='<u>';
else
underline='';
end
df=[underline bold '<font color="' colf '" bgcolor="' colbghex(rem(j,2)+1,:) '">' df '</b>' '</font>' ];
end
% if rem(j,2)==0
% if j==2
% df=['<html>' vorl{2,2} df vorl{2,3}]
% end
dy =[dy df ];%HTML
dy2=[dy2 dx{i,j}];%RAW
end
dz{i,1} =dy;
dz2{i,1}=dy2;
end
dz=cellfun(@(dz) {['<html><pre>' dz '</pre>']} ,dz);
fontsize=9;
fig= findobj(0,'tag','tabelz');
if ~isempty(fig);
posfig=get(fig,'position') ;
lb=findobj(fig,'tag','txt');
set(lb,'string',dz);
else
figure;set(gcf,'color','w', 'tag' ,'tabelz' );
set(gcf,'units','normalized','menubar','none');
set(gcf,'position',[0.7090 0.7911 0.1743 0.1767]);
fig= findobj(0,'tag','tabelz');
set(gcf,'name','CURRENT LABEL');
try
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jframe=get(fig,'javaframe');
icon=strrep(which('labs.m'),'labs.m','monkey.png');
jIcon=javax.swing.ImageIcon(icon);
jframe.setFigureIcon(jIcon);
end
% if ~isempty(fig);
% set(gcf,'position',posfig) ;
% end
if isempty(pos)
pos=[0 0 1 1];
end
% p = get(hx,'position');
h= uicontrol('tag','txt', 'units','normalized','Style', 'listbox', 'String', dz,...
'position',pos,'backgroundcolor','w',...
'foregroundcolor','k','fontsize',fontsize );
set(h,'FontName','courier new');
set(h,'Callback',@clicked)
if ~isempty(varargin)
set(h,varargin{:});
end
if 0
set(gcf,'units','characters');
pos=get(gcf,'position');
% pos(3)=pos(1)+length(dz2{1,:})-30
pos(3)=length(dz2{1,:})+80;
% pos(4)=size(dz2,1)+1
set(gcf,'position',pos);
set(gcf,'units','normalized');
pos=get(gcf,'position');
pos(1)=.1;
set(gcf,'position',pos);
end
%----------------------------------
% context
%----------------------------------
cmenu = uicontextmenu;
set(h,'UIContextMenu', cmenu);
item1 = uimenu(cmenu, 'Label','table to workspace ', 'Callback', {@gcontext, 1});%ws
item2 = uimenu(cmenu, 'Label','save table', 'Callback', {@gcontext, 2});%save
end
% set(gcf,'WindowScrollWheelFcn',{@gwheel,1});
% -----------------------------------------------------------
% x.scroll =findjobj(fig,'Class', 'UIScrollPane$1');%scroll
x.fontsize =fontsize;
x.evntModifier=0;
x.table =dz2;
x.tablec =tab;
set(fig,'userdata',x);
if isempty(findobj(findobj('Tag','tabelz'),'tag','aot'))%ALWAYS ON TOP
set(0,'currentfigure', findobj('Tag','tabelz') );
b1 = uicontrol('Style', 'checkbox', 'String', '','fontsize',8,...%'pushbutton'
'units','normalized','TooltipString','toggle: alway on top',...
'Position', [0 0 .07 .07], 'Callback', @ontop,'backgroundcolor',[1 1 1],'tag','aot');
end
% r=findobj(fig,'tag','aot');
% set(r,'value',newstate);
% ontop;
function ontop(src,evnt)
us=get(gcf,'userdata');
if isfield(us,'aot')==0;
us.aot=0;
end
try
fig=findobj('Tag','tabelz');
newstate=abs(mod([us.aot],2)-1);
jFrame = get(handle(fig),'JavaFrame');
jFrame.fFigureClient.getWindow.setAlwaysOnTop(newstate);
r=findobj(fig,'tag','aot');
set(r,'value',newstate);
us.aot=newstate;
set(gcf,'userdata',us);
end
function clicked(hh,ss)
x=get(gcf,'userdata');
lb=findobj(gcf,'tag','txt');
val=get(lb,'value');
cords=str2num(x.tablec{val,2});
disp(cords);
try
hMIPax = findobj('tag','hMIPax');
spm_mip_ui('SetCoords',cords,hMIPax);
showbrodmann.m
end
%----------------------------------
% contextmenu
%----------------------------------
function gcontext(obj, event, mode)
x= get(gcf,'userdata');
if mode==1
label.table =x.table ;
label.tablec=x.tablec;
assignin('base','label' ,label);
disp('struct "label" assigned to workspace');
elseif mode==2
[fi pa]=uiputfile(pwd,'save table');
if fi~=0
pwrite2file(fullfile(pa,fi),x.table),
end
end
%----------------------------------
% mousewheel
%----------------------------------
function gwheel(obj, event, mode)
try
x=get(gcf,'userdata');
if x.evntModifier==0 %[scroll text]
x=get(gcf,'userdata'); scroll=x.scroll;
try
% set(scroll,'value', get(scroll,'value') +event.VerticalScrollCount*25);
% set(scroll,'value', get(scroll,'value') +round(event.VerticalScrollCount*20));
class(get(scroll,'value') )
% set(gcf,'units','characters')
% pos=get(gcf,'position')
step=round(event.VerticalScrollCount*40);
set(scroll,'value', get(scroll,'value') +step);
catch %after savibng Image
x.scroll=findjobj(gcf,'Class', 'UIScrollPane$1');%scroll
set(gcf,'userdata',x);
end
drawnow
else %define fontsize with mouse wheel
tx= findobj(gcf,'tag','txt');
fs= get(tx,'fontsize');
fs2=fs+event.VerticalScrollCount;
if fs2>1
set(tx,'fontsize', fs2) ;
end
x.evntModifier=0;
set(gcf,'userdata',x);
end
end
%----------------------------------
% arrow keys
%----------------------------------
function fontsize(src,evnt)
x=get(gcf,'userdata');
if strcmp(evnt.Modifier,'control'); %[control]+mousewheel
x.evntModifier=1; %if [control]-key is pressed..
%code this for mousewheel-specifications
else
x.evntModifier=0;
tx= findobj(gcf,'tag','txt');
if strcmp(evnt.Key,'leftarrow')
set(tx,'fontsize', get(tx,'fontsize')-1) ;
elseif strcmp(evnt.Key, 'rightarrow')
set(tx,'fontsize', get(tx,'fontsize')+1) ;
end
end
set(gcf,'userdata',x);
|
github
|
philippboehmsturm/antx-master
|
busy.m
|
.m
|
antx-master/mritools/labs/busy.m
| 1,860 |
utf_8
|
566b8dd115197f908a53bd983743ac48
|
function busy(varargin)
% fg
% text(.5,.5,'dddd')
% set(gcf,'menubar','none')
% frame = get(handle(gcf), 'JavaFrame');
%
%
% clear
if nargin==1
if varargin{1}==1
busyRemove;
return
end
end
busyRemove;
img2=strrep(which('labs.m'),'labs.m','monkey.png');
img=imread(img2);
jimg = im2java(img);
frame = javax.swing.JFrame;
frame.setUndecorated(true);
icon = javax.swing.ImageIcon(jimg);
label = javax.swing.JLabel(icon);
set(label,'Text','BUSY')
% frame.setBackground(javaObject('java.awt.Color', 1, 1, 0,0))
F = java.awt.Font('Arial', java.awt.Font.BOLD, 16);
label.setFont(F);
frame.show;
set(label,'Foreground',[1 0 0])
frame.setBackground(java.awt.Color(0,0,0));
frame.getContentPane.add(label);
frame.getContentPane().setBackground(java.awt.Color(0,1,0,1));
frame.pack;
screenSize = get(0,'ScreenSize'); %# Get the screen size from the root object
frame.setSize(80,16);
frame.setLocation(screenSize(3)/2,screenSize(4)/2);
frame.show;
set(frame,'Tag','busy');
us=getappdata(0,'busy');
% s=get(0,'userdata');
us=[us;{frame}];
% set(0,'userdata',s);
setappdata(0,'busy',us);
% try
% us=getappdata(0,'busy');
% catch
% us=[];
% setappdata(0,'busy',us);
% us=getappdata(0,'busy');
% end
function busyRemove
if 1
try
us=getappdata(0,'busy');
catch
us=[];
setappdata(0,'busy',us);
us=getappdata(0,'busy');
end
% us=get(0,'userdata');
ni=[];
for i=1:length(us)
frame=us{i};
if ~isempty(strfind(class(frame),'JFrame'));
frame.dispose;
ni=[ni (i)];
end
end
if ~isempty(ni)
us{ni}=[];
setappdata(0,'busy',us);
end
end
% frame.dispose
% rmappdata(0,'busy')
|
github
|
philippboehmsturm/antx-master
|
showtable3.m
|
.m
|
antx-master/mritools/labs/showtable3.m
| 7,090 |
utf_8
|
59185186193dd8a258cb22cad1188626
|
function showtable3(pos,tab,varargin)
if 0
showtable3([0 0 1 1],tab,'fontsize',9,'fontweight','normal','backgroundcolor','w')
if ~exist('fontsize','var'); fontsize=8;end
if ~exist('color','var'); color='k';end
end
colbg=[1 1 1; 1 1 .8;];
for i=1:size(colbg,1);
colbghex(i,:) = reshape(dec2hex( round( colbg(i,:).*255))' ,[6 1])';
end
colbghead= reshape(dec2hex( round( [1 .7 .4] .*255))' ,[6 1])';
colfont= reshape(dec2hex( round( [0 0 1] .*255))' ,[6 1])';
for i=1:size(tab,2)
kn=char([tab(:,i); ]);
for j=1:size(tab(:,i),1)
dum= tab{j,i};
% labely{j,i}= [repmat(' ' ,[1 1+size(kn,2)-length(dum)]) dum ' ' ];
labely{j,i}= [repmat(' ' ,[1 size(kn,2)-length(dum)]) dum ' ' ];
end
end
dx=labely;
dz={};dz2={};
for i=1:size(dx,1)
dy='';dy2='';
for j=1:size(dx,2)
df=dx{i,j};
if i==1
df=[ '<b><u><font color="black" bgcolor="' colbghex(rem(j,2)+1,:) '">' df '</b>' '</font>' ];
else
if j~=2
colf= 'black';
bold='';
else
colf= colfont;
bold='<b>';
end
if rem(i-1,5)==0 | i==size(dx,1)
underline='<u>';
else
underline='';
end
df=[underline bold '<font color="' colf '" bgcolor="' colbghex(rem(j,2)+1,:) '">' df '</b>' '</font>' ];
end
% if rem(j,2)==0
% if j==2
% df=['<html>' vorl{2,2} df vorl{2,3}]
% end
dy =[dy df ];%HTML
dy2=[dy2 dx{i,j}];%RAW
end
dz{i,1} =dy;
dz2{i,1}=dy2;
end
dz=cellfun(@(dz) {['<html><pre>' dz '</pre>']} ,dz);
fontsize=9;
fig= findobj(0,'tag','tabelz2');
if ~isempty(fig);
posfig=get(fig,'position') ;
lb=findobj(fig,'tag','txt');
set(lb,'string',dz);
else
figure;set(gcf,'color','w', 'tag' ,'tabelz2' );
set(gcf,'units','normalized','menubar','none');
set(gcf,'position',[0.7090 0.7911 0.1743 0.1767]);
fig= findobj(0,'tag','tabelz2');
try
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jframe=get(fig,'javaframe');
icon=strrep(which('labs.m'),'labs.m','monkey.png');
jIcon=javax.swing.ImageIcon(icon);
jframe.setFigureIcon(jIcon);
end
% if ~isempty(fig);
% set(gcf,'position',posfig) ;
% end
if isempty(pos)
pos=[0 0 1 1];
end
% p = get(hx,'position');
h= uicontrol('tag','txt', 'units','normalized','Style', 'listbox', 'String', dz,...
'position',pos,'backgroundcolor','w',...
'foregroundcolor','k','fontsize',fontsize );
set(h,'FontName','courier new');
set(h,'Callback',@clicked)
if ~isempty(varargin)
set(h,varargin{:});
end
if 1
set(gcf,'units','characters');
pos=get(gcf,'position');
% pos(3)=pos(1)+length(dz2{1,:})-30
pos(3)=length(dz2{1,:})+80;
% pos(4)=size(dz2,1)+1
set(gcf,'position',pos);
set(gcf,'units','normalized');
pos=get(gcf,'position');
pos(1)=.1;
set(gcf,'position',pos);
end
%----------------------------------
% context
%----------------------------------
cmenu = uicontextmenu;
set(h,'UIContextMenu', cmenu);
item1 = uimenu(cmenu, 'Label','table to workspace ', 'Callback', {@gcontext, 1});%ws
item2 = uimenu(cmenu, 'Label','save FULL TABLE (TXT & EXCEL)', 'Callback', {@gcontext, 4});%save
item2 = uimenu(cmenu, 'Label','save table(only coordinates!!)', 'Callback', {@gcontext, 2});%save
item3 = uimenu(cmenu, 'Label','save as HTML file', 'Callback',{@gcontext, 3});%save
end
% set(gcf,'WindowScrollWheelFcn',{@gwheel,1});
% -----------------------------------------------------------
% x.scroll =findjobj(fig,'Class', 'UIScrollPane$1');%scroll
x.fontsize =fontsize;
x.evntModifier=0;
x.table =dz2;
x.tablec =tab;
set(fig,'userdata',x);
function clicked(hh,ss)
x=get(gcf,'userdata');
lb=findobj(gcf,'tag','txt');
val=get(lb,'value');
% cords=str2num(x.tablec{val,2});
columnMNI=find(cellfun('isempty',strfind(x.tablec(1,:),'xyzMNI'))==0);
cords=str2num(x.tablec{val,columnMNI});
% disp(cords);
try
hMIPax = findobj('tag','hMIPax');
spm_mip_ui('SetCoords',cords,hMIPax);
% showbrodmann;
fun2_activateResults;
end
%----------------------------------
% contextmenu
%----------------------------------
function gcontext(obj, event, mode)
x= get(gcf,'userdata');
if mode==1
label.table =x.table ;
label.tablec=x.tablec;
assignin('base','label' ,label);
disp('struct "label" assigned to workspace');
elseif mode==2
[fi pa]=uiputfile(pwd,'save table');
if fi~=0
pwrite2file(fullfile(pa,fi),x.table),
end
elseif mode==3
fun2_makeHTMLtable;
elseif mode==4
fun2_makeTable;
end
%----------------------------------
% mousewheel
%----------------------------------
% function gwheel(obj, event, mode)
%
% try
% x=get(gcf,'userdata');
% if x.evntModifier==0 %[scroll text]
% x=get(gcf,'userdata'); scroll=x.scroll;
% try
% % set(scroll,'value', get(scroll,'value') +event.VerticalScrollCount*25);
% % set(scroll,'value', get(scroll,'value') +round(event.VerticalScrollCount*20));
% class(get(scroll,'value') )
%
% % set(gcf,'units','characters')
% % pos=get(gcf,'position')
% step=round(event.VerticalScrollCount*40);
%
% set(scroll,'value', get(scroll,'value') +step);
%
% catch %after savibng Image
% x.scroll=findjobj(gcf,'Class', 'UIScrollPane$1');%scroll
% set(gcf,'userdata',x);
% end
% drawnow
% else %define fontsize with mouse wheel
% tx= findobj(gcf,'tag','txt');
%
% fs= get(tx,'fontsize');
% fs2=fs+event.VerticalScrollCount;
% if fs2>1
% set(tx,'fontsize', fs2) ;
% end
% x.evntModifier=0;
% set(gcf,'userdata',x);
% end
% end
%----------------------------------
% arrow keys
%----------------------------------
function fontsize(src,evnt)
x=get(gcf,'userdata');
if strcmp(evnt.Modifier,'control'); %[control]+mousewheel
x.evntModifier=1; %if [control]-key is pressed..
%code this for mousewheel-specifications
else
x.evntModifier=0;
tx= findobj(gcf,'tag','txt');
if strcmp(evnt.Key,'leftarrow')
set(tx,'fontsize', get(tx,'fontsize')-1) ;
elseif strcmp(evnt.Key, 'rightarrow')
set(tx,'fontsize', get(tx,'fontsize')+1) ;
end
end
set(gcf,'userdata',x);
|
github
|
philippboehmsturm/antx-master
|
vc2nc.m
|
.m
|
antx-master/mritools/labs/vc2nc.m
| 1,415 |
utf_8
|
8f5497fb37161f2aa7920c509ee01023
|
function nc=vc2nc(v2,hb)
% volume coords to normalized cords
% ----------------------------------
s_x=hb.hdr.hist.srow_x;
s_y=hb.hdr.hist.srow_y;
s_z=hb.hdr.hist.srow_z;
% s_x(find(s_x(1:3)==0))=1;
% s_y(find(s_y(1:3)==0))=1;
% s_z(find(s_z(1:3)==0))=1;
nc(:,1) = s_x(1).* v2(:,1) + s_x(2).* v2(:,2) + s_x(3).* v2(:,3) + s_x(4);
nc(:,2) = s_y(1).* v2(:,1) + s_y(2).* v2(:,2) + s_y(3).* v2(:,3) + s_y(4);
nc(:,3) = s_z(1).* v2(:,1) + s_z(2).* v2(:,2) + s_z(3).* v2(:,3) + s_z(4);
% %
% %
% % % The (x,y,z) coordinates are given by a general affine transformation
% % % of the (i,j,k) indexes:
% % %
% % % x = srow_x[0] * i + srow_x[1] * j + srow_x[2] * k + srow_x[3]
% % % y = srow_y[0] * i + srow_y[1] * j + srow_y[2] * k + srow_y[3]
% % % z = srow_z[0] * i + srow_z[1] * j + srow_z[2] * k + srow_z[3]
% % %
% % % The srow_* vectors are in the NIFTI_1 header. Note that no use is
% % % made of pixdim[] in this method.
% %
% %
% % srow_x=g.hdr.hist.srow_x
% % srow_y=g.hdr.hist.srow_y
% % srow_z=g.hdr.hist.srow_z
% %
% % % a=[27 30 40]
% % a=[78 112 50]
% % i=a(1);j=a(2);k=a(3);
% % disp([i j k])
% %
% % x = srow_x(1) * i + srow_x(2) * j + srow_x(3) * k + srow_x(4);
% % y = srow_y(1)* i + srow_y(2) * j + srow_y(3) * k + srow_y(4);
% % z = srow_z(1) * i + srow_z(2) * j + srow_z(3) * k + srow_z(4);
|
github
|
philippboehmsturm/antx-master
|
m_select3d.m
|
.m
|
antx-master/mritools/labs/m_select3d.m
| 11,219 |
utf_8
|
9813d3db9488481df18c76c0bb374a61
|
function [pout, vout, viout, facevout, faceiout] = m_select3d(obj)
%SELECT3D(H) Determines the selected point in 3-D data space.
% P = SELECT3D determines the point, P, in data space corresponding
% to the current selection position. P is a point on the first
% patch or surface face intersected along the selection ray. If no
% face is encountered along the selection ray, P returns empty.
%
% P = SELECT3D(H) constrains selection to graphics handle H and,
% if applicable, any of its children. H can be a figure, axes,
% patch, or surface object.
%
% [P V] = SELECT3D(...), V is the closest face or line vertex
% selected based on the figure's current object.
%
% [P V VI] = SELECT3D(...), VI is the index into the object's
% x,y,zdata properties corresponding to V, the closest face vertex
% selected.
%
% [P V VI FACEV] = SELECT3D(...), FACE is an array of vertices
% corresponding to the face polygon containing P and V.
%
% [P V VI FACEV FACEI] = SELECT3D(...), FACEI is the row index into
% the object's face array corresponding to FACE. For patch
% objects, the face array can be obtained by doing
% get(mypatch,'faces'). For surface objects, the face array
% can be obtained from the output of SURF2PATCH (see
% SURF2PATCH for more information).
%
% RESTRICTIONS:
% SELECT3D supports surface, patch, or line object primitives. For surface
% and patches, the algorithm assumes non-self-intersecting planar faces.
% For line objects, the algorithm always returns P as empty, and V will
% be the closest vertex relative to the selection point.
%
% Example:
%
% h = surf(peaks);
% zoom(10);
% disp('Click anywhere on the surface, then hit return')
% pause
% [p v vi face facei] = m_select3d;
% marker1 = line('xdata',p(1),'ydata',p(2),'zdata',p(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('xdata',v(1),'ydata',v(2),'zdata',v(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('erasemode','xor','xdata',face(1,:),'ydata',face(2,:),...
% 'zdata',face(3,:),'linewidth',10);
% disp(sprintf('\nYou clicked at\nX: %.2f\nY: %.2f\nZ: %.2f',p(1),p(2),p(3)'))
% disp(sprintf('\nThe nearest vertex is\nX: %.2f\nY: %.2f\nZ: %.2f',v(1),v(2),v(3)'))
%
% Version 1.3 11-11-04
% Copyright Joe Conti 2004
% Send comments to [email protected]
%
% See also GINPUT, GCO.
% Output variables
pout = [];
vout = [];
viout = [];
facevout = [];
faceiout = [];
% other variables
ERRMSG = 'Input argument must be a valid graphics handle';
isline = logical(0);
isperspective = logical(0);
% Parse input arguments
if nargin<1
obj = gco;
end
if isempty(obj) | ~ishandle(obj) | length(obj)~=1
error(ERRMSG);
end
% if obj is a figure
if strcmp(get(obj,'type'),'figure')
fig = obj;
ax = get(fig,'currentobject');
currobj = get(fig,'currentobject');
% bail out if not a child of the axes
if ~strcmp(get(get(currobj,'parent'),'type'),'axes')
return;
end
% if obj is an axes
elseif strcmp(get(obj,'type'),'axes')
ax = obj;
fig = get(ax,'parent');
currobj = get(fig,'currentobject');
currax = get(currobj,'parent');
% Bail out if current object is under an unspecified axes
if ~isequal(ax,currax)
return;
end
% if obj is child of axes
elseif strcmp(get(get(obj,'parent'),'type'),'axes')
currobj = obj;
ax = get(obj,'parent');
fig = get(ax,'parent');
% Bail out
else
return
end
axchild = currobj;
obj_type = get(axchild,'type');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Get vertex, face, and current point data %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cp = get(ax,'currentpoint')';
% If surface object
if strcmp(obj_type,'surface')
% Get surface face and vertices
fv = surf2patch(axchild);
vert = fv.vertices;
faces = fv.faces;
% If patch object
elseif strcmp(obj_type,'patch')
vert = get(axchild,'vertices');
faces = get(axchild,'faces');
% If line object
elseif strcmp(obj_type,'line')
xdata = get(axchild,'xdata');
ydata = get(axchild,'ydata');
zdata = get(axchild,'zdata');
vert = [xdata', ydata',zdata'];
faces = [];
isline = logical(1);
% Ignore all other objects
else
return;
end
% Add z if empty
if size(vert,2)==2
vert(:,3) = zeros(size(vert(:,2)));
if isline
zdata = vert(:,3);
end
end
% NaN and Inf check
nan_inf_test1 = isnan(faces) | isinf(faces);
nan_inf_test2 = isnan(vert) | isinf(vert);
if any(nan_inf_test1(:)) | any(nan_inf_test2(:))
% warning(sprintf('%s does not support NaNs or Infs in face/vertex data.',mfilename));
end
% For debugging
% if 0
% ax1 = getappdata(ax,'testselect3d');
% if isempty(ax1) | ~ishandle(ax1)
% fig = figure;
% ax1 = axes;
% axis(ax1,'equal');
% setappdata(ax,'testselect3d',ax1);
% end
% cla(ax1);
% patch('parent',ax1,'faces',faces,'vertices',xvert','facecolor','none','edgecolor','k');
% line('parent',ax1,'xdata',xcp(1,2),'ydata',xcp(2,2),'zdata',0,'marker','o','markerfacecolor','r','erasemode','xor');
% end
% Transform vertices from data space to pixel space
xvert = local_Data2PixelTransform(ax,vert)';
xcp = local_Data2PixelTransform(ax,cp')';
% Translate vertices so that the selection point is at the origin.
xvert(1,:) = xvert(1,:) - xcp(1,2);
xvert(2,:) = xvert(2,:) - xcp(2,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% simple algorithm (almost naive algorithm!) for line objects %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isline
% Ignoring line width and marker attributes, find closest
% vertex in 2-D view space.
d = xvert(1,:).*xvert(1,:) + xvert(2,:).*xvert(2,:);
[val i] = min(d);
i = i(1); % enforce only one output
% Assign output
vout = [ xdata(i) ydata(i) zdata(i)];
viout = i;
return % Bail out early
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Perform 2-D crossing test (Jordan Curve Theorem) %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Find all vertices that have y components less than zero
vert_with_negative_y = zeros(size(faces));
face_y_vert = xvert(2,faces);
ind_vert_with_negative_y = find(face_y_vert<0);
vert_with_negative_y(ind_vert_with_negative_y) = logical(1);
% Find all the line segments that span the x axis
is_line_segment_spanning_x = abs(diff([vert_with_negative_y, vert_with_negative_y(:,1)],1,2));
% Find all the faces that have line segments that span the x axis
ind_is_face_spanning_x = find(any(is_line_segment_spanning_x,2));
% Ignore data that doesn't span the x axis
candidate_faces = faces(ind_is_face_spanning_x,:);
vert_with_negative_y = vert_with_negative_y(ind_is_face_spanning_x,:);
is_line_segment_spanning_x = is_line_segment_spanning_x(ind_is_face_spanning_x,:);
% Create line segment arrays
pt1 = candidate_faces;
pt2 = [candidate_faces(:,2:end), candidate_faces(:,1)];
% Point 1
x1 = reshape(xvert(1,pt1),size(pt1));
y1 = reshape(xvert(2,pt1),size(pt1));
% Point 2
x2 = reshape(xvert(1,pt2),size(pt2));
y2 = reshape(xvert(2,pt2),size(pt2));
% Cross product of vector to origin with line segment
cross_product_test = -x1.*(y2-y1) > -y1.*(x2-x1);
% Find all line segments that cross the positive x axis
crossing_test = (cross_product_test==vert_with_negative_y) & is_line_segment_spanning_x;
% If the number of line segments is odd, then we intersected the polygon
s = sum(crossing_test,2);
s = mod(s,2);
ind_intersection_test = find(s~=0);
% Bail out early if no faces were hit
if isempty(ind_intersection_test)
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Plane/ray intersection test %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Perform plane/ray intersection with the faces that passed
% the polygon intersection tests. Grab the only the first
% three vertices since that is all we need to define a plane).
% assuming planar polygons.
candidate_faces = candidate_faces(ind_intersection_test,1:3);
candidate_faces = reshape(candidate_faces',1,prod(size(candidate_faces)));
vert = vert';
candidate_facev = vert(:,candidate_faces);
candidate_facev = reshape(candidate_facev,3,3,length(ind_intersection_test));
% Get three contiguous vertices along polygon
v1 = squeeze(candidate_facev(:,1,:));
v2 = squeeze(candidate_facev(:,2,:));
v3 = squeeze(candidate_facev(:,3,:));
% Get normal to face plane
vec1 = [v2-v1];
vec2 = [v3-v2];
crs = cross(vec1,vec2);
mag = sqrt(sum(crs.*crs));
nplane(1,:) = crs(1,:)./mag;
nplane(2,:) = crs(2,:)./mag;
nplane(3,:) = crs(3,:)./mag;
% Compute intersection between plane and ray
cp1 = cp(:,1);
cp2 = cp(:,2);
d = cp2-cp1;
dp = dot(-nplane,v1);
%A = dot(nplane,d);
A(1,:) = nplane(1,:).*d(1);
A(2,:) = nplane(2,:).*d(2);
A(3,:) = nplane(3,:).*d(3);
A = sum(A,1);
%B = dot(nplane,pt1)
B(1,:) = nplane(1,:).*cp1(1);
B(2,:) = nplane(2,:).*cp1(2);
B(3,:) = nplane(3,:).*cp1(3);
B = sum(B,1);
% Distance to intersection point
t = (-dp-B)./A;
% Find "best" distance (smallest)
[tbest ind_best] = min(t);
% Determine intersection point
pout = cp1 + tbest .* d;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Assign additional output variables %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout>1
% Get face index and vertices
faceiout = ind_is_face_spanning_x(ind_intersection_test(ind_best));
facevout = vert(:,faces(faceiout,:));
% Determine index of closest face vertex intersected
facexv = xvert(:,faces(faceiout,:));
dist = sqrt(facexv(1,:).*facexv(1,:) + facexv(2,:).*facexv(2,:));
min_dist = min(dist);
min_index = find(dist==min_dist);
% Get closest vertex index and vertex
viout = faces(faceiout,min_index);
vout = vert(:,viout);
end
%--------------------------------------------------------%
function [p] = local_Data2PixelTransform(ax,vert)
% Transform vertices from data space to pixel space.
% Get needed transforms
xform = get(ax,'x_RenderTransform');
offset = get(ax,'x_RenderOffset');
scale = get(ax,'x_RenderScale');
% Equivalent: nvert = vert/scale - offset;
nvert(:,1) = vert(:,1)./scale(1) - offset(1);
nvert(:,2) = vert(:,2)./scale(2) - offset(2);
nvert(:,3) = vert(:,3)./scale(3) - offset(3);
% Equivalent xvert = xform*xvert;
w = xform(4,1) * nvert(:,1) + xform(4,2) * nvert(:,2) + xform(4,3) * nvert(:,3) + xform(4,4);
xvert(:,1) = xform(1,1) * nvert(:,1) + xform(1,2) * nvert(:,2) + xform(1,3) * nvert(:,3) + xform(1,4);
xvert(:,2) = xform(2,1) * nvert(:,1) + xform(2,2) * nvert(:,2) + xform(2,3) * nvert(:,3) + xform(2,4);
% w may be 0 for perspective plots
ind = find(w==0);
w(ind) = 1; % avoid divide by zero warning
xvert(ind,:) = 0; % set pixel to 0
p(:,1) = xvert(:,1) ./ w;
p(:,2) = xvert(:,2) ./ w;
|
github
|
philippboehmsturm/antx-master
|
pmakemask.m
|
.m
|
antx-master/mritools/labs/pmakemask.m
| 4,079 |
utf_8
|
27116389c072e8e0718ac7a51e8904fd
|
function pmakemask(nameout,radius)
% pmakemask('__muell',10)
% make mask based on current position of SPM's coordinate
% nameout: outputfilename
% radius : radius of VOI [mm]
% example: pmakemask('__muell',10) ;%current MIP-poistion with radius 10mm
% ===========================================================================
if 0
pmakemask('__muell',10)
end
% ===========================================================================
c =extractVolume(radius);
data3=makevol( ones(length(c.maskidx),1), c.XYZ(:,c.maskidx), c.hdr);
pwritevol2vol(nameout,(data3),c.hdr, ['nvox=' num2str(length(c.maskidx))]);
function c=extractVolume(radius)
% spm_vol('beta_0001.hdr')
file='beta_0001.hdr';
hdr=spm_vol(file);
[M XYZmm]=spm_read_vols(hdr);
[x y z] = ind2sub(size(M),1:length(M(:)));
XYZ=[x;y;z];
if exist('operation')
% XYZ =XYZ(:,M(:)>0);
% XYZmm=XYZmm(:,M(:)>0);
tg=['XYZ =XYZ(:,M(:)' operation ');' ];eval(tg);
tg=['XYZmm =XYZmm(:,M(:)' operation ');' ];eval(tg);
end
ts = spm_sample_vol(hdr,XYZ(1,:),XYZ(2,:),XYZ(3,:),0);
c.ts =ts;
c.hdr =hdr;
c.vol =M;
c.XYZ =XYZ;
c.XYZmm =XYZmm;
%% get current coordinate
hReg=evalin('base','hReg');
u=get(hReg,'UserData');% , u.xyz
xyz=round(u.xyz);
if size(xyz,1)==1; xyz=xyz'; end
% xyz=sv.XYZ
% tic
XYZ=XYZmm;
idx=nan(size(xyz,2),1);
XYZ=single(XYZ);
xyz=single(xyz);
for i=1:size(xyz,2)
ab= repmat(xyz(:,i)',[ size(XYZ,2) 1]);
sums= sum( (XYZ'-ab).^2 ,2);
ix=min(find(sums==min(sums)));
% [uxyz ix]=intersect(XYZ',xyz(:,i)','rows');
% [uxyz ix]=ismember(XYZ',xyz(:,i)','rows'); ix=find(ix==1);
if ~isempty(ix)
idx(i)=ix;
end
end
idx=idx(1);
% radius=10
r = radius.^2;
O = ones(1,length(c.XYZ));% searchlite sphereSize
s = (sum((c.XYZmm-c.XYZmm(:,idx)*O).^2) < r);%SPHEREMASK [1x NvoxSphere; bool]
% j = find(sum((XYZmm - xY.xyz*Q).^2) <= xY.spec^2); %%see spm_regions & spm_ROI
disp(['MNI-coordinate: [ ' num2str( xyz(:)' ) ']']);
disp(['Nvoxel in mask: ' num2str(sum(s)) ]);
c.mask=single(s);
c.maskcenteridx=idx;
c.maskidx=find(c.mask==1);
% 'a'
% ===========================================================================
function data3=makevol( data, XYZ, strct,voltype)
% function data3=makevol( data, XYZ, strct)
% put data into 3d volume at coordinates XYZ
% voltype: type of volume [0 or NAN]
% example
% vol =makevol( ACC.dat, ACC.XYZ, ACC.hdr);%-->put data into '0'-matrix
% vol =makevol( ACC.dat, ACC.XYZ, ACC.hdr,0);%-->put data into '0'-matrix
% vol =makevol( ACC.dat, ACC.XYZ, ACC.hdr,nan);%-->put data into 'nan'-matrix
if size(XYZ,1)~=3 ; XYZ=XYZ'; end
if exist('voltype')==0
voltype=0;
end
% XYZ =xw.XYZ
% dim =strct.dim
data3=zeros(strct.dim)*voltype;
for kv=1:length(data)
data3(XYZ(1,kv),XYZ(2,kv),XYZ(3,kv))=data(kv);
end
% ===========================================================================
function pwritevol2vol(name,dat3d,strct, description)
% function pwritevol2vol(name,dat3d,strct, description)
% write 3d volume to majo-IMG/HDR
if exist('description')==0; description=''; end
name=regexprep(name,'.img$','');
[pathi nameshort aaa]=fileparts(name);
if isempty(pathi)
pathi=pwd;
end
% fullname=fullfile(pathi,[nameshort '.img']);
fullname=fullfile(pathi,[nameshort '.nii']);
% strct=spm_vol(templatefile);
% im=zeros(strct.dim);
% for kv=1:length(data)
% im(XYZ(1,kv),XYZ(2,kv),XYZ(3,kv))=data(kv);
% end
oim = struct('fname',fullname ,...
'dim', {strct.dim},...
'pinfo', {[1 0 0]'},...
'mat', {strct.mat},...
'dt',[2 0],...%BINARY
'descrip', {[description ' map']});
% 'dt', {[4 spm_platform('bigend')]},...% 'dt', {[16 spm_platform('bigend')]},...
% hdr.dt(1)=2;%save binary data as bytes: uint8=2; int16=4; int32=8; float32=16; float64=64
oim=spm_create_vol(oim);
oim=spm_write_vol(oim,double(dat3d));
|
github
|
philippboehmsturm/antx-master
|
fun2_activateResults.m
|
.m
|
antx-master/mritools/labs/fun2_activateResults.m
| 802 |
utf_8
|
f987e9dbe2372ef2d74d4d4a730a630e
|
function fun2_activateResults
% 'fun2_activateResults: function used during shift MIPcursor'
drawnow;
pause(.1);
fig3=findobj(0,'Tag','Graphics');
ax=findobj(fig3,'Tag','hMIPax');
xyz=spm_mip_ui('GetCoords',ax);
[labelx header labelcell]=pick_wrapper(xyz(:)', 'Noshow');%
% cprintf([1 0 1],'fun2_activateResults');
% showtable2([0 0 1 1],[header(2:end);labelx(2:end)]','fontsize',8);
% xSPM=evalin('base','xSPM');
fig2=findobj(0,'Tag','Interactive');
str=get(sort(findobj(fig2,'style','text')),'string');
value= char(str( find(strcmp(str,'statistic'))+1 ));
tabx=[
[header(2) '#[1 0.1608 0] Value' header(3:end)];
[labelx(2) [ '#[1 0.1608 0]' value ] labelx(3:end)];
]';
showtable2([0 0 1 1],tabx,'fontsize',8);
|
github
|
philippboehmsturm/antx-master
|
pwritevol2vol.m
|
.m
|
antx-master/mritools/labs/pwritevol2vol.m
| 852 |
utf_8
|
f780ac0088af85ea5244122ccf0abd12
|
function pwritevol2vol(name,dat3d,strct, description)
% function pwritevol2vol(name,dat3d,strct, description)
% write 3d volume to majo-IMG/HDR
if exist('description')==0; description=''; end
name=regexprep(name,'.img$','');
[pathi nameshort aaa]=fileparts(name);
if isempty(pathi)
pathi=pwd;
end
% fullname=fullfile(pathi,[nameshort '.img']);
fullname=fullfile(pathi,[nameshort '.nii']);
% strct=spm_vol(templatefile);
% im=zeros(strct.dim);
% for kv=1:length(data)
% im(XYZ(1,kv),XYZ(2,kv),XYZ(3,kv))=data(kv);
% end
oim = struct('fname',fullname ,...
'dim', {strct.dim},...
'dt', {[16 spm_platform('bigend')]},...
'pinfo', {[1 0 0]'},...
'mat', {strct.mat},...
'descrip', {[description ' map']});
oim=spm_create_vol(oim);
oim=spm_write_vol(oim,double(dat3d));
|
github
|
philippboehmsturm/antx-master
|
batab.m
|
.m
|
antx-master/mritools/labs/batab.m
| 1,093 |
utf_8
|
195ad1cdae29a80928bd58947226df6d
|
function varargout=batab(varargin) %show BAtable
% use with SPM: batab(1) from cmd-line
busy;
if varargin{1}==1%whole brain
xSPM= evalin('base','xSPM');
hReg= evalin('base','hReg');
TabDat = spm_list('List',xSPM,hReg);
assignin('base','TabDat',TabDat);
elseif varargin{1}==2%curent cluster
xSPM= evalin('base','xSPM');
hReg= evalin('base','hReg');
TabDat = spm_list('ListCluster',xSPM,hReg);
assignin('base','TabDat',TabDat);
end
fig=findobj(0,'Tag','Graphics');
axtab=get(findobj(fig,'string','mm mm mm'),'parent');%table
hl=sort(findobj(axtab,'Tag','ListXYZ')) ;%mmText mm mm mm
% return
if isempty(axtab)
disp('there is no table');
return
end
cords=str2num(char([get(hl,'string')]));
[labelx header labelcell]=pick_wrapper(cords, 'Noshow');%
showtable3([0 0 1 1],[header;labelx],'fontsize',8);
zz.cords =cords;
zz.labelx=labelx;
zz.header=header;
zz.labelcell=labelcell;
varargout{1}=zz;
% TabDat = spm_list('List',xSPM,hReg);
% TabDat = spm_list('ListCluster',xSPM,hReg);
busy(1);
|
github
|
philippboehmsturm/antx-master
|
slice2mm.m
|
.m
|
antx-master/mritools/methods/slice2mm.m
| 1,355 |
utf_8
|
37d73cbd53149366b185b95bff9647bf
|
%% convert slice to mm (get mm of slices)
% function out=slice2mm(fi, slices, dimx);
%% IN
% fi: fp-path of volume or spm-volume-header
% slices: array of slice-numbers
% dimx: which dimention 1,2,3 or 'allen' (which is dimx=2) or 'native' (which is dimx==3) (space)
%% OUT : 2d-array [slices x mm]
%% example
% native-space or allen-space
% slice2mm('O:\harms1\harms3_lesionfill\dat\s20150908_FK_C1M02_1_3_1\hemi.nii', [1:32], 'native')
% slice2mm('O:\harms1\harms3_lesionfill\dat\s20150908_FK_C1M02_1_3_1\x_hemi.nii', [1:212], 'allen')
function out=slice2mm(fi, slices, dimx);
if isstruct(fi)
ha=fi;
fi=ha.fname;
else
ha=rgetnii(fi);
end
q=slices(:)';
% q=[60,73,86,99,112,125,138]; %sliceIDs
% q2=[ zeros(length(q),1) zeros(length(q),1) q'];
if 0
q2=[zeros(length(q),3)]; %matrix
idx=2;
q2(:,idx)=q;
[a b]=voxcalc([q2 ],ha,'idx2mm');
mm=a(:,idx)';
out=[q(:) mm(:) ];
end
% disp(out)
[bb vx] = world_bb(fi);
if ischar(dimx)
if strcmp(dimx,'allen')
dirs=2;
elseif strcmp(dimx,'native')
dirs=3;
end
else
dirs=dimx;
end
%%
mm=linspace(bb(1,dirs),bb(2,dirs), ha.dim(dirs))';
out=[ q(:) mm(q(:)) ];
%
% out([1 end],:)
%
% ha.dim
% bb
% median(diff(mm))
% vx
% mm([1 end],:)
|
github
|
philippboehmsturm/antx-master
|
makeMaskT2.m
|
.m
|
antx-master/mritools/methods/makeMaskT2.m
| 701 |
utf_8
|
21be7a2bd6867d4729f11ef7c66a66b9
|
%make mask from t2 image
% makeMaskT2(file,fileout, thresh)
% example
% file='O:\harms1\harms3_lesionfill\templates\AVGT.nii'
% fileout='O:\harms1\harms3_lesionfill\templates\allemask.nii'
% thresh='>50'; %string with operator and number ,e.g. '>0'
% makeMaskT2(file,fileout, thresh)
function makeMaskT2(file,fileout, thresh)
if 0
file='O:\harms1\harms3_lesionfill\templates\AVGT.nii'
fileout='O:\harms1\harms3_lesionfill\templates\allemask.nii'
thresh='>50';
end
[ha a ]=rgetnii(file);
str=['b=a' thresh ';'];
eval(str);
d=b.*nan;
for i=1:size(b,2)
c=squeeze(b(:,i,:));
c=imfill(c,'holes');
d(:,i,:)=c;
end
rsavenii(fileout,ha,d,[2 0]);
|
github
|
philippboehmsturm/antx-master
|
fileparts2.m
|
.m
|
antx-master/mritools/methods/fileparts2.m
| 305 |
utf_8
|
9f58b31e1b0df0639f018820177e1a9f
|
% fileparts2: for multiple paths (cell)
% function [pathstr, name, ext] = fileparts2(file)
function [pathstr, name, ext] = fileparts2(fi)
if ~iscell(fi); fi=cellstr(fi); end
[pathstr name ext]=deal({});
for i=1:length(fi)
[pathstr{i,1} name{i,1} ext{i,1}]=fileparts(fi{i});
end
|
github
|
philippboehmsturm/antx-master
|
makeMaskT3m.m
|
.m
|
antx-master/mritools/methods/makeMaskT3m.m
| 782 |
utf_8
|
2181a7bdb9633683ef4a9e7ccd084535
|
%make mask from t2 image
% makeMaskT2(file,fileout, thresh)
% example
% file='O:\harms1\harms3_lesionfill\templates\AVGT.nii'
% fileout='O:\harms1\harms3_lesionfill\templates\allemask.nii'
% thresh='>50'; %string with operator and number ,e.g. '>0'
% makeMaskT2(file,fileout, thresh)
function makeMaskT3(file,fileout, thresh)
if 0
file='O:\harms1\harms3_lesionfill\templates\AVGT.nii'
fileout='O:\harms1\harms3_lesionfill\templates\allemask.nii'
thresh='>50';
end
[ha a xyz xyzind]=rgetnii(file);
str=['b=a' thresh ';'];
eval(str);
d=b.*nan;
for i=1:size(b,2)
c=squeeze(b(:,i,:));
c=imfill(c,'holes');
d(:,i,:)=c;
end
e=d;
for i=1:size(e,3)
e(:,:,i)=medfilt2(e(:,:,i));
end
rsavenii(fileout,ha,e,[2 0]);
|
github
|
philippboehmsturm/antx-master
|
explorerpreselect.m
|
.m
|
antx-master/mritools/methods/explorerpreselect.m
| 109 |
utf_8
|
6abb83b2bfe58926f850ff85939548a0
|
%% preselect file in explorer
function explorerpreselect(fi)
system(['explorer.exe /select,"' fi '"']);
|
github
|
philippboehmsturm/antx-master
|
bruker2nifti.m
|
.m
|
antx-master/mritools/methods/bruker2nifti.m
| 8,396 |
utf_8
|
e75dca28e0fa06efd4296d9b329dfea0
|
function tagout=bruker2nifti(pathin, pathout)
%
% s=input('use GUI or ')
% [files,dirs] = spm_select('FPListRec',a,'2dseq')
%% gui ..get 2dseq
if ~exist('pathin') || isempty(pathin); pathin=pwd; end
disp('====================================================');
disp('*** find recursively all "2dseq" in subfolders ***');
disp('[1]in GUI select upper path were data are stored in subfolders');
disp('[2]in GUI pres [rec] button to recursively find all 2dseq-files in all subfolders');
disp('[3]in GUI pres [done]');
[files,dirs] = spm_select(inf,'2dseq',...
'select [2dseq], press [rec] to recursively find all [2dseq]files in subfolder',...
'',pathin);
if isempty(files); return; end ;%ESCAPE
files=cellstr(files);
%% gui ..path2store NIFT
if ~exist('pathout') || isempty(pathout)
% [pa fi]=fileparts(pathin)
pathout = uigetdir(pathin,'Select the directory to store NIFTI data');
end
if exist(pathout,'file')~=7
mkdir(pathout);
end
%% select data via check size
for i=1:size(files,1)
k(i)=dir(files{i});
end
mbytes=cell2mat({k(:).bytes}')/1e6;
prompt = {'select method [rare,flash,fisp], if empty all sequences processed'; 'select data above x-Mbites, otherwise [empty] using all data'};
dlg_title = 'Input for peaks function';
num_lines = 1;
def = {'rare' , num2str([0])};
answer = inputdlg(prompt,dlg_title,num_lines,def);
sequence= answer{1};
mbthresh = answer{2};
%% byte-issue
if isempty(mbthresh); mbthresh='0'; end
mbthresh=str2num(mbthresh);
isel= find(mbytes>=mbthresh );
sprintf(' # %d files above %2.2fMB found',length(isel) ,mbthresh);
files=files(isel);
% filesbk=files;
%% sequence-issue
%check: <Bruker:RARE>
tagout={''};
if ~isempty(sequence)
usedfiles =zeros(length(files),1);
usedfileSeq=cell(length(files),1);
disp('*** check Sequence ***');
for i=1:length(files)
[pa fi]=fileparts(files{i});
pa2=pa(1:strfind(pa,'pdata')-1);
methodfile=fullfile(pa2,'method');
%% if methodfile is not found ... adaption needed...
if exist(methodfile,'file')~=2
keyboard
end
pause(.1); %readerrorstuff :)
methods=readBrukerParamFile(methodfile);
usedfileSeq{i,1}=methods.Method;
% if strcmp(methods.Method, upper(sequence) )==1
if ~isempty(regexpi(methods.Method,sequence))
usedfiles(i)=1;
end
tag= sprintf('%d\\%d-%s:\t%s >>[used]%d',i,length(files), methodfile,methods.Method,usedfiles(i)) ;
disp(tag);
tagout{i,1}=tag;
end
files= files(find(usedfiles));
tagout=[{'*** USED FILES ***'} ;tagout(find(usedfiles))];
end
% keyboard
tagout=[tagout; {['#MbSizeTresh: ' num2str(mbthresh) ]} ];
tagout=[tagout; {['#Sequence: ' sequence ]} ];
tagout=[tagout; {['#Nfolders: ' num2str(length(files)) ]} ];
if pathout==0 ; return; end
%% loop trhoug all 2dseq-files
h = waitbar(0,'Please wait...');
for i=1:size(files,1)
[pa fi]=fileparts(files{i});
waitbar(i/size(files,1),h,[' convert2nifti: ' num2str(i) '/' num2str(size(files,1)) ]);
% PathName_2dseq=fullfile(PathName_pvstudy,nameFolds{i},'pdata',nameSubfolds{j});
% path_to_2dseq=fullfile(PathName_2dseq,'2dseq');
% open 2dseq
path_to_2dseq = files{i} ;%fullfile(PathName_2dseq,'2dseq');
Visu = readBrukerParamFile(fullfile(pa,'visu_pars'));
image_2dseq = readBruker2dseq(path_to_2dseq,Visu);
image_2dseq=squeeze(image_2dseq);% remove unnecessary dimensions
%====Generate NIFTI files and store them in directory==========
% Extract header info for NIFTI storage
voxelsize_2dseq=[Visu.VisuCoreExtent./Visu.VisuCoreSize Visu.VisuCoreFrameThickness];
voxelsize_2dseq=voxelsize_2dseq(1:3);
%% ORIGIN : to check
% pos= Visu.VisuCorePosition;
% origin=[mean(pos(:,1:2)) [(min(pos(:,3))) ] ];
% Convert the extracted image to Nifti and store
% image_2dseq_nii=make_nii(image_2dseq, voxelsize_2dseq);
% image_2dseq_nii=make_nii(image_2dseq, voxelsize_2dseq,origin);
errorbool=[0 0 0 0];
try
SubjectId=Visu.VisuSubjectId ;
catch
SubjectId='x'; errorbool(1)=1;
end
try
StudyNumber=num2str(Visu.VisuStudyNumber) ;
catch
StudyNumber='x'; errorbool(2)=1;
end
try
ExperimentNumber=num2str(Visu.VisuExperimentNumber) ;
catch
ExperimentNumber='x' ; errorbool(3)=1;
end
try
ProcessingNumber=num2str(Visu.VisuProcessingNumber) ;
catch
ProcessingNumber='x' ; errorbool(4)=1;
end
numID= files{1}(max(strfind(pa,filesep))+1:strfind(files{1},'2dseq')-2 );
FileName_2dseq_base=[SubjectId '_' StudyNumber '_' ...
ExperimentNumber '_' ProcessingNumber '_' numID ];
% % Filenames
% FileName_2dseq_base=[Visu.VisuSubjectId '_' num2str(Visu.VisuStudyNumber)...
% '_' num2str(Visu.VisuExperimentNumber) '_' num2str(Visu.VisuProcessingNumber)];
%
filename=['s' FileName_2dseq_base];
paout2=fullfile(pathout,filename);%% make DIR
mkdir(paout2);
filename2=fullfile(paout2,[filename '.nii']);
%FileName_2dseq=fullfile(pathout,[FileName_2dseq_base '.nii']);
% Store
display(['saving ' filename2]);
% save_nii(image_2dseq_nii,FileName_2dseq);
% save_nii(image_2dseq_nii,'dum');
%%===========SPM
dim=size(image_2dseq);
mat=diag([voxelsize_2dseq 1],0);
mat(1:3,4)=-diag(mat(1:3,1:3)).*round(dim/2)' ;%origin set to centerImage
hh = struct('fname',filename2 ,...
'dim', {dim},...
'dt', {[64 spm_platform('bigend')]},...
'pinfo', {[1 0 0]'},...
'mat', {mat},...
'descrip', {['x']});
%=================
hh=spm_create_vol(hh);
hh=spm_write_vol(hh, (image_2dseq));
end%i
close(h)
% FORMAT function [Outdata,voxdim, Origin] = rest_readfile(filename)
% filename - Analyze file (*.{hdr, img, nii})
% Outdata - data file.
% VoxDim - the size of the voxel.
% Header - It's decided by the format of data file:
% for ANALYZE 7.5 - Header.Origin - the origin of the image;
% for NIFTI - Head.fname - the filename of the image.
% Head.dim - the x, y and z dimensions of the volume
% Head.dt - A 1x2 array. First element is datatype (see spm_type).
% The second is 1 or 0 depending on the endian-ness.
% Head.mat - a 4x4 affine transformation matrix mapping from
% voxel coordinates to real world coordinates.
% Head.pinfo - plane info for each plane of the volume.
% Head.pinfo(1,:) - scale for each plane
% Head.pinfo(2,:) - offset for each plane
% The true voxel intensities of the jth image are given
% by: val*Head.pinfo(1,j) + Head.pinfo(2,j)
% Head.pinfo(3,:) - offset into image (in bytes).
% If the size of pinfo is 3x1, then the volume is assumed
% to be contiguous and each plane has the same scalefactor
% and offset.
% Head.private - a structure containing complete information in the
% header
% Header.Origin - the origin of the image;
|
github
|
philippboehmsturm/antx-master
|
rimg2nii.m
|
.m
|
antx-master/mritools/methods/rimg2nii.m
| 2,359 |
utf_8
|
dc8f91efbfd0f1f2dd217a74210cf2be
|
function fiout=rimg2nii(in,gui )
%% convert analyze2niffti with empty(GUI) or path/FPfile-INPUT
% fiout=rimg2nii(in,gui )
%% INPUTS
% in: empty [],path <string> or fullpathfilename of imag(s) <string/cell>
% gui: <0|1> with GUI for selection of files (empty: open GUI)
%
%% OUTPUTS
% fiout: cell with FPlist of nifitFiles
%% no path defined
% rimg2nii : GUI for path, GUI for imgs
% rimg2nii([],1) GUI for path, GUI for imgs
% rimg2nii([],0) GUI for path, allIMG in path
%% with defined path
% rimg2nii(pwd,0) ; pathis defined, allIMG in path
% rimg2nii(pwd,1) ; pathis defined, GUI for imgs
%% with fullpath-files defined (as string or cell) !! use cell for multiple files!!
% rimg2nii('o:\harms1\harmsStaircaseTrial\lesionMasks\analyze\20150505SM09_lesion_total_mask.img')
% rimg2nii({'o:\harms1\harmsStaircaseTrial\lesionMasks\analyze\20150505SM09_lesion_total_mask.img'})
%
% z={ 'o:\harms1\harmsStaircaseTrial\lesionMasks\analyze\20150505SM09_lesion_total_mask.img'
% 'o:\harms1\harmsStaircaseTrial\lesionMasks\analyze\20150507Sm25_lesion_total_mask.im'}
% rimg2nii(z) ;
%% output
% e=rimg2nii(pwd,0); %all files in pwd converted...output is a cell with all nifftiFiles
% in=pwd
% gui=0
% in=[]
%% check INPUTS
if exist('in') ==0; in=[]; end
if exist('gui')==0; gui=1; end
%% GUI/inputs
if isempty(in)
in= uigetdir(pwd,'selectFolder with img/hdr');
if in==0; return; end
end
t=[];
if iscell(in) %in
t=in;
else %one file or dir
if exist(in)==7 %is a DIRECTORY
if gui==0
[t,sts] = spm_select('FPList',in,'.*.img$');
t=cellstr(t);
else %USERSELECTION
[t,sts] = spm_select(inf,'any','select analyzeData','',in,'.*.img$',1);
t=cellstr(t);
end
else
t=cellstr(in);
end
end
if isempty(t); return; end
%% conversion
% return
t=t(:);
fiout=[];
for i=1:length(t)
file=t{i};
[ha a]=rgetnii(file );
[pa fi ext]=fileparts(file);
fileout=fullfile(pa,[fi,'.nii']);
fiout{i,1}=rsavenii(fileout,ha,a);
end
% if isempty(in)
% pa= uigetdir(pwd,'selectFolder with img/hdr')
% [t,sts] = spm_select(inf,'any','select analyzeData','',pa,'.*.img',1)
% t=cellstr(t);
% else
% t=in;
% end
|
github
|
philippboehmsturm/antx-master
|
existn.m
|
.m
|
antx-master/mritools/methods/existn.m
| 605 |
utf_8
|
9b9c7d7b122cf84063d957e54566ad2d
|
%% exist-function for multiple files/objects --if input is cell-type
%% function b=existn(ce,varargin)
% output: vector with flags as in exist.m
%% example
% q={ 'O:\data\karina\dat\s2014109_02sr_1_x_x\JD.nii'
% 'O:\data\karina\dat\s20141009_03sr_1_x_x\JD.nii'
% 'O:\data\karina\dat\s20141009_05sr_1_x_x\JD.nii'}
% b=existn(q);
function b=existn(ce,varargin)
if ischar(ce); ce=cellstr(ce); end
if nargin==1
for i=1:length(ce)
b(i,1) =exist(ce{i});
end
elseif nargin==2
for i=1:length(ce)
b(i,1) =exist(ce{i},varargin{1});
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_orthviews2.m
|
.m
|
antx-master/mritools/displaykey/spm_orthviews2.m
| 62,002 |
utf_8
|
b294d80d56447081c7b5e8b06fc6c119
|
function varargout = spm_orthviews(action,varargin)
% Display Orthogonal Views of a Normalized Image
% FORMAT H = spm_orthviews('Image',filename[,position])
% filename - name of image to display
% area - position of image
% - area(1) - position x
% - area(2) - position y
% - area(3) - size x
% - area(4) - size y
% H - handle for ortho sections
% FORMAT spm_orthviews('BB',bb)
% bb - bounding box
% [loX loY loZ
% hiX hiY hiZ]
%
% FORMAT spm_orthviews('Redraw')
% Redraws the images
%
% FORMAT spm_orthviews('Reposition',centre)
% centre - X, Y & Z coordinates of centre voxel
%
% FORMAT spm_orthviews('Space'[,handle])
% handle - the view to define the space by
% with no arguments - puts things into mm space
%
% FORMAT spm_orthviews('MaxBB')
% sets the bounding box big enough display the whole of all images
%
% FORMAT spm_orthviews('Resolution',res)
% res - resolution (mm)
%
% FORMAT spm_orthviews('Delete', handle)
% handle - image number to delete
%
% FORMAT spm_orthviews('Reset')
% clears the orthogonal views
%
% FORMAT spm_orthviews('Pos')
% returns the co-ordinate of the crosshairs in millimetres in the
% standard space.
%
% FORMAT spm_orthviews('Pos', i)
% returns the voxel co-ordinate of the crosshairs in the image in the
% ith orthogonal section.
%
% FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs')
% disables the cross-hairs on the display.
%
% FORMAT spm_orthviews('Xhairs','on')
% enables the cross-hairs.
%
% FORMAT spm_orthviews('Interp',hld)
% sets the hold value to hld (see spm_slice_vol).
%
% FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations (currently in millimeters)
% Z - blob voxel intensities
% mat - matrix from millimeters to voxels of blob.
% This method only adds one set of blobs, and displays them using a
% split colour table.
%
% spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations (currently in millimeters)
% Z - blob voxel intensities
% mat - matrix from millimeters to voxels of blob.
% colour - the 3 vector containing the colour that the blobs should be
% Several sets of blobs can be added in this way, and it uses full colour.
% Although it may not be particularly attractive on the screen, the colour
% blobs print well.
%
% spm_orthviews('Register',hReg)
% See spm_XYZreg for more information.
%
% FORMAT spm_orthviews('RemoveBlobs',handle)
% Removes all blobs from the image specified by the handle(s).
%
% spm_orthviews('Register',hReg)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%
% spm_orthviews('AddContext',handle)
% handle - image number to add context menu to
%
% spm_orthviews('RemoveContext',handle)
% handle - image number to remove context menu from
%
% CONTEXT MENU
% spm_orthviews offers many of its features in a context menu, which is
% accessible via the right mouse button in each displayed image.
%
% PLUGINS
% The display capabilities of spm_orthviews can be extended with
% plugins. These are located in the spm_orthviews subdirectory of the SPM
% distribution. Currently there are 3 plugins available:
% quiver Add Quiver plots to a displayed image
% quiver3d Add 3D Quiver plots to a displayed image
% roi ROI creation and modification
% The functionality of plugins can be accessed via calls to
% spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions
% of each plugin see help spm_orthviews/spm_ov_'plugin_name'.
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner, Matthew Brett, Tom Nichols and Volkmar Glauche
% $Id: spm_orthviews.m 112 2005-05-04 18:20:52Z john $
% The basic fields of st are:
% n - the number of images currently being displayed
% vols - a cell array containing the data on each of the
% displayed images.
% Space - a mapping between the displayed images and the
% mm space of each image.
% bb - the bounding box of the displayed images.
% centre - the current centre of the orthogonal views
% callback - a callback to be evaluated on a button-click.
% xhairs - crosshairs off/on
% hld - the interpolation method
% fig - the figure that everything is displayed in
% mode - the position/orientation of the sagittal view.
% - currently always 1
%
% st.registry.hReg \_ See spm_XYZreg for documentation
% st.registry.hMe /
%
% For each of the displayed images, there is a non-empty entry in the
% vols cell array. Handles returned by "spm_orthviews('Image',.....)"
% indicate the position in the cell array of the newly created ortho-view.
% Operations on each ortho-view require the handle to be passed.
%
% When a new image is displayed, the cell entry contains the information
% returned by spm_vol (type help spm_vol for more info). In addition,
% there are a few other fields, some of which I will document here:
%
% premul - a matrix to premultiply the .mat field by. Useful
% for re-orienting images.
% window - either 'auto' or an intensity range to display the
% image with.
%
% ax - a cell array containing an element for the three
% views. The fields of each element are handles for
% the axis, image and crosshairs.
%
% blobs - optional. Is there for using to superimpose blobs.
% vol - 3D array of image data
% mat - a mapping from vox-to-mm (see spm_vol, or
% help on image formats).
% max - maximum intensity for scaling to. If it
% does not exist, then images are auto-scaled.
%
% There are two colouring modes: full colour, and split
% colour. When using full colour, there should be a
% 'colour' field for each cell element. When using
% split colourscale, there is a handle for the colorbar
% axis.
%
% colour - if it exists it contains the
% red,green,blue that the blobs should be
% displayed in.
% cbar - handle for colorbar (for split colourscale).
%
% PLUGINS
% The plugin concept has been developed to extend the display capabilities
% of spm_orthviews without the need to rewrite parts of it. Interaction
% between spm_orthviews and plugins takes place
% a) at startup: The subfunction 'reset_st' looks for files with a name
% spm_ov_PLUGINNAME.m in the directory 'SWD/spm_orthviews'.
% For each such file, PLUGINNAME will be added to the list
% st.plugins{:}.
% The subfunction 'add_context' calls each plugin with
% feval(['spm_ov_', st.plugins{k}], ...
% 'context_menu', i, parent_menu)
% Each plugin may add its own submenu to the context
% menu.
% b) at redraw: After images and blobs of st.vols{i} are drawn, the
% struct st.vols{i} is checked for field names that occur in
% the plugin list st.plugins{:}. For each matching entry, the
% corresponding plugin is called with the command 'redraw':
% feval(['spm_ov_', st.plugins{k}], ...
% 'redraw', i, TM0, TD, CM0, CD, SM0, SD);
% The values of TM0, TD, CM0, CD, SM0, SD are defined in the
% same way as in the redraw subfunction of spm_orthviews.
% It is up to the plugin to do all necessary redraw
% operations for its display contents. Each displayed item
% must have set its property 'HitTest' to 'off' to let events
% go through to the underlying axis, which is responsible for
% callback handling. The order in which plugins are called is
% undefined.
global st;
if isempty(st), reset_st; end;
spm('Pointer','watch');
if nargin == 0, action = ''; end;
action = lower(action);
switch lower(action),
case 'image',
H = specify_image(varargin{1});
if ~isempty(H)
st.vols{H}.area = [0 0 1 1];
if length(varargin)>=2, st.vols{H}.area = varargin{2}; end;
voxdim = mean(sqrt(sum((st.vols{H}.mat(1:3,1:3)).^2))); % added sjs
st.Space = diag([voxdim voxdim voxdim 1]);
if isempty(st.bb), st.bb = maxbb; end;
bbox;
cm_pos;
end;
varargout{1} = H;
st.centre = mean(maxbb);
redraw_all
case 'bb',
if length(varargin)> 0 & all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end;
bbox;
redraw_all;
case 'redraw',
redraw_all;
eval(st.callback);
if isfield(st,'registry'),
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end;
case 'reposition',
if length(varargin)<1, tmp = findcent;
else, tmp = varargin{1}; end;
if length(tmp)==3, st.centre = tmp(:); end;
redraw_all;
eval(st.callback);
if isfield(st,'registry'),
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end;
cm_pos;
case 'setcoords',
st.centre = varargin{1};
st.centre = st.centre(:);
redraw_all;
eval(st.callback);
cm_pos;
case 'space',
if length(varargin)<1,
voxdim = mean(sqrt(sum((st.vols{1}.mat(1:3,1:3)).^2)));
st.Space = diag([voxdim voxdim voxdim 1]);
st.bb = maxbb;
redraw_all;
else,
space(varargin{1});
redraw_all;
end;
bbox;
case 'maxbb',
st.bb = maxbb;
bbox;
redraw_all;
case 'resolution',
resolution(varargin{1});
bbox;
redraw_all;
case 'window',
if length(varargin)<2,
win = 'auto';
elseif length(varargin{2})==2,
win = varargin{2};
end;
for i=valid_handles(varargin{1}),
st.vols{i}.window = win;
end;
redraw(varargin{1});
case 'delete',
my_delete(varargin{1});
case 'move',
move(varargin{1},varargin{2});
% redraw_all;
case 'reset',
my_reset;
case 'pos',
if isempty(varargin),
H = st.centre(:);
else,
H = pos(varargin{1});
end;
varargout{1} = H;
case 'interp',
st.hld = varargin{1};
redraw_all;
case 'xhairs',
xhairs(varargin{1});
case 'register',
register(varargin{1});
case 'addblobs',
addblobs(varargin{1}, varargin{2},varargin{3},varargin{4});
% redraw(varargin{1});
case 'addcolouredblobs',
addcolouredblobs(varargin{1}, varargin{2},varargin{3},varargin{4},varargin{5});
% redraw(varargin{1});
case 'addimage',
addimage(varargin{1}, varargin{2});
% redraw(varargin{1});
case 'addcolouredimage',
addcolouredimage(varargin{1}, varargin{2},varargin{3});
% redraw(varargin{1});
case 'addtruecolourimage',
% spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn)
% Adds blobs from an image in true colour
% handle - image number to add blobs to [default 1]
% filename of image containing blob data [default - request via GUI]
% colourmap - colormap to display blobs in [GUI input]
% prop - intensity proportion of activation cf grayscale [0.4]
% mx - maximum intensity to scale to [maximum value in activation image]
% mn - minimum intensity to scale to [minimum value in activation image]
%
if nargin < 2
varargin(1) = {1};
end
if nargin < 3
varargin(2) = {spm_select(1, 'image', 'Image with activation signal')};
end
if nargin < 4
actc = [];
while isempty(actc)
actc = getcmap(spm_input('Colourmap for activation image', '+1','s'));
end
varargin(3) = {actc};
end
if nargin < 5
varargin(4) = {0.4};
end
if nargin < 6
actv = spm_vol(varargin{2});
varargin(5) = {max([eps maxval(actv)])};
end
if nargin < 7
varargin(6) = {min([0 minval(actv)])};
end
addtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ...
varargin{5}, varargin{6});
% redraw(varargin{1});
case 'rmblobs',
rmblobs(varargin{1});
% redraw(varargin{1});
case 'addcontext',
if nargin == 1,
handles = 1:24;
else,
handles = varargin{1};
end;
addcontexts(handles);
case 'rmcontext',
if nargin == 1,
handles = 1:24;
else,
handles = varargin{1};
end;
rmcontexts(handles);
case 'context_menu',
c_menu(varargin{:});
case 'valid_handles',
if nargin == 1
handles = 1:24;
else,
handles = varargin{1};
end;
varargout{1} = valid_handles(handles);
otherwise,
addonaction = strcmp(st.plugins,action);
if any(addonaction)
feval(['spm_ov_' st.plugins{addonaction}],varargin{:});
else
warning('Unknown action string')
end;
end;
spm('Pointer');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addblobs(handle, xyz, t, mat)
global st
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
st.vols{i}.blobs=cell(1,1);
if st.mode == 0,
axpos = get(st.vols{i}.ax{2}.ax,'Position');
else,
axpos = get(st.vols{i}.ax{1}.ax,'Position');
end;
ax = axes('Parent',st.fig,'Position',[(axpos(1)+axpos(3)+0.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'Box','on');
mx = max([eps max(t)]);
mn = min([0 min(t)]);
image([0 1],[mn mx],[1:64]' + 64,'Parent',ax);
set(ax,'YDir','normal','XTickLabel',[]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'cbar',ax,'max',mx, 'min',mn);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addimage(handle, fname)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else,
vol = spm_vol(fname);
end;
mat = vol.mat;
st.vols{i}.blobs=cell(1,1);
if st.mode == 0,
axpos = get(st.vols{i}.ax{2}.ax,'Position');
else,
axpos = get(st.vols{i}.ax{1}.ax,'Position');
end;
ax = axes('Parent',st.fig,'Position',[(axpos(1)+axpos(3)+0.05) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'Box','on');
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
image([0 1],[mn mx],[1:64]' + 64,'Parent',ax);
set(ax,'YDir','normal','XTickLabel',[]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'cbar',ax,'max',mx);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredblobs(handle, xyz, t, mat,colour)
global st
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else,
bset = length(st.vols{i}.blobs)+1;
end;
axpos = get(st.vols{i}.ax{2}.ax,'Position');
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredimage(handle, fname,colour)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else,
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else,
bset = length(st.vols{i}.blobs)+1;
end;
axpos = get(st.vols{i}.ax{2}.ax,'Position');
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addtruecolourimage(handle,fname,colourmap,prop,mx,mn)
% adds true colour image to current displayed image
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else,
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else,
bset = length(st.vols{i}.blobs)+1;
end;
axpos = get(st.vols{i}.ax{2}.ax,'Position');
ax = axes('Parent',st.fig,'Position',...
[(axpos(1)+axpos(3)+0.18) (axpos(2)-axpos(4)-0.03) 0.05 (axpos(4)-0.01)],...
'Box','on');
image([0 1],[mn mx],[1:64]' + 64,'Parent',ax);
set(ax,'YDir','normal','XTickLabel',[]);
title(spm_str_manip(fname,'t'),'FontSize',8)
c = struct('cmap', colourmap,'prop',prop);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',c);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmblobs(handle)
global st
for i=valid_handles(handle),
if isfield(st.vols{i},'blobs'),
for j=1:length(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'cbar') & ishandle(st.vols{i}.blobs{j}.cbar),
delete(st.vols{i}.blobs{j}.cbar);
end;
end;
st.vols{i} = rmfield(st.vols{i},'blobs');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function register(hreg)
global st
tmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig);
h = valid_handles(1:24);
if ~isempty(h),
tmp = st.vols{h(1)}.ax{1}.ax;
st.registry = struct('hReg',hreg,'hMe', tmp);
spm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews');
else,
warning('Nothing to register with');
end;
st.centre = spm_XYZreg('GetCoords',st.registry.hReg);
st.centre = st.centre(:);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function xhairs(arg1),
global st
st.xhairs = 0;
opt = 'on';
if ~strcmp(arg1,'on'),
opt = 'off';
else,
st.xhairs = 1;
end;
for i=valid_handles(1:24),
for j=1:3,
set(st.vols{i}.ax{j}.lx,'Visible',opt);
set(st.vols{i}.ax{j}.ly,'Visible',opt);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = pos(arg1)
global st
H = [];
for arg1=valid_handles(arg1),
is = inv(st.vols{arg1}.premul*st.vols{arg1}.mat);
H = is(1:3,1:3)*st.centre(:) + is(1:3,4);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_reset
global st
if ~isempty(st) & isfield(st,'registry') & ishandle(st.registry.hMe),
delete(st.registry.hMe); st = rmfield(st,'registry');
end;
my_delete(1:24);
reset_st;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_delete(arg1)
global st
for i=valid_handles(arg1),
kids = get(st.fig,'Children');
for j=1:3,
if any(kids == st.vols{i}.ax{j}.ax),
set(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn','');
delete(st.vols{i}.ax{j}.ax);
end;
end;
st.vols{i} = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function resolution(arg1)
global st
res = arg1/mean(svd(st.Space(1:3,1:3)));
Mat = diag([res res res 1]);
st.Space = st.Space*Mat;
st.bb = st.bb/res;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function move(handle,pos)
global st
for handle = valid_handles(handle),
st.vols{handle}.area = pos;
end;
bbox;
% redraw(valid_handles(handle));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bb = maxbb
global st
mn = [Inf Inf Inf];
mx = -mn;
for i=valid_handles(1:24),
bb = [[1 1 1];st.vols{i}.dim(1:3)];
c = [ bb(1,1) bb(1,2) bb(1,3) 1
bb(1,1) bb(1,2) bb(2,3) 1
bb(1,1) bb(2,2) bb(1,3) 1
bb(1,1) bb(2,2) bb(2,3) 1
bb(2,1) bb(1,2) bb(1,3) 1
bb(2,1) bb(1,2) bb(2,3) 1
bb(2,1) bb(2,2) bb(1,3) 1
bb(2,1) bb(2,2) bb(2,3) 1]';
tc = st.Space\(st.vols{i}.premul*st.vols{i}.mat)*c;
tc = tc(1:3,:)';
mx = max([tc ; mx]);
mn = min([tc ; mn]);
end;
bb = [mn ; mx];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function space(arg1)
global st
if ~isempty(st.vols{arg1})
num = arg1;
Mat = st.vols{num}.premul(1:3,1:3)*st.vols{num}.mat(1:3,1:3);
vox = sqrt(sum(Mat.^2));
if det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end;
Mat = diag([vox 1]);
Space = (st.vols{num}.mat)/Mat;
bb = [1 1 1;st.vols{num}.dim(1:3)];
bb = [bb [1;1]];
bb=bb*Mat';
bb=bb(:,1:3);
bb=sort(bb);
mvox = mean(vox); %added sjs
st.Space = diag([mvox mvox mvox 1]) * Space;
st.bb = maxbb;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = specify_image(arg1, arg2)
global st
H=[];
ok = 1;
if isstruct(arg1),
V = arg1(1);
else,
try,
V = spm_vol(arg1);
catch,
fprintf('Can not use image "%s"\n', arg1);
return;
end;
end;
ii = 1;
while ~isempty(st.vols{ii}), ii = ii + 1; end;
DeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');'];
V.ax = cell(3,1);
for i=1:3,
ax = axes('Visible','off','DrawMode','fast','Parent',st.fig,'DeleteFcn',DeleteFcn,...
'YDir','normal','ButtonDownFcn',...
['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...
'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''Reposition'');',...
'spm_orthviews(''context_menu'',''ts'',1);end;']);
d = image(0,'Tag','Transverse','Parent',ax,...
'DeleteFcn',DeleteFcn);
set(ax,'Ydir','normal','ButtonDownFcn',...
['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...
'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''reposition'');',...
'spm_orthviews(''context_menu'',''ts'',1);end;']);
lx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);
ly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);
if ~st.xhairs,
set(lx,'Visible','off');
set(ly,'Visible','off');
end;
V.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly);
end;
V.premul = eye(4);
V.window = 'auto';
st.vols{ii} = V;
H = ii;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcontexts(handles)
global st
for ii = valid_handles(handles),
cm_handle = addcontext(ii);
for i=1:3,
set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',cm_handle);
st.vols{ii}.ax{i}.cm = cm_handle;
end;
end;
spm_orthviews('reposition',spm_orthviews('pos'));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmcontexts(handles)
global st
for ii = valid_handles(handles),
for i=1:3,
set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]);
st.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bbox
global st
Dims = diff(st.bb)'+1;
TD = Dims([1 2])';
CD = Dims([1 3])';
if st.mode == 0, SD = Dims([3 2])'; else, SD = Dims([2 3])'; end;
un = get(st.fig,'Units');set(st.fig,'Units','Pixels');
sz = get(st.fig,'Position');set(st.fig,'Units',un);
sz = sz(3:4);
sz(2) = sz(2)-40;
for i=valid_handles(1:24),
area = st.vols{i}.area(:);
area = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)];
if st.mode == 0,
sx = area(3)/(Dims(1)+Dims(3))/1.02;
else,
sx = area(3)/(Dims(1)+Dims(2))/1.02;
end;
sy = area(4)/(Dims(2)+Dims(3))/1.02;
s = min([sx sy]);
offy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2);
sky = s*(Dims(2)+Dims(3))*0.02;
if st.mode == 0,
offx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(3))*0.02;
else,
offx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(2))*0.02;
end;
DeleteFcn = ['spm_orthviews(''Delete'',' num2str(i) ');'];
% Transverse
set(st.vols{i}.ax{1}.ax,'Units','pixels', ...
'Position',[offx offy s*Dims(1) s*Dims(2)],...
'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Coronal
set(st.vols{i}.ax{2}.ax,'Units','Pixels',...
'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],...
'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Sagittal
if st.mode == 0,
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
else,
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw_all
global st
redraw(1:24);
return;
%_______________________________________________________________________
function mx = maxval(vol)
if isstruct(vol),
mx = -Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imx = max(tmp(find(isfinite(tmp))));
if ~isempty(imx),mx = max(mx,imx);end
end;
else,
mx = max(vol(find(isfinite(vol))));
end;
%_______________________________________________________________________
function mn = minval(vol)
if isstruct(vol),
mn = Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imn = min(tmp(find(isfinite(tmp))));
if ~isempty(imn),mn = min(mn,imn);end
end;
else,
mn = min(vol(find(isfinite(vol))));
end;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw(arg1)
global st
bb = st.bb;
Dims = round(diff(bb)'+1);%/ mean(sqrt(sum(svd(st.vols{1}.mat(1:3,1:3)).^2))))
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
% voxadj = 0
%
% if ~voxadj
% voxadj = 1;
% end
for i = valid_handles(arg1),
M = st.vols{i}.premul*st.vols{i}.mat;
TM0 = [ 1 0 0 -bb(1,1)+1
0 1 0 -bb(1,2)+1
0 0 1 -cent(3)
0 0 0 1];
TM = inv(TM0*(st.Space\M));
TD = Dims([1 2]);
CM0 = [ 1 0 0 -bb(1,1)+1
0 0 1 -bb(1,3)+1
0 1 0 -cent(2)
0 0 0 1];
CM = inv(CM0*(st.Space\M));
CD = Dims([1 3]);
if st.mode ==0,
SM0 = [ 0 0 1 -bb(1,3)+1
0 1 0 -bb(1,2)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*(st.Space\M)); SD = Dims([3 2]);
else,
SM0 = [ 0 1 0 -bb(1,2)+1
0 0 1 -bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
SM0 = [ 0 -1 0 +bb(2,2)+1
0 0 1 -bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*(st.Space\M));
SD = Dims([2 3]);
end;
ok=1;
eval('imgt = (spm_slice_vol(st.vols{i},TM,TD,st.hld))'';','ok=0;');
eval('imgc = (spm_slice_vol(st.vols{i},CM,CD,st.hld))'';','ok=0;');
eval('imgs = (spm_slice_vol(st.vols{i},SM,SD,st.hld))'';','ok=0;');
if (ok==0), fprintf('Image "%s" can not be resampled\n', st.vols{i}.fname);
else,
if strcmp(st.vols{i}.window,'auto'),
mx = -Inf; mn = Inf;
if ~isempty(imgt),
mx = max([mx max(max(imgt))]);
mn = min([mn min(min(imgt))]);
end;
if ~isempty(imgc),
mx = max([mx max(max(imgc))]);
mn = min([mn min(min(imgc))]);
end;
if ~isempty(imgs),
mx = max([mx max(max(imgs))]);
mn = min([mn min(min(imgs))]);
end;
if mx==mn, mx=mn+eps; end;
else,
mx = st.vols{i}.window(2);
mn = st.vols{i}.window(1);
r=min([mn mx]);imgt = max(imgt,r); r=max([mn mx]);imgt = min(imgt,r);
r=min([mn mx]);imgc = max(imgc,r); r=max([mn mx]);imgc = min(imgc,r);
r=min([mn mx]);imgs = max(imgs,r); r=max([mn mx]);imgs = min(imgs,r);
end;
if isfield(st,'overlay');
q = st.overlay.mat;
tmpt = spm_slice_vol(st.overlay,inv(TM0*(st.Space\q)),TD,[0 NaN])';
tmpc = spm_slice_vol(st.overlay,inv(CM0*(st.Space\q)),CD,[0 NaN])';
tmps = spm_slice_vol(st.overlay,inv(SM0*(st.Space\q)),SD,[0 NaN])';
tmpt(~isfinite(tmpt)) = 0;
tmps(~isfinite(tmps)) = 0;
tmpc(~isfinite(tmpc)) = 0;
tmpt = tmpt/(max(tmpt(:))+eps);
tmps = tmps/(max(tmps(:))+eps);
tmpc = tmpc/(max(tmpc(:))+eps);
imgt = imgt/(max(imgt(:))+eps);
imgc = imgc/(max(imgc(:))+eps);
imgs = imgs/(max(imgs(:))+eps);
%convert to colour
imgt = repmat(imgt,[1 1 3]);
imgc = repmat(imgc,[1 1 3]);
imgs = repmat(imgs,[1 1 3]);
%add overlay
if isfield(st.overlay,'col')==0
col = [0 1 1]; % green
st.overlay.col=col;
else
col=st.overlay.col;
end
if isfield(st.overlay,'wt')==0
wt = 0.3; % weighting
st.overlay.wt=wt;
else
wt=st.overlay.wt;
end
for jj=1:3
imgt(:,:,jj) = (0.8) * imgt(:,:,jj) + wt.*col(jj).*tmpt;
imgs(:,:,jj) = (0.8) * imgs(:,:,jj) + wt.*col(jj).*tmps;
imgc(:,:,jj) = (0.8) * imgc(:,:,jj) + wt.*col(jj).*tmpc;
end
% normalise
imgt = abs(imgt/max(imgt(:)));
imgc = abs(imgc/max(imgc(:)));
imgs = abs(imgs/max(imgs(:)));
else
if isfield(st.vols{i},'blobs'),
if ~isfield(st.vols{i}.blobs{1},'colour'),
% Add blobs for display using the split colourmap
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
if isfield(st.vols{i}.blobs{1},'max'),
mx = st.vols{i}.blobs{1}.max;
else,
mx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.max = mx;
end;
if isfield(st.vols{i}.blobs{1},'min'),
mn = st.vols{i}.blobs{1}.min;
else,
mn = min([0 minval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.min = mn;
end;
vol = st.vols{i}.blobs{1}.vol;
M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])';
%tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN;
%tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN;
%tmps_z = find(tmps==0);tmps(tmps_z) = NaN;
sc = 64/(mx-mn);
off = 65.51-mn*sc;
msk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc;
msk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc;
msk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc;
cmap = get(st.fig,'Colormap');
if size(cmap,1)~=128
figure(st.fig)
spm_figure('Colormap','gray-hot')
end;
elseif isstruct(st.vols{i}.blobs{1}.colour),
% Add blobs for display using a defined
% colourmap
% colourmaps
gryc = [0:63]'*ones(1,3)/63;
actc = ...
st.vols{1}.blobs{1}.colour.cmap;
actp = ...
st.vols{1}.blobs{1}.colour.prop;
% scale grayscale image, not isfinite -> black
imgt = scaletocmap(imgt,mn,mx,gryc,65);
imgc = scaletocmap(imgc,mn,mx,gryc,65);
imgs = scaletocmap(imgs,mn,mx,gryc,65);
gryc = [gryc; 0 0 0];
% get max for blob image
vol = st.vols{i}.blobs{1}.vol;
mat = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
if isfield(st.vols{i}.blobs{1},'max'),
cmx = st.vols{i}.blobs{1}.max;
else,
cmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
end;
% get blob data
vol = st.vols{i}.blobs{1}.vol;
M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])';
% actimg scaled round 0, black NaNs
topc = size(actc,1)+1;
tmpt = scaletocmap(tmpt,-cmx,cmx,actc,topc);
tmpc = scaletocmap(tmpc,-cmx,cmx,actc,topc);
tmps = scaletocmap(tmps,-cmx,cmx,actc,topc);
actc = [actc; 0 0 0];
% combine gray and blob data to
% truecolour
imgt = reshape(actc(tmpt(:),:)*actp+ ...
gryc(imgt(:),:)*(1-actp), ...
[size(imgt) 3]);
imgc = reshape(actc(tmpc(:),:)*actp+ ...
gryc(imgc(:),:)*(1-actp), ...
[size(imgc) 3]);
imgs = reshape(actc(tmps(:),:)*actp+ ...
gryc(imgs(:),:)*(1-actp), ...
[size(imgs) 3]);
else,
% Add full colour blobs - several sets at once
scal = 1/(mx-mn);
dcoff = -mn*scal;
wt = zeros(size(imgt));
wc = zeros(size(imgc));
ws = zeros(size(imgs));
imgt = repmat(imgt*scal+dcoff,[1,1,3]);
imgc = repmat(imgc*scal+dcoff,[1,1,3]);
imgs = repmat(imgs*scal+dcoff,[1,1,3]);
cimgt = zeros(size(imgt));
cimgc = zeros(size(imgc));
cimgs = zeros(size(imgs));
for j=1:length(st.vols{i}.blobs), % get colours of all images first
if isfield(st.vols{i}.blobs{j},'colour'),
colour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]);
else,
colour(j,:) = [1 0 0];
end;
end;
%colour = colour/max(sum(colour));
for j=1:length(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'max'),
mx = st.vols{i}.blobs{j}.max;
else,
mx = max([eps max(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.max = mx;
end;
if isfield(st.vols{i}.blobs{j},'min'),
mn = st.vols{i}.blobs{j}.min;
else,
mn = min([0 min(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.min = mn;
end;
vol = st.vols{i}.blobs{j}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{j}.mat;
tmpt = (spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])'+mn)/(mx-mn);
tmpc = (spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])'+mn)/(mx-mn);
tmps = (spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])'+mn)/(mx-mn);
tmpt(~isfinite(tmpt)) = 0;
tmpc(~isfinite(tmpc)) = 0;
tmps(~isfinite(tmps)) = 0;
cimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3));
cimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3));
cimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3));
wt = wt + tmpt;
wc = wc + tmpc;
ws = ws + tmps;
end;
%cimgt(cimgt<0)=0; cimgt(cimgt>1)=1;
%cimgc(cimgc<0)=0; cimgc(cimgc>1)=1;
%cimgs(cimgs<0)=0; cimgs(cimgs>1)=1;
imgt = repmat(1-wt,[1 1 3]).*imgt+cimgt;
imgc = repmat(1-wc,[1 1 3]).*imgc+cimgc;
imgs = repmat(1-ws,[1 1 3]).*imgs+cimgs;
imgt(imgt<0)=0; imgt(imgt>1)=1;
imgc(imgc<0)=0; imgc(imgc>1)=1;
imgs(imgs<0)=0; imgs(imgs>1)=1;
end;
else,
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
end;
end;
set(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt);
set(st.vols{i}.ax{1}.lx,'HitTest','off',...
'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{1}.ly,'HitTest','off',...
'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc); %##
set(st.vols{i}.ax{2}.lx,'HitTest','off',...
'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{2}.ly,'HitTest','off',...
'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs);
if st.mode ==0,
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1));
else,
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2)));
end;
%% PAUL 3
box=getappdata(gcf,'box');
if ~isfield(box,'iscontour')
box.iscontour=0;
setappdata(gcf,'box',box);
box=getappdata(gcf,'box');
end
if box.iscontour==0;
try; delete(findobj(gcf, 'tag','pcontourc'));end
else
% if st.overlay.wt<.1
try; delete(findobj(gcf, 'tag','pcontourc'));end
set(gcf,'currentaxes',(st.vols{i}.ax{1}.ax));
hold on
contour( (tmpt ),2,'color','r','tag','pcontourc');
set(gcf,'currentaxes',(st.vols{i}.ax{2}.ax));
hold on
contour( (tmpc ),3,'color','r','tag','pcontourc');
set(gcf,'currentaxes',(st.vols{i}.ax{3}.ax));
hold on
contour( (tmps ),3,'color','r','tag','pcontourc');
end
if ~isempty(st.plugins) % process any addons
for k = 1:prod(size(st.plugins))
if isfield(st.vols{i},st.plugins{k})
feval(['spm_ov_', st.plugins{k}], ...
'redraw', i, TM0, TD, CM0, CD, SM0, SD);
end;
end;
end;
end;
end;
drawnow;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function centre = findcent
global st
obj = get(st.fig,'CurrentObject');
centre = [];
cent = [];
cp = [];
for i=valid_handles(1:24),
for j=1:3,
if ~isempty(obj),
if (st.vols{i}.ax{j}.ax == obj),
cp = get(obj,'CurrentPoint');
end;
end;
if ~isempty(cp),
cp = cp(1,1:2);
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
switch j,
case 1,
cent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1];
case 2,
cent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1];
case 3,
if st.mode ==0,
cent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1];
else,
cent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1];
end;
end;
break;
end;
end;
if ~isempty(cent), break; end;
end;
if ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function handles = valid_handles(handles)
global st;
handles = handles(:)';
handles = handles(find(handles<=24 & handles>=1 & ~rem(handles,1)));
for h=handles,
if isempty(st.vols{h}), handles(find(handles==h))=[]; end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function reset_st
global st
fig = spm_figure('FindWin','Graphics');
bb = []; %[ [-78 78]' [-112 76]' [-50 85]' ];
st = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',[]);
st.vols = cell(24,1);
pluginpath = fullfile(spm('Dir'),'spm_orthviews');
if isdir(pluginpath)
pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m'));
if ~isempty(pluginfiles)
addpath(pluginpath);
% fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath);
for k = 1:length(pluginfiles)
[p pluginname e v] = fileparts(pluginfiles(k).name);
st.plugins{k} = strrep(pluginname, 'spm_ov_','');
% fprintf('%s\n',st.plugins{k});
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = scaletocmap(inpimg,mn,mx,cmap,miscol)
if nargin < 5, miscol=1;end
cml = size(cmap,1);
scf = (cml-1)/(mx-mn);
img = round((inpimg-mn)*scf)+1;
img(find(img<1)) = 1;
img(find(img>cml)) = cml;
img(~isfinite(img)) = miscol;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cmap = getcmap(acmapname)
% get colormap of name acmapname
if ~isempty(acmapname),
cmap = evalin('base',acmapname,'[]');
if isempty(cmap), % not a matrix, is .mat file?
[p f e] = fileparts(acmapname);
acmat = fullfile(p, [f '.mat']);
if exist(acmat, 'file'),
s = struct2cell(load(acmat));
cmap = s{1};
end;
end;
end;
if size(cmap, 2)~=3,
warning('Colormap was not an N by 3 matrix')
cmap = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function item_parent = addcontext(volhandle)
global st;
%create context menu
fg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg);
%contextmenu
item_parent = uicontextmenu;
%contextsubmenu 0
item00 = uimenu(item_parent, 'Label','unknown image', 'Separator','on');
spm_orthviews('context_menu','image_info',item00,volhandle);
item0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on');
item0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');');
item0c = uimenu(item_parent, 'UserData','v_value');
%contextsubmenu 1
item1 = uimenu(item_parent,'Label','Zoom');
item1_1 = uimenu(item1, 'Label','Full Volume', 'Callback','spm_orthviews(''context_menu'',''zoom'',6);', 'Checked','on');
item1_2 = uimenu(item1, 'Label','20x vox', 'Callback','spm_orthviews(''context_menu'',''zoom'',5);');
item1_3 = uimenu(item1, 'Label','10x vox', 'Callback','spm_orthviews(''context_menu'',''zoom'',4);');
item1_4 = uimenu(item1, 'Label','5x vox', 'Callback','spm_orthviews(''context_menu'',''zoom'',3);');
item1_5 = uimenu(item1, 'Label','2.5x vox', 'Callback','spm_orthviews(''context_menu'',''zoom'',2);');
item1_6 = uimenu(item1, 'Label','1.25x vox', 'Callback','spm_orthviews(''context_menu'',''zoom'',1);');
%contextsubmenu 2
checked={'off','off'};
checked{st.xhairs+1} = 'on';
item2 = uimenu(item_parent,'Label','Crosshairs');
item2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2});
item2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1});
%contextsubmenu 3
if st.Space == eye(4)
checked = {'off', 'on'};
else
checked = {'on', 'off'};
end;
item3 = uimenu(item_parent,'Label','Orientation');
item3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2});
item3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1});
item3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off');
%contextsubmenu 4
if st.hld == 0,
checked = {'off', 'off', 'on'};
elseif st.hld > 0,
checked = {'off', 'on', 'off'};
else,
checked = {'on', 'off', 'off'};
end;
item4 = uimenu(item_parent,'Label','Interpolation');
item4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3});
item4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2});
item4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1});
%contextsubmenu 5
% item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');');
%contextsubmenu 6
item6 = uimenu(item_parent,'Label','Image','Separator','on');
item6_1 = uimenu(item6, 'Label','Window');
item6_1_1 = uimenu(item6_1, 'Label','local');
item6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);');
item6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);');
item6_1_2 = uimenu(item6_1, 'Label','global');
item6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);');
item6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);');
%contextsubmenu 7
item7 = uimenu(item_parent,'Label','Blobs');
item7_1 = uimenu(item7, 'Label','Add blobs');
item7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);');
item7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);');
item7_2 = uimenu(item7, 'Label','Add colored blobs');
item7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);');
item7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);');
item7_3 = uimenu(item7, 'Label','Add colored image');
item7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);');
item7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);');
item7_4 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on');
item7_5 = uimenu(item7, 'Label','Remove colored blobs','Visible','off');
item7_5_1 = uimenu(item7_5, 'Label','local', 'Visible','on');
item7_5_2 = uimenu(item7_5, 'Label','global','Visible','on');
for i=1:3,
set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent);
st.vols{volhandle}.ax{i}.cm = item_parent;
end;
if ~isempty(st.plugins) % process any plugins
for k = 1:prod(size(st.plugins)),
feval(['spm_ov_', st.plugins{k}], ...
'context_menu', volhandle, item_parent);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function c_menu(varargin)
global st
switch lower(varargin{1}),
case 'image_info',
if nargin <3,
current_handle = get_current_handle;
else
current_handle = varargin{3};
end;
if isfield(st.vols{current_handle},'fname'),
[p,n,e,v] = fileparts(st.vols{current_handle}.fname);
set(varargin{2}, 'Label',[n e v]);
end;
delete(get(varargin{2},'children'));
if exist('p','var')
item1 = uimenu(varargin{2}, 'Label', p);
end;
if isfield(st.vols{current_handle},'descrip'),
item2 = uimenu(varargin{2}, 'Label',...
st.vols{current_handle}.descrip);
end;
if isfield(st.vols{current_handle},'dt'),
dt = st.vols{current_handle}.dt(1);
else,
dt = st.vols{current_handle}.dt(1);
end;
item3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt)));
str = 'Intensity: varied';
if size(st.vols{current_handle}.pinfo,2) == 1,
if st.vols{current_handle}.pinfo(2),
str = sprintf('Intensity: Y = %g X + %g',...
st.vols{current_handle}.pinfo(1:2)');
else,
str = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)');
end;
end;
item4 = uimenu(varargin{2}, 'Label',str);
item5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on');
item51 = uimenu(varargin{2}, 'Label',...
sprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3)));
prms = spm_imatrix(st.vols{current_handle}.mat);
item6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on');
item61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9)));
item7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on');
item71 = uimenu(varargin{2}, 'Label',...
sprintf('%.2f %.2f %.2f', prms(1:3)));
R = spm_matrix([0 0 0 prms(4:6)]);
item8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on');
item81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3)));
item82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3)));
item83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3)));
item9 = uimenu(varargin{2},...
'Label','Specify other image...',...
'Callback','spm_orthviews(''context_menu'',''swap_img'');',...
'Separator','on');
case 'repos_mm',
oldpos_mm = spm_orthviews('pos');
newpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3);
spm_orthviews('reposition',newpos_mm);
case 'repos_vx'
current_handle = get_current_handle;
oldpos_vx = spm_orthviews('pos', current_handle);
newpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3);
newpos_mm = st.vols{current_handle}.mat*[newpos_vx;1];
spm_orthviews('reposition',newpos_mm(1:3));
case 'zoom'
zoom_all(varargin{2});
bbox;
redraw_all;
case 'xhair',
spm_orthviews('Xhairs',varargin{2});
cm_handles = get_cm_handles;
for i = 1:length(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children');
set(z_handle,'Checked','off'); %reset check
if strcmp(varargin{2},'off'), op = 1; else op = 2; end
set(z_handle(op),'Checked','on');
end;
case 'orientation',
cm_handles = get_cm_handles;
for i = 1:length(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children');
set(z_handle,'Checked','off');
end;
if varargin{2} == 3,
spm_orthviews('Space');
elseif varargin{2} == 2,
spm_orthviews('Space',1);
else,
spm_orthviews('Space',get_current_handle);
z_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Orientation'),'Children');
set(z_handle(1),'Checked','on');
return;
end;
for i = 1:length(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children');
set(z_handle(varargin{2}),'Checked','on');
end;
case 'interpolation',
tmp = [-4 1 0];
st.hld = tmp(varargin{2});
cm_handles = get_cm_handles;
for i = 1:length(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children');
set(z_handle,'Checked','off');
set(z_handle(varargin{2}),'Checked','on');
end;
redraw_all;
case 'window',
current_handle = get_current_handle;
if varargin{2} == 2,
spm_orthviews('window',current_handle);
else
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%.2f %.2f', st.vols{current_handle}.window);
else
defstr = '';
end;
spm_orthviews('window',current_handle,spm_input('Range','+1','e',defstr,2));
end;
case 'window_gl',
if varargin{2} == 2,
for i = 1:length(get_cm_handles),
st.vols{i}.window = 'auto';
end;
else,
current_handle = get_current_handle;
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%d %d', st.vols{current_handle}.window);
else
defstr = '';
end;
data = spm_input('Range','+1','e',defstr,2);
for i = 1:length(get_cm_handles),
st.vols{i}.window = data;
end;
end;
redraw_all;
case 'swap_img',
current_handle = get_current_handle;
new_info = spm_vol(spm_select(1,'image','select new image'));
st.vols{current_handle}.fname = new_info.fname;
st.vols{current_handle}.dim = new_info.dim;
st.vols{current_handle}.mat = new_info.mat;
st.vols{current_handle}.pinfo = new_info.pinfo;
st.vols{current_handle}.descrip = new_info.descrip;
spm_orthviews('context_menu','image_info',get(gcbo, 'parent'));
redraw_all;
case 'add_blobs',
% Add blobs to the image - in split colortable
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_figure('Clear','Interactive');
[SPM,VOL] = spm_getSPM;
for i = 1:length(cm_handles),
addblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M);
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');
if varargin{2} == 1,
item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');
end;
end;
redraw_all;
case 'remove_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
for i = 1:length(cm_handles),
rmblobs(cm_handles(i));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
delete(get(c_handle,'Children'));
set(c_handle,'Visible','off');
end;
redraw_all;
case 'add_c_blobs',
% Add blobs to the image - in full colour
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_figure('Clear','Interactive');
[SPM,VOL] = spm_getSPM;
c = spm_input('Colour','+1','m',...
'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
for i = 1:length(cm_handles),
addcolouredblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M,colours(c,:));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',c_names{c},'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',...
'UserData',c);
if varargin{2} == 1,
item7_4_2 = uimenu(ch_c_handle(1),'Label',c_names{c},'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end;
end;
redraw_all;
case 'remove_c_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
for i = 1:length(cm_handles),
if isfield(st.vols{cm_handles(i)},'blobs'),
for j = 1:length(st.vols{cm_handles(i)}.blobs),
if st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:);
st.vols{cm_handles(i)}.blobs(j) = [];
break;
end;
end;
rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs');
delete(findobj(rm_c_menu,'Label',c_names{varargin{3}}));
if isempty(st.vols{cm_handles(i)}.blobs),
st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs');
set(rm_c_menu, 'Visible', 'off');
end;
end;
end;
redraw_all;
case 'add_c_image',
% Add truecolored image
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle;end;
spm_figure('Clear','Interactive');
fname = spm_select(1,'image','select image');
c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
for i = 1:length(cm_handles),
addcolouredimage(cm_handles(i),fname,colours(c,:));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',c_names{c},'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c);
if varargin{2} == 1
item7_4_2 = uimenu(ch_c_handle(1),'Label',c_names{c},'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end
end
redraw_all;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function current_handle = get_current_handle
global st
cm_handle = get(gca,'UIContextMenu');
cm_handles = get_cm_handles;
current_handle = find(cm_handles==cm_handle);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_pos
global st
for i = 1:length(valid_handles(1:24)),
if isfield(st.vols{i}.ax{1},'cm')
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),...
'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos')));
pos = spm_orthviews('pos',i);
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),...
'Label',sprintf('vx: %.1f %.1f %.1f',pos));
set(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),...
'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld)));
end
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_handles = get_cm_handles
global st
cm_handles = [];
for i=valid_handles(1:24),
cm_handles = [cm_handles st.vols{i}.ax{1}.cm];
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function zoom_all(op)
global st
cm_handles = get_cm_handles;
res = [.125 .125 .25 .5 1 1] *min(sqrt(sum((st.vols{1}.mat(1:3,1:3).^2))));
if op==6,
resolution(res(op));
st.bb = maxbb;
else,
vx = sqrt(sum(st.Space(1:3,1:3).^2));
vx = vx.^(-1);
pos = spm_orthviews('pos');
pos = st.Space\[pos ; 1];
pos = pos(1:3)';
if op == 5, st.bb = [pos-20*vx ; pos+20*vx] ;
elseif op == 4, st.bb = [pos-10*vx ; pos+10*vx] ;
elseif op == 3, st.bb = [pos-5*vx ; pos+5*vx] ;
elseif op == 2, st.bb = [pos-2.5*vx ; pos+2.5*vx] ;
elseif op == 1; st.bb = [pos- 1.25*vx ; pos+ 1.25*vx] ;
else disp('no Zoom possible');
end;
resolution(2*res(op));
end
redraw_all;
for i = 1:length(cm_handles)
z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children');
set(z_handle,'Checked','off');
set(z_handle(op),'Checked','on');
end
return;
|
github
|
philippboehmsturm/antx-master
|
dispoverlay3.m
|
.m
|
antx-master/mritools/displaykey/dispoverlay3.m
| 7,652 |
utf_8
|
a56808f77d607327389520407878aff2
|
function dispoverlay3(img1all,img2,namestr)
% FOR MULTIPLE PATHS
% dispoverlay2(paths,img2 )
% paths: cell of paths
% img2 : referenceImage
if ~iscell(img1all); img1all={img1all}; end
% if ~iscell(img1all); img1all={img1all}; end
global ovl ;
ovl.img1all=img1all;
ovl.img2 =img2 ;
ovl.n =1 ;
ovl.doloop =1;
%====================================
while ovl.doloop==1
% for i=6:size(paths,1)
i=ovl.n ;
% [t] = spm_select('FPList',[paths{i} ],'^s.*nii$')
img1=img1all{i};
[pa fi fmt]=fileparts(img1);
if ~isempty(pa); cd(pa);end
% img1=t;%char(t);
ovl.img1={[fi fmt]};
% img2= 'V:\mritools\tpm\pgreyr62.nii'
if ~exist('namestr') || isempty(namestr)
namestr= [num2str(i) '/' num2str(length(img1all)) ' - ' fi];
end
overlay(img1,img2,namestr)
end
function overlay(img1,img2,namestr)
displaykey2(img1,img2);
delete(findobj(gcf,'tag','pb'))
%% colorize 'Reorient images...'-BUTTON
try
hgr=findobj(0,'tag','Graphics');
hRI=findobj(hgr,'string','Reorient images...');
set(hRI,'BackgroundColor',[ 1.0000 0.6941 0.3922]);
end
% [pa fi]=fileparts(t);
units=get(gcf,'units');
% namestr
% message=[['bgrIMG: ' img1 ] (char(10)) ['ovlIMG: ' img2 ]]
set(gcf,'units','normalized');
pb= uicontrol('Style', 'push','units','normalized',...
'String','' ,...%namestr,...
'Position', [.1 .95 .8 .05],'backgroundcolor',[1 1 1],'tag','pb','fontsize',9);
set(pb,'HorizontalAlignment','left');
r= ['<HTML>'...<b>
'<FONT COLOR="black">dooftag1' '<br>'... '<br style="margin: 2px">'...
'<FONT COLOR="blue">dooftag2' '<br>'...
'<FONT COLOR="red">dooftag3' ...
'</HTML>'
];
if ~exist('namestr') && isempty(namestr);
namestr='';
end
r=strrep(r,'dooftag1', namestr);
r=strrep(r,'dooftag2', ['bgrIMG: ' img1 ]);
r=strrep(r,'dooftag3', ['ovlIMG: ' img2 ]);
set(pb,'string',r);
if 0 ; delete(pb) ; end
if 1
if 0
%% 'go to NUM'
pb= uicontrol('Style', 'text', 'String', 'go to NUM',...
'Position', [300 530 50 25],'backgroundcolor',[1 1 1],'tag','pb','fontsize',9)
% set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
pb= uicontrol('Style', 'edit', 'String', '',...
'Position', [300 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,3}) ;
% set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% previous
pb= uicontrol('Style', 'pushbutton', 'String', 'previous',...
'Position', [350 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,-1}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% next
pb= uicontrol('Style', 'pushbutton', 'String', 'next',...
'Position', [400 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,1}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
end
bgcol=[ 0.9412 0.9412 0.9412];
xx=.7065;
yy=.55;
sizbut=[.13 .025];
if 0
%% 'reorientIMAGE'
pb= uicontrol('Style', 'pushbutton', 'String', 'reorientIMAGE',...
'Position', [xx yy sizbut],'units','normalized','backgroundcolor',[0 1 0],'tag','pb','fontsize',9);
iptaddcallback(pb, 'callback', 'spm_image(''reorient'')') ;
iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
iptaddcallback(pb, 'callback', 'drawnow;overlay(img1,img2,namestr)') ;
% iptaddcallback(pb, 'callback', 'uiresume(gcbf)') ;
end
%% cancel/END
pb= uicontrol('Style', 'pushbutton', 'String', 'END',...
'Position', [xx+sizbut(1) yy sizbut],'units','normalized',...%'Position', [450 500 50 40],...
'backgroundcolor',[ 1 .4 .4],'tag','pb','fontsize',9,...
'callback', {@task,nan},...
'tooltip','end the "BUSY mode" (no other changes ..)"') ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% HELP
pb= uicontrol('Style', 'pushbutton', 'String', '?',...
'Position', [xx+sizbut(1)*2 yy sizbut(1)/3 sizbut(2) ],'units','normalized',...%'Position', [450 500 50 40],...
'backgroundcolor',[1.0000 0.9490 0.8667],'tag','pb','fontsize',12,...
'callback', {@task,100},...
'tooltip','show shortcuts') ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% 2nd LINE buttons
%% 'sliceview'
pb= uicontrol('Style', 'pushbutton', 'String', 'sView',...
'Position',[xx yy-sizbut(2) sizbut(1) sizbut(2)],'units','normalized',...
'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,4},...
'tooltip','show slices [labs] has to be installed') ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% openDIR
pb= uicontrol('Style', 'pushbutton', 'String', 'openDIR',...
'Position', [xx+sizbut(1) yy-sizbut(2) sizbut(1) sizbut(2)],'units','normalized',...
'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,2},...
'tooltip','open folder') ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% info
pb= uicontrol('Style', 'text', 'String', 'blalbla','units','normalized',...
'Position', [xx yy-sizbut(2)*2 2*sizbut(1) sizbut(2)],...
'backgroundcolor',[.8 .8 .8],'tag','pb','fontsize',7,'userdata','myinfo' );
% iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
try
set(pb,'tooltip',[['bgrIMG: ' img1 ] (char(10)) ['ovlIMG: ' img2 ]]);
end
end
set(gcf,'units',units);
hfig=findobj(0,'tag','Graphics');
ca=findobj(hfig,'string','Reorient images...');
iptaddcallback(ca, 'callback', 'uiresume(gcf)') ;
displaykey(2)
drawnow
pos=spm_orthviews2('Pos');
spm_orthviews2('Reposition',pos);
drawnow
ax=findobj(gcf,'type','axes');
set(gcf,'CurrentObject',1);
% set(ax,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
% set(0,'')
uiwait(gcf);
function task(ho,cbd, code)
global ovl
if code==100%help
evnt.Character= 'h';
evnt.Modifier={};
evnt.Key= 'h';
keyb(1,evnt);
elseif code==1%next
if ovl.n+1<=length(ovl.img1)
ovl.n=ovl.n+1;
end
uiresume(gcf)
elseif code==-1%previous
if ovl.n-1>=1
ovl.n=ovl.n-1;
end
uiresume(gcf)
elseif isnan(code); %cancel
ovl.doloop=0;
try
hgr=findobj(0,'tag','Graphics');
delete(findobj(hgr,'tag','pb'));
end
uiresume(gcf)
elseif code==2%openDIR
% uiresume(gcf)
thispath=fileparts(ovl.img1{ovl.n});
if isempty(thispath)
thispath=pwd;
end
str=['!explorer ' thispath ];
eval(str);
elseif code==3%openDIR
num=get(ho,'string');
try
num=str2num(num)
if num<=length(ovl.img1) && num>=1
ovl.n= num;
end
set(ho,'string','');
uiresume(gcf)
end
elseif code==4%pslices
f2=ovl.img1{ovl.n};
f1=ovl.img2;
c1=gray;
c2=autumn;
% cmap=[c1(33:end,:); c2(1:32,:) ]
% cmap=[c1(33:end,:); flipud(c2(1:2:end,:)) ]
cmap=[c1(33:end,:); repmat([1 0 0],32,1) ];
add=[];
add.transparency=.6 %overlay transparency
add.anatomicalImg=f2
pslices(f1,[],[-8:1:8],[],'axial',add) ;
end
set(gcf,'CurrentObject',1);
|
github
|
philippboehmsturm/antx-master
|
spm_image2.m
|
.m
|
antx-master/mritools/displaykey/spm_image2.m
| 23,612 |
utf_8
|
a789d28249f3ecdab3d96e985ff422b5
|
function spm_image(op,varargin)
% image and header display
% FORMAT spm_image
%_______________________________________________________________________
%
% spm_image is an interactive facility that allows orthogonal sections
% from an image volume to be displayed. Clicking the cursor on either
% of the three images moves the point around which the orthogonal
% sections are viewed. The co-ordinates of the cursor are shown both
% in voxel co-ordinates and millimeters within some fixed framework.
% The intensity at that point in the image (sampled using the current
% interpolation scheme) is also given. The position of the crosshairs
% can also be moved by specifying the co-ordinates in millimeters to
% which they should be moved. Clicking on the horizontal bar above
% these boxes will move the cursor back to the origin (analogous to
% setting the crosshair position (in mm) to [0 0 0]).
%
% The images can be re-oriented by entering appropriate translations,
% rotations and zooms into the panel on the left. The transformations
% can then be saved by hitting the ``Reorient images...'' button. The
% transformations that were applied to the image are saved to the
% ``.mat'' files of the selected images. The transformations are
% considered to be relative to any existing transformations that may be
% stored in the ``.mat'' files. Note that the order that the
% transformations are applied in is the same as in ``spm_matrix.m''.
%
% The ``Reset...'' button next to it is for setting the orientation of
% images back to transverse. It retains the current voxel sizes,
% but sets the origin of the images to be the centre of the volumes
% and all rotations back to zero.
%
% The right panel shows miscellaneous information about the image.
% This includes:
% Dimensions - the x, y and z dimensions of the image.
% Datatype - the computer representation of each voxel.
% Intensity - scalefactors and possibly a DC offset.
% Miscellaneous other information about the image.
% Vox size - the distance (in mm) between the centres of
% neighbouring voxels.
% Origin - the voxel at the origin of the co-ordinate system
% DIr Cos - Direction cosines. This is a widely used
% representation of the orientation of an image.
%
% There are also a few options for different resampling modes, zooms
% etc. You can also flip between voxel space (as would be displayed
% by Analyze) or world space (the orientation that SPM considers the
% image to be in). If you are re-orienting the images, make sure that
% world space is specified. Blobs (from activation studies) can be
% superimposed on the images and the intensity windowing can also be
% changed.
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_image.m 904 2007-09-03 17:41:15Z john $
%
% Modified for animal sized brains and allowed overlays to be shown
% simultaneous to the main image. sjs.
%
global st
if nargin == 0,
spm('FnUIsetup','Display',0);
spm('FnBanner',mfilename,'$Rev: 904 $');
spm_help('!ContextHelp',[mfilename,'.m']);
% get the image's filename {P}
%-----------------------------------------------------------------------
P = spm_select(1,'image','Select image',[],0);
spm_image('init',P);
return;
end;
try
if ~strcmp(op,'init') && ~strcmp(op,'reset') && isempty(st.vols{1})
my_reset; warning('Lost all the image information');
return;
end;
catch
end
if strcmp(op,'repos'),
% The widgets for translation rotation or zooms have been modified.
%-----------------------------------------------------------------------
fg = spm_figure('Findwin','Graphics');
set(fg,'Pointer','watch');
i = varargin{1};
st.B(i) = eval(get(gco,'String'),num2str(st.B(i)));
set(gco,'String',st.B(i));
st.vols{1}.premul = spm_matrix(st.B);
% spm_orthviews2('MaxBB');
spm_image('zoom_in');
spm_image('update_info');
set(fg,'Pointer','arrow');
return;
end;
if strcmp(op,'shopos'),
% The position of the crosshairs has been moved.
%-----------------------------------------------------------------------
if isfield(st,'mp'),
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp),
set(st.mp,'String',sprintf('%.1f %.1f %.1f',spm_orthviews2('pos')));
pos = spm_orthviews2('pos',1);
set(st.vp,'String',sprintf('%.1f %.1f %.1f',pos));
set(st.in,'String',sprintf('%g',spm_sample_vol(st.vols{1},pos(1),pos(2),pos(3),st.hld)));
else
st.Callback = ';';
st = rmfield(st,{'mp','vp','in'});
end;
else
st.Callback = ';';
end;
return;
end;
if strcmp(op,'setposmm'),
% Move the crosshairs to the specified position
%-----------------------------------------------------------------------
if isfield(st,'mp'),
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp),
pos = sscanf(get(st.mp,'String'), '%g %g %g');
if length(pos)~=3,
pos = spm_orthviews2('pos');
end;
spm_orthviews2('Reposition',pos);
end;
end;
return;
end;
if strcmp(op,'setposvx'),
% Move the crosshairs to the specified position
%-----------------------------------------------------------------------
if isfield(st,'mp'),
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.vp),
pos = sscanf(get(st.vp,'String'), '%g %g %g');
if length(pos)~=3,
pos = spm_orthviews2('pos',1);
end;
tmp = st.vols{1}.premul*st.vols{1}.mat;
pos = tmp(1:3,:)*[pos ; 1];
spm_orthviews2('Reposition',pos);
end;
end;
return;
end;
if strcmp(op,'addblobs'),
% Add blobs to the image - in full colour
spm_figure('Clear','Interactive');
nblobs = spm_input('Number of sets of blobs',1,'1|2|3|4|5|6',[1 2 3 4 5 6],1);
for i=1:nblobs,
[SPM,VOL] = spm_getSPM;
c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
spm_orthviews2('addcolouredblobs',1,VOL.XYZ,VOL.Z,VOL.M,colours(c,:));
set(st.blobber,'String','Remove Blobs','Callback','spm_image(''rmblobs'');');
end;
spm_orthviews2('addcontext',1);
spm_orthviews2('Redraw');
end;
if strcmp(op,'rmblobs'),
% Remove all blobs from the images
spm_orthviews2('rmblobs',1);
set(st.blobber,'String','Add Blobs','Callback','spm_image(''addblobs'');');
spm_orthviews2('rmcontext',1);
spm_orthviews2('Redraw');
end;
if strcmp(op,'window'),
op = get(st.win,'Value');
if op == 1,
spm_orthviews2('window',1);
else
spm_orthviews2('window',1,spm_input('Range','+1','e','',2));
end;
end;
if strcmp(op,'reorient'),
% Time to modify the ``.mat'' files for the images.
% I hope that giving people this facility is the right thing to do....
%-----------------------------------------------------------------------
mat = spm_matrix(st.B);
if det(mat)<=0
spm('alert!','This will flip the images',mfilename,0,1);
end;
P = spm_select(Inf, 'image','Images to reorient');
Mats = zeros(4,4,size(P,1));
spm_progress_bar('Init',size(P,1),'Reading current orientations',...
'Images Complete');
for i=1:size(P,1),
Mats(:,:,i) = spm_get_space(P(i,:));
spm_progress_bar('Set',i);
end;
spm_progress_bar('Init',size(P,1),'Reorienting images',...
'Images Complete');
for i=1:size(P,1),
spm_get_space(P(i,:),mat*Mats(:,:,i));
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8,
spm_image('init',st.vols{1}.fname);
end;
return;
end;
if strcmp(op,'resetorient'),
% Time to modify the ``.mat'' files for the images.
% I hope that giving people this facility is the right thing to do....
%-----------------------------------------------------------------------
P = spm_select(Inf, 'image','Images to reset orientation of');
spm_progress_bar('Init',size(P,1),'Resetting orientations',...
'Images Complete');
for i=1:size(P,1),
V = spm_vol(deblank(P(i,:)));
M = V.mat;
vox = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vox(1) = -vox(1); end;
orig = (V.dim(1:3)+1)/2;
off = -vox.*orig;
M = [vox(1) 0 0 off(1)
0 vox(2) 0 off(2)
0 0 vox(3) off(3)
0 0 0 1];
spm_get_space(P(i,:),M);
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8,
spm_image('init',st.vols{1}.fname);
end;
return;
end;
if strcmp(op,'update_info'),
% Modify the positional information in the right hand panel.
%-----------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
set(st.posinf.z,'String', sprintf('%.3g x %.3g x %.3g', Z));
O = mat\[0 0 0 1]'; O=O(1:3)';
set(st.posinf.o, 'String', sprintf('%.3g %.3g %.3g', O));
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m1, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m2, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m3, 'String', tmp2);
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
if sum(tmp(:).^2)>1e-8,
set(st.posinf.w, 'String', 'Warning: shears involved');
else
set(st.posinf.w, 'String', '');
end;
return;
end;
if strcmp(op,'reset'),
my_reset;
end;
global defaults;
if strcmp(op,'zoom_in'),
op = get(st.zoomer,'Value');
if op==1,
scl = 1;
if(~isempty('defaults'))
if(isfield(defaults,'animal'))
scl = defaults.animal.scale;
end
end
spm_orthviews2('resolution',scl);
spm_orthviews2('MaxBB');
else
vx = sqrt(sum(st.Space(1:3,1:3).^2));
vx = vx.^(-1);
pos = spm_orthviews2('pos');
pos = st.Space\[pos ; 1];
pos = pos(1:3)';
if op == 2, st.bb = [pos-10*vx ; pos+10*vx] ; spm_orthviews2('resolution',0.125);
elseif op == 3, st.bb = [pos-5*vx ; pos+5*vx] ; spm_orthviews2('resolution',0.0625);
elseif op == 4, st.bb = [pos-1*vx ; pos+1*vx] ; spm_orthviews2('resolution',0.03125);
elseif op == 5, st.bb = [pos-0.4*vx ; pos+0.4*vx] ; spm_orthviews2('resolution',0.015625);
else st.bb = [pos- 0.2*vx ; pos+ 0.2*vx] ; spm_orthviews2('resolution',.00728125);
end;
end;
return;
end;
%=============================0
if strcmp(op,'setparams')
lab=varargin(1:2:end);
val=varargin(2:2:end);
iex=find(strcmp(lab,'col'));
if ~isempty(iex); st.overlay.col=val{iex}; end
iex=find(strcmp(lab,'wt'));
if ~isempty(iex); st.overlay.wt=val{iex}; end
spm_orthviews2('Redraw');
end
if strcmp(op,'addoverlay2')
t=varargin{1};
st.overlay = spm_vol(t);
spm_orthviews2('Redraw');
end
%===============================
if strcmp(op,'addoverlay')
% put an overlay on the image
% t = V:\spmmouse\tpm\output.img,1
[t,sts]=spm_select(1,'image','Select overlay image',[],pwd);
if(sts==0) return; end;
st.overlay = spm_vol(t);
spm_orthviews2('Redraw');
end
if strcmp(op,'rmoverlay')
% remove overlay
if(isfield(st,'overlay'))
rmfield(st,'overlay');
spm_orthviews2('Redraw');
end
end
if strcmp(op,'init'),
fg = spm_figure('GetWin','Graphics');
if isempty(fg), error('Can''t create graphics window'); end
spm_figure('Clear','Graphics');
P = varargin{1};
if ischar(P), P = spm_vol(P); end;
P = P(1);
spm_orthviews2('Reset');
spm_orthviews2('Image', P, [0.0 0.45 1 0.55]);
if isempty(st.vols{1}), return; end;
spm_orthviews2('MaxBB');
global defaults
scl = 1;
if(~isempty('defaults'))
if(isfield(defaults,'animal'))
scl = defaults.animal.scale;
end
end
spm_orthviews2('resolution',scl);
st.callback = 'spm_image(''shopos'');';
st.B = [0 0 0 0 0 0 1 1 1 0 0 0];
% locate Graphics window and clear it
%-----------------------------------------------------------------------
WS = spm('WinScale');
% Widgets for re-orienting images.
%-----------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');
uicontrol(fg,'Style','Text', 'Position',[75 220 100 016].*WS,'String','right {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 200 100 016].*WS,'String','foward {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 180 100 016].*WS,'String','up {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 160 100 016].*WS,'String','pitch {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 140 100 016].*WS,'String','roll {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 120 100 016].*WS,'String','yaw {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 100 100 016].*WS,'String','resize {x}');
uicontrol(fg,'Style','Text', 'Position',[75 80 100 016].*WS,'String','resize {y}');
uicontrol(fg,'Style','Text', 'Position',[75 60 100 016].*WS,'String','resize {z}');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',1)','Position',[175 220 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',2)','Position',[175 200 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',3)','Position',[175 180 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',4)','Position',[175 160 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',5)','Position',[175 140 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',6)','Position',[175 120 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',7)','Position',[175 100 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',8)','Position',[175 80 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',9)','Position',[175 60 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','Pushbutton','String','Reorient images...','Callback','spm_image(''reorient'')',...
'Position',[70 35 125 020].*WS,'ToolTipString','modify position information of selected images');
uicontrol(fg,'Style','Pushbutton','String','Reset...','Callback','spm_image(''resetorient'')',...
'Position',[195 35 55 020].*WS,'ToolTipString','reset orientations of selected images');
% Crosshair position
%-----------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[70 250 180 90].*WS);
uicontrol(fg,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');
uicontrol(fg,'Style','PushButton', 'Position',[75 316 170 006].*WS,...
'Callback','spm_orthviews2(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...
% 'Callback','spm_orthviews2(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
uicontrol(fg,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');
uicontrol(fg,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');
uicontrol(fg,'Style','Text', 'Position',[75 255 65 020].*WS,'String','Intensity:');
st.mp = uicontrol(fg,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');
st.vp = uicontrol(fg,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');
st.in = uicontrol(fg,'Style','Text', 'Position',[140 255 85 020].*WS,'String','');
% General information
%-----------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[305 25 280 325].*WS);
uicontrol(fg,'Style','Text','Position' ,[310 330 50 016].*WS,...
'HorizontalAlignment','right', 'String', 'File:');
uicontrol(fg,'Style','Text','Position' ,[360 330 210 016].*WS,...
'HorizontalAlignment','left', 'String', spm_str_manip(st.vols{1}.fname,'k25'),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 310 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dimensions:');
uicontrol(fg,'Style','Text','Position' ,[410 310 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%d x %d x %d', st.vols{1}.dim(1:3)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 290 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Datatype:');
uicontrol(fg,'Style','Text','Position' ,[410 290 160 016].*WS,...
'HorizontalAlignment','left', 'String', spm_type(st.vols{1}.dt(1)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 270 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Intensity:');
str = 'varied';
if size(st.vols{1}.pinfo,2) == 1,
if st.vols{1}.pinfo(2),
str = sprintf('Y = %g X + %g', st.vols{1}.pinfo(1:2)');
else
str = sprintf('Y = %g X', st.vols{1}.pinfo(1)');
end;
end;
uicontrol(fg,'Style','Text','Position' ,[410 270 160 016].*WS,...
'HorizontalAlignment','left', 'String', str,'FontWeight','bold');
if isfield(st.vols{1}, 'descrip'),
uicontrol(fg,'Style','Text','Position' ,[310 250 260 016].*WS,...
'HorizontalAlignment','center', 'String', st.vols{1}.descrip,'FontWeight','bold');
end;
% Positional information
%-----------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
uicontrol(fg,'Style','Text','Position' ,[310 210 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Vox size:');
st.posinf = struct('z',uicontrol(fg,'Style','Text','Position' ,[410 210 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g x %.3g x %.3g', Z),'FontWeight','bold'));
O = mat\[0 0 0 1]'; O=O(1:3)';
uicontrol(fg,'Style','Text','Position' ,[310 190 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Origin:');
st.posinf.o = uicontrol(fg,'Style','Text','Position' ,[410 190 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g %.3g %.3g', O),'FontWeight','bold');
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
uicontrol(fg,'Style','Text','Position' ,[310 170 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dir Cos:');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m1 = uicontrol(fg,'Style','Text','Position' ,[410 170 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m2 = uicontrol(fg,'Style','Text','Position' ,[410 150 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m3 = uicontrol(fg,'Style','Text','Position' ,[410 130 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
st.posinf.w = uicontrol(fg,'Style','Text','Position' ,[310 110 260 016].*WS,...
'HorizontalAlignment','center', 'String', '','FontWeight','bold');
if sum(tmp(:).^2)>1e-8,
set(st.posinf.w, 'String', 'Warning: shears involved');
end;
% Assorted other buttons.
%-----------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[310 30 270 100].*WS); % changed 70 to 110 to accommodate new button for overlays
st.zoomer = uicontrol(fg,'Style','popupmenu' ,'Position',[315 105 125 20].*WS,...
'String',char('Full Volume','20x20x20mm','10x10x10mm','2x2x2mm','800x800x800um','400x400x400um'),...
'Callback','spm_image(''zoom_in'')','ToolTipString','zoom in by different amounts');
c = 'if get(gco,''Value'')==1, spm_orthviews2(''Space''), else, spm_orthviews2(''Space'', 1);end;spm_image(''zoom_in'')';
uicontrol(fg,'Style','popupmenu' ,'Position',[315 82 125 20].*WS,...
'String',char('World Space','Voxel Space'),...
'Callback',c,'ToolTipString','display in aquired/world orientation');
c = 'if get(gco,''Value'')==1, spm_orthviews2(''Xhairs'',''off''), else, spm_orthviews2(''Xhairs'',''on''); end;';
uicontrol(fg,'Style','togglebutton','Position',[450 95 125 20].*WS,...
'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');
uicontrol(fg,'Style','popupmenu' ,'Position',[450 75 125 20].*WS,...
'String',char('NN interp','bilin interp','sinc interp'),...
'Callback','tmp_ = [0 1 -4];spm_orthviews2(''Interp'',tmp_(get(gco,''Value'')))',...
'Value',2,'ToolTipString','interpolation method for displaying images');
st.win = uicontrol(fg,'Style','popupmenu','Position',[315 60 125 20].*WS,...
'String',char('Auto Window','Manual Window'),'Callback','spm_image(''window'');','ToolTipString','range of voxel intensities displayed');
% uicontrol(fg,'Style','pushbutton','Position',[315 35 125 20].*WS,...
% 'String','Window','Callback','spm_image(''window'');','ToolTipString','range of voxel intensities % displayed');
%added by sjs - overlay image
uicontrol(fg,'Style','pushbutton','Position',[315 35 125 20].*WS,...
'String','Add Overlay',...
'Callback','spm_image(''addoverlay'');',...
'ToolTipString','Add overlay image');
st.blobber = uicontrol(fg,'Style','pushbutton','Position',[450 35 125 20].*WS,...
'String','Add Blobs','Callback','spm_image(''addblobs'');','ToolTipString','superimpose activations');
end;
return;
function my_reset
spm_orthviews2('reset');
spm_figure('Clear','Graphics');
return;
|
github
|
philippboehmsturm/antx-master
|
dispoverlay2.m
|
.m
|
antx-master/mritools/displaykey/dispoverlay2.m
| 4,799 |
utf_8
|
c7a17e8fbc5c1d90a1a11a783e1f7ece
|
function dispoverlay2(paths,img2)
% FOR MULTIPLE PATHS
% dispoverlay2(paths,img2 )
% paths: cell of paths
% img2 : referenceImage
global ovl ;
ovl.paths=paths;
ovl.img2 =img2 ;
ovl.n =1 ;
ovl.doloop =1;
%====================================
while ovl.doloop==1
% for i=6:size(paths,1)
i=ovl.n ;
[t] = spm_select('FPList',[paths{i} ],'^s.*nii$')
[pa fi fmt]=fileparts(t);
cd(pa)
img1=char(t);
ovl.img1=[fi fmt];
% img2= 'V:\mritools\tpm\pgreyr62.nii'
namestr= [num2str(i) '/' num2str(size(paths,1)) ' - ' fi];
overlay(img1,img2,namestr)
end
function overlay(img1,img2,namestr)
displaykey2(img1,img2);
delete(findobj(gcf,'tag','pb'))
% [pa fi]=fileparts(t);
pb= uicontrol('Style', 'text', 'String',...
namestr,...
'Position', [350 600 200 20],'backgroundcolor',[0 1 1],'tag','pb','fontsize',9);
if 1
bgcol=[ 0.9412 0.9412 0.9412];
%% 'reorientIMAGE'
pb= uicontrol('Style', 'pushbutton', 'String', 'reorientIMAGE',...
'Position', [440 540 80 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9);
iptaddcallback(pb, 'callback', 'spm_image(''reorient'')') ;
iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
iptaddcallback(pb, 'callback', 'drawnow;overlay(img1,img2,namestr)') ;
% iptaddcallback(pb, 'callback', 'uiresume(gcbf)') ;
%% 'sliceview'
pb= uicontrol('Style', 'pushbutton', 'String', 'sView',...
'Position', [520 540 80 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,4}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% 'go to NUM'
pb= uicontrol('Style', 'text', 'String', 'go to NUM',...
'Position', [300 530 50 25],'backgroundcolor',[1 1 1],'tag','pb','fontsize',9)
% set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
pb= uicontrol('Style', 'edit', 'String', '',...
'Position', [300 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,3}) ;
% set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% previous
pb= uicontrol('Style', 'pushbutton', 'String', 'previous',...
'Position', [350 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,-1}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% next
pb= uicontrol('Style', 'pushbutton', 'String', 'next',...
'Position', [400 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,1}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% cancel
pb= uicontrol('Style', 'pushbutton', 'String', 'cancel',...
'Position', [450 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,nan}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
%% openDIR
pb= uicontrol('Style', 'pushbutton', 'String', 'openDIR',...
'Position', [500 500 50 40],'backgroundcolor',bgcol,'tag','pb','fontsize',9,...
'callback', {@task,2}) ;
set(pb,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
end
hfig=findobj(0,'tag','Graphics');
ca=findobj(hfig,'string','Reorient images...');
iptaddcallback(ca, 'callback', 'uiresume(gcf)') ;
displaykey(2)
drawnow
pos=spm_orthviews2('Pos');
spm_orthviews2('Reposition',pos);
drawnow
ax=findobj(gcf,'type','axes');
set(gcf,'CurrentObject',1);
% set(ax,'keypressfcn','eval(get(gcbf,''keypressfcn''))');
% set(0,'')
uiwait(gcf);
function task(ho,cbd, code)
global ovl
if code==1%next
if ovl.n+1<=length(ovl.paths)
ovl.n=ovl.n+1;
end
uiresume(gcf)
elseif code==-1%previous
if ovl.n-1>=1
ovl.n=ovl.n-1;
end
uiresume(gcf)
elseif isnan(code); %cancel
ovl.doloop=0;
uiresume(gcf)
elseif code==2%openDIR
% uiresume(gcf)
str=['!explorer ' ovl.paths{ovl.n} ];
eval(str);
elseif code==3%openDIR
num=get(ho,'string');
try
num=str2num(num)
if num<=length(ovl.paths) && num>=1
ovl.n= num;
end
set(ho,'string','');
uiresume(gcf)
end
elseif code==4%pslices
f2=fullfile( ovl.paths{ovl.n}, ovl.img1);
f1=ovl.img2;
c1=gray;
c2=autumn;
% cmap=[c1(33:end,:); c2(1:32,:) ]
% cmap=[c1(33:end,:); flipud(c2(1:2:end,:)) ]
cmap=[c1(33:end,:); repmat([1 0 0],32,1) ];
add=[];
add.transparency=.6 %overlay transparency
add.anatomicalImg=f2
pslices(f1,[],[-8:1:8],'cmap','axial',add) ;
end
set(gcf,'CurrentObject',1);
|
github
|
philippboehmsturm/antx-master
|
Kopie von keyb.m
|
.m
|
antx-master/mritools/displaykey/Kopie von keyb.m
| 12,469 |
utf_8
|
70d6eccf6e42cba7b93669fe43cbd6dc
|
function keyb(src,evnt)
if nargin==0
helphelp;
return
end
if length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & strcmp(evnt.Key, 'control')
return
end
if length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'shift') & strcmp(evnt.Key, 'shift')
return
end
box=getappdata(gcf,'box');
if evnt.Character == 'h'
helphelp
elseif evnt.Character == 'd'
spm_image2('setparams','col',box.col,'wt',box.wt);
elseif evnt.Character == 'f' %flipdim
global st
if isfield(st.overlay,'orig')==0;
st.overlay.orig=st.overlay
end
prompt = {'order of dims,use[-] to flip dir of this dim, e.g. [1 3 -2], [] for orig. settup '};
dlg_title = 'Input for peaks function';
num_lines = 1;
def = {num2str([1 2 3])};
answer = inputdlg(prompt,dlg_title,num_lines,def);
if isempty(char(answer)); %orig settup
st.overlay= st.overlay.orig;
spm_orthviews2('Redraw');
return
elseif length(str2num(char(answer)))==3
vc=[str2num(char(answer)) ];
flips=sign(vc);
perms=abs(vc);
v=spm_vol(st.overlay.fname)
d=spm_read_vols(v); % r
isflip=find(flips==-1);
dia=diag(v.mat(1:3,1:3))
dc=zeros(3,1);
for i=1:length(isflip)
vsiz=dia(isflip(i))
a=[vsiz:vsiz:vsiz*(size(d,isflip(i))+1)]+v.mat(isflip(i),4);
%a=[0:vsiz:vsiz*(size(d,isflip)-1)]+v.mat(isflip(i),4);
dc(isflip(i))=-[a([ end]) ] ;
d=flipdim(d,isflip(i));
end
%permute
d=permute(d,[perms]);
% dsh=round(size(d)/2) ;
% subplot(3,3,7); imagesc( squeeze(d(dsh(1),: ,:) ) ) ;title(['2 3']);
% subplot(3,3,8); imagesc( squeeze(d(: ,dsh(2),:) ) ) ; title(['1 3']);
% subplot(3,3,9); imagesc( squeeze(d(: ,: ,dsh(3)) ) ); title(['1 2']);
%
%
v2=v;
[pa fi fmt]=fileparts(v2.fname);
v2.fname=fullfile(pa ,['p' fi fmt]);
v2.dim=size(d);
mat=v2.mat;
dia=diag(mat);
mat(1:4+1:end)=dia([perms 4]);
orig=mat(1:3,4);
orig(find(dc~=0) )=dc(find(dc~=0));
% orig=orig.*flips'
% orig(2)=orig(2)+3
orig=orig(perms);
mat(:,4)=[orig; 1];
% mat(3,4)=mat(3,4)+2
v2.mat=mat;
spm_write_vol(v2, d); % write data to an image file.
backup= st.overlay.orig;
st.overlay =v2;
st.overlay.col=backup.col;
st.overlay.wt=backup.wt;
st.overlay.orig =backup;
spm_orthviews2('Redraw');
end
% v.mat
%
% ans =
%
% 0.0699 0 0 -5.9951
% 0 0.0700 0 -9.5589
% 0 0 0.0700 -8.7410
% 0 0 0 1.0000
%
% v2.mat
%
% ans =
%
% 0.0699 0 0 -5.9951
% 0 0.0700 0 -8.7410
% 0 0 0.0700 -6.5589
% 0 0 0 1.0000
%
elseif (strcmp(evnt.Character, '+') | strcmp(evnt.Character, '-')) && isempty(evnt.Modifier)
global st
stp=.1;
if evnt.Character == '-'
stp=-stp;
end
try
st.overlay.wt=st.overlay.wt+stp;
catch
st.overlay.wt=st.overlay.wt+stp;
end
% if st.overlay.wt>1; st.overlay.wt=1; end
if st.overlay.wt<0; st.overlay.wt=0; end
spm_image2('setparams','wt',st.overlay.wt) ;
box=getappdata(gcf,'box');
box.wt=st.overlay.wt;
setappdata(gcf,'box',box);
% elseif (evnt.Character == '+' || evnt.Character=='-' ) && strcmp(evnt.Modifier{:},'control')
% global st
% stp=.1;
% if evnt.Character == '-'
% stp=-stp;
% end
%
% try
% st.overlay.wt=st.overlay.wt+stp;
% catch
% st.overlay.wt=st.overlay.wt+stp;
% end
% if st.overlay.wt>1; st.overlay.wt=1; end
% if st.overlay.wt<0; st.overlay.wt=0; end
% spm_image2('setparams','wt',st.overlay.wt) ;
% 'jjjjj'
elseif evnt.Key == '1'
prompt = {'Enter StepSize-->Translation:','Enter StepSize-->Rotation:'};
dlg_title = 'Input for peaks function';
num_lines = 1;
def = {num2str(box.stpshift),num2str(box.stpangle)};
answer = inputdlg(prompt,dlg_title,num_lines,def);
box.stpshift=str2num(answer{1});
box.stpangle=str2num(answer{2});
setappdata(gcf,'box',box);
elseif evnt.Key == '2'
if box.isBackgroundOnly==0;
box.isBackgroundOnly=1;
spm_image2('setparams','col',box.col,'wt',0);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
else
box.isBackgroundOnly=0;
spm_image2('setparams','col',box.col,'wt',box.wt);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
end
elseif evnt.Key == '3'
if box.isOverlayOnly==0;
box.isOverlayOnly=1;
spm_image2('setparams','col',box.col,'wt',5);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
else
box.isOverlayOnly=0;
spm_image2('setparams','col',box.col,'wt',box.wt);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
end
elseif evnt.Key == '4'
if box.isOverlayOnly==0;
box.isOverlayOnly=1;
spm_image2('setparams','col',box.col,'wt',5);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
else
box.isOverlayOnly=0;
spm_image2('setparams','col',box.col,'wt',0);
setappdata(gcf,'box',box);
getappdata(gcf,'box');
end
elseif evnt.Character == 't'
global st
r1=st.vols{1};
r2=st.overlay;
try
adjuest=round(-(r1.dim/2)'.*diag(r1.mat(1:3,1:3)));
catch
disp('no overlay selected..');
return
end
for i=1:3
hfig=findobj(0,'tag','Graphics');
ex=findobj(hfig,'callback',['spm_image(''repos'',' num2str(i) ')' ]);
set(hfig,'CurrentObject',ex );
set(ex,'string',num2str(adjuest(i)) );
hgfeval(get(ex,'callback'));
end
spm_orthviews2('Redraw');
elseif evnt.Character == 'c'
col=colorui;
spm_image2('setparams','col',col) ;
elseif strcmp(evnt.Key , 'o' ) & length(evnt.Modifier) == 0
spm_image2('addoverlay')
spm_image2('setparams','col',box.col,'wt',box.wt);
global st
name2save=st.overlay.fname;
tx=textread(which('keyb.m'),'%s','delimiter','\n');
i1=find(strcmp(tx,'%% pprivate-path'))+1;
i2=find(strcmp(tx,'%% pprivate-pathEND'))-1;
paths =tx(i1:i2);
paths2=[paths; {['% ' name2save ]}];
iredun=find(strcmp(paths2,paths2(end)));
if length(iredun)>1
paths2(iredun(2:end))=[];
end
tx2=[tx(1:i1-1); paths2; tx(i2+1:end)] ;
fid = fopen([ 'muell.m' ],'w','n');
for i=1:size(tx2,1)
dumh=char( (tx2(i,:)) );
fprintf(fid,'%s\n',dumh);
end
fclose(fid);
elseif strcmp(evnt.Key , 'o' ) & strcmp(evnt.Modifier{:},'shift') & length(evnt.Modifier) == 1
tx=textread(which('keyb.m'),'%s','delimiter','\n');
i1=find(strcmp(tx,'%% pprivate-path'))+1
i2=find(strcmp(tx,'%% pprivate-pathEND'))-1
paths=tx(i1:i2);
paths=regexprep(paths,{'%','''' ,' '}, {'','' ,''});
if isempty(char(paths))
disp('no paths in memory');
return
end
str =paths;
[s,v] = listdlg('PromptString','Select a file:',...
'SelectionMode','single',...
'ListString',str)
if v==0; return; end
img2overlay=paths(v)
global st
st.overlay=spm_vol(char(img2overlay));
spm_orthviews2('Redraw');
elseif evnt.Character == 'u'
spm_orthviews2('Redraw');
% elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & evnt.Key == 't'
% 'a'
elseif strcmp(evnt.Key,'leftarrow') && isempty(evnt.Modifier)
do('l', 'spm_image(''repos'',1)' , box.stpshift )
elseif strcmp(evnt.Key,'rightarrow') && isempty(evnt.Modifier)
do('r', 'spm_image(''repos'',1)' ,-box.stpshift )
elseif strcmp(evnt.Key,'uparrow') && isempty(evnt.Modifier)
do('l', 'spm_image(''repos'',3)' ,-box.stpshift )
elseif strcmp(evnt.Key,'downarrow') && isempty(evnt.Modifier)
do('r', 'spm_image(''repos'',3)' , box.stpshift )
elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & strcmp(evnt.Key ,'uparrow' )
do('l', 'spm_image(''repos'',2)' ,-box.stpshift )
elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & strcmp(evnt.Key , 'downarrow' )
do('l', 'spm_image(''repos'',2)' , box.stpshift )
elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & strcmp(evnt.Key ,'leftarrow' )
do('l', 'spm_image(''repos'',2)' ,-box.stpshift )
elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & strcmp(evnt.Key , 'rightarrow' )
do('l', 'spm_image(''repos'',2)' , box.stpshift )
%% ANGLES
elseif strcmp(evnt.Key,'p') && isempty(evnt.Modifier)
do('l', 'spm_image(''repos'',4)' , box.stpangle )
elseif strcmp(evnt.Key , 'p' ) & strcmp(evnt.Modifier{:},'shift') & length(evnt.Modifier) == 1
do('l', 'spm_image(''repos'',4)' , -box.stpangle )
elseif strcmp(evnt.Key,'r') && isempty(evnt.Modifier)
do('l', 'spm_image(''repos'',5)' , -box.stpangle )
elseif strcmp(evnt.Key , 'r' ) & strcmp(evnt.Modifier{:},'shift') & length(evnt.Modifier) == 1
do('l', 'spm_image(''repos'',5)' , box.stpangle )
elseif strcmp(evnt.Key,'y') && isempty(evnt.Modifier)
do('l', 'spm_image(''repos'',6)' , -box.stpangle )
elseif strcmp(evnt.Key , 'y' ) & strcmp(evnt.Modifier{:},'shift') & length(evnt.Modifier) == 1
do('l', 'spm_image(''repos'',6)' , box.stpangle )
end
function helphelp
a={};
a{end+1,1}=' +++DISPLAY SHORTCUTS +++';
a{end+1,1}='[h] shortcuts help';
a{end+1,1}='[o] overlay reference image (userinput/dialog)';
a{end+1,1}='[c] color selection for overlay)';
a{end+1,1}='[d] default settings for color and overlay Transparency)';
a{end+1,1}='[t] initial transpose (rough))';
a{end+1,1}='[u] update overlay)';
a{end+1,1}='[+/-] change transparency of overlay)';
a{end+1,1}=' ';
a{end+1,1}='[arrow up/down] up/down';
a{end+1,1}='[arrow left/right] left/right';
a{end+1,1}='[ctrl]+[arrow up/down] backward/forward';
a{end+1,1}='[ctrl]+[arrow left/right] backward/forward';
a{end+1,1}=' ';
a{end+1,1}='[p] / [ctrl]+[p] -/+pitch';
a{end+1,1}='[r] / [ctrl]+[r] -/+roll';
a{end+1,1}='[y] / [ctrl]+[y] -/+yaw';
a{end+1,1}='[1] change stepSize of translation & rotation';
a{end+1,1}='[2] toggle blendedIMG /Background ';
a{end+1,1}='[3] toggle blendedIMG /Overlay ';
a{end+1,1}='[4] toggle Background /Overlay ';
disp(char(a));
function do(key,callback, stp )
% stp=callback;
e=sort(findobj(gcf,'style','edit'));
% stp
% if strcmp(key,'l')
ex=findobj(gcf,'callback' ,callback);
val0=str2num(get(ex,'string'));
val=val0+stp ;
set(1,'CurrentObject',ex)
% try
set(ex,'string',num2str(val) );
hgfeval(get(ex,'callback'));
spm_orthviews2('Redraw');
% catch
% set(ex,'string',num2str(val0) );
% hgfeval(get(ex,'callback'));
% spm_orthviews2('Redraw');
% end
% end
% e=sort(findobj(gcf,'style','edit'))
% get(e,'string')
% ans =
% '2'
% '1'
% '0.5'
% '0.001'
% '0.002'
% '0.003'
% '1'
% '1'
% '1'
% '4.9 1.7 -2.5'
% '127.7 147.0 89.8'
% get(e,'callback')
% ans =
% 'spm_image('repos',1)'
% 'spm_image('repos',2)'
% 'spm_image('repos',3)'
% 'spm_image('repos',4)'
% 'spm_image('repos',5)'
% 'spm_image('repos',6)'
% 'spm_image('repos',7)'
% 'spm_image('repos',8)'
% 'spm_image('repos',9)'
% 'spm_image('setposmm')'
% 'spm_image('setposvx')'
%% pprivate-path
% V:\mritools\tpm\pwhiter62.nii
%% pprivate-pathEND
|
github
|
philippboehmsturm/antx-master
|
dispoverlay.m
|
.m
|
antx-master/mritools/displaykey/dispoverlay.m
| 2,217 |
utf_8
|
1f8ba913d57538f42af3d5e293bcc2a9
|
function dispoverlay(img1,img2, namestr)
% inside function used for s1_checkoverlay
% img1='V:\MRI_testdata\T2w_nifti\s20150909_FK_C2M09_1_3_1\\s20150909_FK_C2M09_1_3_1.nii'
% img2='V:\mritools\tpm\pgreyr62.nii'
% namestr ='7/28 - s20150909_FK_C2M09_1_3_1'
displaykey2(img1,img2);
delete(findobj(gcf,'tag','pb'))
%% colorize 'Reorient images...'-BUTTON
try
hgr=findobj(0,'tag','Graphics');
hRI=findobj(hgr,'string','Reorient images...');
set(hRI,'BackgroundColor',[ 1.0000 0.6941 0.3922]);
end
% [pa fi]=fileparts(t);
units=get(gcf,'units');
set(gcf,'units','normalized')
pb= uicontrol('Style', 'text', 'String', namestr,...
'units','normalized',...
'Position', [.1 .96 .8 .02],'backgroundcolor',[0 1 1],'tag','pb','fontsize',9);
% 350 600 200 20
sizbut=[.15 .03]
%% reorientIMAGE
if 0
pb= uicontrol('Style', 'pushbutton', 'String', 'reorientIMAGE','units','normalized',...
'Position', [.6 .55 sizbut],'backgroundcolor',[0 1 0],'tag','pb','fontsize',9);
iptaddcallback(pb, 'callback', 'spm_image(''reorient'')') ;
iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
iptaddcallback(pb, 'callback', 'drawnow;dispoverlay(img1,img2,namestr)') ;
% iptaddcallback(pb, 'callback', 'uiresume(gcbf)') ;
end
%% weiter
pb= uicontrol('Style', 'pushbutton', 'String', 'weiter','units','normalized',...
'Position', [.6+sizbut(1) .55 sizbut],'backgroundcolor',[0 1 0],'tag','pb','fontsize',9);
iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
%% info
pb= uicontrol('Style', 'text', 'String', 'blalbla','units','normalized',...
'Position', [.6 .55-sizbut(2) 2*sizbut(1) sizbut(2)],...
'backgroundcolor',[.8 .8 .8],'tag','pb','fontsize',7,'userdata','myinfo' );
% iptaddcallback(pb, 'callback', 'uiresume(gcf)') ;
try
set(pb,'tooltip',[['bgrIMG: ' img1 ] (char(10)) ['ovlIMG: ' img2 ]]);
end
set(gcf,'units',units);
hfig=findobj(0,'tag','Graphics');
ca=findobj(hfig,'string','Reorient images...');
iptaddcallback(ca, 'callback', 'uiresume(gcf)') ;
displaykey(2)
drawnow
% ax=findobj(gcf,'type','axes');
% get(gcf,'CurrentObject',1);
% set(0,'')
uiwait(gcf);
|
github
|
philippboehmsturm/antx-master
|
propertiesGUI.m
|
.m
|
antx-master/mritools/others/propertiesGUI.m
| 71,009 |
utf_8
|
588c931336a6890ed0c786d68a8a78ad
|
function [hPropsPane,parameters] = propertiesGUI(hParent, parameters, filename, selectedBranch)
% propertiesGUI displays formatted editable list of properties
%
% Syntax:
%
% Initialization:
% [hPropsPane,parameters] = propertiesGUI(hParent, parameters)
%
% Run-time interaction:
% propertiesGUI(hPropsPane, mode, filename, branch)
%
% Description:
% propertiesGUI processes a list of data properties and displays
% them in a GUI table, where each parameter value has a unique
% associated editor.
%
% propertiesGUI by itself, with no input parameters, displays a demo
%
% By default, propertiesGUI identifies and processes the following
% field types: signed, unsigned, float, file, folder, text or string,
% color, IPAddress, password, date, boolean, cell-array, numeric array,
% font, struct and class object.
%
% Inputs:
% Initialization (up to 2 inputs)
%
% hParent - optional handle of a parent GUI container (figure/uipanel
% /uitab) in which the properties table will appear.
% If missing or empty or 0, the table will be shown in a
% new modal dialog window; otherwise it will be embedded
% in the parent container.
%
% parameters - struct or object with data fields. The fields are
% processed separately to determine their corresponding cell
% editor. If parameters is not specified, then the global
% test_data will be used. If test_data is also empty, then
% a demo of several different data types will be used.
%
% Run-time interactions (4 inputs)
%
% hPropsPane - handle to the properties panel width (see output below)
%
% mode - char string, 'save' or 'load' to indicate the operation mode
% to save data or load
%
% filename - char string of the filename to be saved. Can be full path
% or relative.
%
% branch - char string to the branch to be saved or loaded. If it is a
% sub branch then the items are to be delimited by '.'
% If branch is empty -> then the full tree data is saved/loaded.
%
% Outputs:
% hPropsPane - handle of the properties panel widget, which can be
% customized to display field descriptions, toolbar, etc.
%
% parameters - the resulting (possibly-updated) parameters struct.
% Naturally, this is only relevant in case of a modal dialog.
%
% (global test_data) - this global variable is updated internally when
% the <OK> button is clicked. It is meant to enable easy data
% passing between the properties GUI and other application
% component. Using global vars is generally discouraged as
% bad programming, but it simplifies component interaction.
%
% Customization:
% This utility is meant to be used either as stand-alone, or as a
% template for customization. For example, you can attach a unique
% description to each property that will be shown in an internal
% sub-panel: see the customizePropertyPane() and preparePropsList()
% sub-functions.
%
% When passing the properties in an input parameters struct, the
% utility automatically inspects each struct field and assigns a
% corresponding cell-editor with no description and a field label
% that reflects the field name. The properties are automatically
% set as modifiable (editable) and assigned a default callback
% function (propUpdatedCallback() sub-function).
% See the demoParameters() sub-function for some examples.
%
% You can have specific control over each property's description,
% label, editability, cell-editor and callback function. See the
% preparePropsList() sub-functions for some examples. You can add
% additional cell-editors/renderers in the newProperty() sub-function.
%
% You can place specific control over the acceptable property values
% by entering custom code into the checkProp() sub-function.
%
% Future development:
% 1. Improve the editor for time, numeric and cell arrays
% 2. Enable more control over appearance and functionality via
% propertiesGUI's input parameters
% 3. Add additional built-in cell editors/renderers: slider, point,
% rectangle (=position), ...
%
% Example:
% propertiesGUI; % displays the demo
%
% params.name = 'Yair';
% params.age = uint8(41);
% params.folder = pwd;
% params.date = now;
% params.size.width = 10;
% params.size.height = 20;
% [hPropsPane, params] = propertiesGUI(params);
%
% % runtime interation:
% propertiesGUI(hPropsPane, 'save', 'width.mat', 'size.width');
% propertiesGUI(hPropsPane, 'load', 'width.mat', 'size.width');
%
% Bugs and suggestions:
% Please send to Yair Altman (altmany at gmail dot com)
%
% Warning:
% This code heavily relies on undocumented and unsupported Matlab
% functionality. It works on Matlab 7+, but use at your own risk!
%
% A technical description of the implementation can be found at:
% http://undocumentedmatlab.com/blog/propertiesGUI
% http://undocumentedmatlab.com/blog/jide-property-grids
% http://undocumentedmatlab.com/blog/advanced-jide-property-grids
%
% Change log:
% 2015-03-12: Fixes for R2014b; added support for matrix data, data save/load, feedback links
% 2013-12-24: Fixes for R2013b & R2014a; added support for Font property
% 2013-04-23: Handled multi-dimensional arrays
% 2013-04-23: Fixed case of empty ([]) data, handled class objects & numeric/cell arrays, fixed error reported by Andrew Ness
% 2013-01-26: Updated help section
% 2012-11-07: Minor fix for file/folder properties
% 2012-11-07: Accept any object having properties/fields as input parameter; support multi-level properties
% 2012-10-31: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a>
%
% See also:
% inspect, uiinspect (#17935 on the MathWorks File Exchange)
% License to use and modify this code is granted freely to all interested, as long as the original author is
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.15 $ $Date: 2015/03/12 12:37:46 $
% Get the initial data
global test_data
isDemo = false;
if nargin < 2
try
isObj = nargin==1;
[hasProps,isHG] = hasProperties(hParent);
isObj = isObj && hasProps && ~isHG;
catch
% ignore - maybe nargin==0, so no hParent is available
end
if isObj
parameters = hParent;
hParent = [];
else
parameters = test_data; % comment this if you do not want persistent parameters
if isempty(parameters)
% demo mode
parameters = demoParameters;
end
isDemo = true;
end
elseif nargin == 4 % check if load or save mode
mode = parameters;
if ischar(mode) && ischar(filename) && (ischar(selectedBranch) || iscell(selectedBranch))
hParent = handle(hParent);
hFig = ancestor(hParent,'figure');
%mirrorData = getappdata(hFig, 'mirror');
hgrid = getappdata(hFig, 'hgrid');
if strcmp(mode,'load') && isempty(selectedBranch)
parameters = load(filename, '-mat');
container = hParent.Parent;
delete(hParent)
hPropsPane = propertiesGUI(container,parameters);
else
fileIO_Callback(hgrid, selectedBranch, mode, hFig, filename)
end
else
error('propertiesGUI:incorrectUsage', 'Incorrect input parameters in input');
end
return
end
% Accept any object having data fields/properties
try
parameters = get(parameters);
catch
oldWarn = warning('off','MATLAB:structOnObject');
parameters = struct(parameters);
warning(oldWarn);
end
% Init JIDE
com.mathworks.mwswing.MJUtilities.initJIDE;
% Prepare the list of properties
oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty');
warning off MATLAB:hg:PossibleDeprecatedJavaSetHGProperty
isEditable = true; %=nargin < 1;
propsList = preparePropsList(parameters, isEditable);
% Create a mapping propName => prop
propsHash = java.util.Hashtable;
propsArray = propsList.toArray();
for propsIdx = 1 : length(propsArray)
thisProp = propsArray(propsIdx);
propName = getPropName(thisProp);
propsHash.put(propName, thisProp);
end
warning(oldWarn);
% Prepare a properties table that contains the list of properties
model = javaObjectEDT(com.jidesoft.grid.PropertyTableModel(propsList));
model.expandAll();
% Prepare the properties table (grid)
grid = javaObjectEDT(com.jidesoft.grid.PropertyTable(model));
grid.setShowNonEditable(grid.SHOW_NONEDITABLE_BOTH_NAME_VALUE);
%set(handle(grid.getSelectionModel,'CallbackProperties'), 'ValueChangedCallback', @propSelectedCallback);
com.jidesoft.grid.TableUtils.autoResizeAllColumns(grid);
%com.jidesoft.grid.TableUtils.autoResizeAllRows(grid);
grid.setRowHeight(19); % default=16; autoResizeAllRows=20 - we need something in between
% Auto-end editing upon focus loss
grid.putClientProperty('terminateEditOnFocusLost',true);
% If no parent (or the root) was specified
if nargin < 1 || isempty(hParent) || isequal(hParent,0)
% Create a new figure window
delete(findall(0, '-depth',1, 'Tag','fpropertiesGUI'));
hFig = figure('NumberTitle','off', 'Name','Application properties', 'Units','pixel', 'Pos',[300,200,500,500], 'Menu','none', 'Toolbar','none', 'Tag','fpropertiesGUI', 'Visible','off');
hParent = hFig;
setappdata(0,'isParamsGUIApproved',false)
% Add the bottom action buttons
btOK = uicontrol('String','OK', 'Units','pixel', 'Pos',[ 20,5,60,30], 'Tag','btOK', 'Callback',@btOK_Callback);
btCancel = uicontrol('String','Cancel', 'Units','pixel', 'Pos',[100,5,60,30], 'Tag','btCancel', 'Callback',@(h,e)close(hFig)); %#ok<NASGU>
% Add the rating link (demo mode only)
if isDemo
cursor = java.awt.Cursor(java.awt.Cursor.HAND_CURSOR);
blogLabel = javax.swing.JLabel('<html><center>Additional interesting stuff at<br/><b><a href="">UndocumentedMatlab.com');
set(handle(blogLabel,'CallbackProperties'), 'MouseClickedCallback', 'web(''http://UndocumentedMatlab.com'',''-browser'');');
blogLabel.setCursor(cursor);
javacomponent(blogLabel, [200,5,170,30], hFig);
url = 'http://www.mathworks.com/matlabcentral/fileexchange/38864-propertiesgui';
rateLabel = javax.swing.JLabel('<html><center><b><a href="">Feedback / rating for this utility');
set(handle(rateLabel,'CallbackProperties'), 'MouseClickedCallback', ['web(''' url ''',''-browser'');']);
rateLabel.setCursor(cursor);
javacomponent(rateLabel, [380,5,110,30], hFig);
end
% Check the property values to determine whether the <OK> button should be enabled or not
checkProps(propsList, btOK, true);
% Set the figure icon & make visible
jFrame = get(handle(hFig),'JavaFrame');
icon = javax.swing.ImageIcon(fullfile(matlabroot, '/toolbox/matlab/icons/tool_legend.gif'));
jFrame.setFigureIcon(icon);
% set(hFig, 'WindowStyle','modal', 'Visible','on');
set(hFig, 'Visible','on');
% Set the component's position
%pos = [5,40,490,440];
hFigPos = getpixelposition(hFig);
pos = [5,40,hFigPos(3)-10,hFigPos(4)-50];
wasFigCreated = true;
else
% Set the component's position
drawnow;
pos = getpixelposition(hParent);
pos(1:2) = 5;
pos = pos - [0,0,10,10];
hFig = ancestor(hParent,'figure');
wasFigCreated = false;
% Clear the parent container
if isequal(hFig,hParent)
clf(hFig);
else
delete(allchild(hParent));
end
end
%drawnow; pause(0.05);
pane = javaObjectEDT(com.jidesoft.grid.PropertyPane(grid));
customizePropertyPane(pane);
[jPropsPane, hPropsPane_] = javacomponent(pane, pos, hParent);
% A callback for touching the mouse
hgrid = handle(grid, 'CallbackProperties');
set(hgrid, 'MousePressedCallback', {@MousePressedCallback, hFig});
setappdata(hFig, 'jPropsPane',jPropsPane);
setappdata(hFig, 'propsList',propsList);
setappdata(hFig, 'propsHash',propsHash);
setappdata(hFig, 'mirror',parameters);
setappdata(hFig, 'hgrid',hgrid);
set(hPropsPane_,'tag','hpropertiesGUI');
set(hPropsPane_, 'Units','norm');
% Align the background colors
bgcolor = pane.getBackground.getComponents([]);
try set(hParent, 'Color', bgcolor(1:3)); catch, end % this fails in uitabs - never mind (works ok in stand-alone figures)
try pane.setBorderColor(pane.getBackground); catch, end % error reported by Andrew Ness
% If a new figure was created, make it modal and wait for user to close it
if wasFigCreated
% uiwait(hFig);
if getappdata(0,'isParamsGUIApproved')
parameters = test_data; %=getappdata(hFig, 'mirror');
end
end
if nargout, hPropsPane = hPropsPane_; end % prevent unintentional printouts to the command window
end % propertiesGUI
% Mouse-click callback function
function MousePressedCallback(grid, eventdata, hFig)
% Get the clicked location
%grid = eventdata.getSource;
%columnModel = grid.getColumnModel;
%leftColumn = columnModel.getColumn(0);
clickX = eventdata.getX;
clickY = eventdata.getY;
%rowIdx = grid.getSelectedRow + 1;
if clickX <= 20 %leftColumn.getWidth % clicked the side-bar
return
%elseif grid.getSelectedColumn==0 % didn't press on the value (second column)
% return
end
% bail-out if right-click
if eventdata.isMetaDown
showGridContextMenu(hFig, grid, clickX, clickY);
else
% bail-out if the grid is disabled
if ~grid.isEnabled, return; end
%data = getappdata(hFig, 'mirror');
selectedProp = grid.getSelectedProperty; % which property (java object) was selected
if ~isempty(selectedProp)
if ismember('arrayData',fieldnames(get(selectedProp)))
% Get the current data and update it
actualData = get(selectedProp,'ArrayData');
updateDataInPopupTable(selectedProp.getName, actualData, hFig, selectedProp);
end
end
end
end %Mouse pressed
% Update data in a popup table
function updateDataInPopupTable(titleStr, data, hGridFig, selectedProp)
figTitleStr = [char(titleStr) ' data'];
hFig = findall(0, '-depth',1, 'Name',figTitleStr);
if isempty(hFig)
hFig = figure('NumberTitle','off', 'Name',figTitleStr, 'Menubar','none', 'Toolbar','none');
else
figure(hFig); % bring into focus
end
try
mtable = createTable(hFig, [], data);
set(mtable,'DataChangedCallback',{@tableDataUpdatedCallback,hGridFig,selectedProp});
%uiwait(hFig) % modality
catch
delete(hFig);
errMsg = {'Editing this data requires Yair Altman''s Java-based data table (createTable) utility from the Matlab File Exchange.', ...
' ', 'If you have already downloaded and unzipped createTable, then please ensure that it is on the Matlab path.'};
uiwait(msgbox(errMsg,'Error','warn'));
web('http://www.mathworks.com/matlabcentral/fileexchange/14225-java-based-data-table');
end
end % updateDataInPopupTable
% User updated the data in the popup table
function tableDataUpdatedCallback(mtable,eventData,hFig,selectedProp) %#ok<INUSL>
% Get the latest data
updatedData = cell(mtable.Data);
try
if ~iscellstr(updatedData)
updatedData = cell2mat(updatedData);
end
catch
% probably hetrogeneous data
end
propName = getRecursivePropName(selectedProp); % get the property name
set(selectedProp,'ArrayData',updatedData); % update the appdata of the
% specific property containing the actual information of the array
%% Update the displayed value in the properties GUI
dataClass = class(updatedData);
value = regexprep(sprintf('%dx',size(updatedData)),{'^(.)','x$'},{'<$1',['> ' dataClass ' array']});
% set(selectProp,'value',value);
selectedProp.setValue(value); % update the table
% Update the display
propsList = getappdata(hFig, 'propsList');
checkProps(propsList, hFig);
% Refresh the GUI
propsPane = getappdata(hFig, 'jPropsPane');
try propsPane.repaint; catch; end
% Update the local mirror
data = getappdata(hFig, 'mirror');
eval(['data.' propName ' = updatedData;']);
setappdata(hFig, 'mirror',data);
end % tableDataUpdatedCallback
% Determine whether a specified object should be considered as having fields/properties
% Note: HG handles must be processed seperately for the main logic to work
function [hasProps,isHG] = hasProperties(object)
% A bunch of tests, some of which may croak depending on the Matlab release, platform
try isHG = ishghandle(object); catch, isHG = ishandle(object); end
try isst = isstruct(object); catch, isst = false; end
try isjav = isjava(object); catch, isjav = false; end
try isobj = isobject(object); catch, isobj = false; end
try isco = iscom(object); catch, isco = false; end
hasProps = ~isempty(object) && (isst || isjav || isobj || isco);
end
% Customize the property-pane's appearance
function customizePropertyPane(pane)
pane.setShowDescription(false); % YMA: we don't currently have textual descriptions of the parameters, so no use showing an empty box that just takes up GUI space...
pane.setShowToolBar(false);
pane.setOrder(2); % uncategorized, unsorted - see http://undocumentedmatlab.com/blog/advanced-jide-property-grids/#comment-42057
end
% Prepare a list of some parameters for demo mode
function parameters = demoParameters
parameters.floating_point_property = pi;
parameters.signed_integer_property = int16(12);
parameters.unsigned_integer_property = uint16(12);
parameters.flag_property = true;
parameters.file_property = mfilename('fullpath');
parameters.folder_property = pwd;
parameters.text_property = 'Sample text';
parameters.fixed_choice_property = {'Yes','No','Maybe', 'No'};
parameters.editable_choice_property = {'Yes','No','Maybe','', {3}}; % editable if the last cell element is ''
parameters.date_property = java.util.Date; % today's date
parameters.another_date_property = now-365; % last year
parameters.time_property = datestr(now,'HH:MM:SS');
parameters.password_property = '*****';
parameters.IP_address_property = '10.20.30.40';
parameters.my_category.width = 4;
parameters.my_category.height = 3;
parameters.my_category.and_a_subcategory.is_OK = true;
parameters.numeric_array_property = [11,12,13,14];
parameters.numeric_matrix = magic(5);
parameters.logical_matrix = true(2,5);
parameters.mixed_data_matrix = {true,'abc',pi,uint8(123); false,'def',-pi,uint8(64)};
parameters.cell_array_property = {1,magic(3),'text',-4};
parameters.color_property = [0.4,0.5,0.6];
parameters.another_color_property = java.awt.Color.red;
parameters.font_property = java.awt.Font('Arial', java.awt.Font.Normal, 22);
try parameters.class_object_property = matlab.desktop.editor.getActive; catch, end
end % demoParameters
% Prepare a list of properties
function propsList = preparePropsList(parameters, isEditable)
propsList = java.util.ArrayList();
% Convert a class object into a struct
if isobject(parameters)
parameters = struct(parameters);
end
% Check for an array of inputs (currently unsupported)
%if numel(parameters) > 1, error('YMA:propertiesGUI:ArrayParameters','Non-scalar inputs are currently unsupported'); end
% Prepare a dynamic list of properties, based on the struct fields
if isstruct(parameters) && ~isempty(parameters)
%allParameters = parameters(:); % convert ND array => 3D array
allParameters = reshape(parameters, size(parameters,1),size(parameters,2),[]);
numParameters = numel(allParameters);
if numParameters > 1
for zIdx = 1 : size(allParameters,3)
for colIdx = 1 : size(allParameters,2)
for rowIdx = 1 : size(allParameters,1)
parameters = allParameters(rowIdx,colIdx,zIdx);
field_name = '';
field_label = sprintf('(%d,%d,%d)',rowIdx,colIdx,zIdx);
field_label = regexprep(field_label,',1\)',')'); % remove 3D if unnecesary
newProp = newProperty(parameters, field_name, field_label, isEditable, '', '', @propUpdatedCallback);
propsList.add(newProp);
end
end
end
else
% Dynamically (generically) inspect all the fields and assign corresponding props
field_names = fieldnames(parameters);
for field_idx = 1 : length(field_names)
arrayData = [];
field_name = field_names{field_idx};
value = parameters.(field_name);
field_label = getFieldLabel(field_name);
%if numParameters > 1, field_label = [field_label '(' num2str(parametersIdx) ')']; end
field_description = ''; % TODO
type = 'string';
if isempty(value)
type = 'string'; % not really needed, but for consistency
elseif isa(value,'java.awt.Color')
type = 'color';
elseif isa(value,'java.awt.Font')
type = 'font';
elseif isnumeric(value)
try %if length(value)==3
colorComponents = num2cell(value);
if numel(colorComponents) ~= 3
error(' '); % bail out if definitely not a color
end
try
value = java.awt.Color(colorComponents{:}); % value between 0-1
catch
colorComponents = num2cell(value/255);
value = java.awt.Color(colorComponents{:}); % value between 0-255
end
type = 'color';
catch %else
if numel(value)==1
%value = value(1);
if value > now-3650 && value < now+3650
type = 'date';
value = java.util.Date(datestr(value));
elseif isa(value,'uint') || isa(value,'uint8') || isa(value,'uint16') || isa(value,'uint32') || isa(value,'uint64')
type = 'unsigned';
elseif isinteger(value)
type = 'signed';
else
type = 'float';
end
else % a vector or a matrix
arrayData = value;
value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> numeric array'});
%{
value = num2str(value);
if size(value,1) > size(value,2)
value = value';
end
if size(squeeze(value),2) > 1
% Convert multi-row string into a single-row string
value = [value'; repmat(' ',1,size(value,1))];
value = value(:)';
end
value = strtrim(regexprep(value,' +',' '));
if length(value) > 50
value(51:end) = '';
value = [value '...']; %#ok<AGROW>
end
value = ['[ ' value ' ]']; %#ok<AGROW>
%}
end
end
elseif islogical(value)
if numel(value)==1
% a single value
type = 'boolean';
else % an array of boolean values
arrayData = value;
value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> logical array'});
end
elseif ischar(value)
if exist(value,'dir')
type = 'folder';
value = java.io.File(value);
elseif exist(value,'file')
type = 'file';
value = java.io.File(value);
elseif value(1)=='*'
type = 'password';
elseif sum(value=='.')==3
type = 'IPAddress';
else
type = 'string';
if length(value) > 50
value(51:end) = '';
value = [value '...']; %#ok<AGROW>
end
end
elseif iscell(value)
type = value; % editable if the last cell element is ''
if size(value,1)==1 || size(value,2)==1
% vector - treat as a drop-down (combo-box/popup) of values
if ~iscellstr(value)
type = value;
for ii=1:length(value)
if isnumeric(value{ii}) % if item is numeric -> change to string for display.
type{ii} = num2str(value{ii});
else
type{ii} = value{ii};
end
end
end
else % Matrix - use table popup
%value = ['{ ' strtrim(regexprep(evalc('disp(value)'),' +',' ')) ' }'];
arrayData = value;
value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> cell array'});
end
elseif isa(value,'java.util.Date')
type = 'date';
elseif isa(value,'java.io.File')
if value.isFile
type = 'file';
else % value.isDirectory
type = 'folder';
end
elseif isobject(value)
oldWarn = warning('off','MATLAB:structOnObject');
value = struct(value);
warning(oldWarn);
elseif ~isstruct(value)
value = strtrim(regexprep(evalc('disp(value)'),' +',' '));
end
parameters.(field_name) = value; % possibly updated above
newProp = newProperty(parameters, field_name, field_label, isEditable, type, field_description, @propUpdatedCallback);
propsList.add(newProp);
% Save the array as a new property of the object
if ~isempty(arrayData)
try
set(newProp,'arrayData',arrayData)
catch
%setappdata(hProp,'UserData',propName)
hp = schema.prop(handle(newProp),'arrayData','mxArray'); %#ok<NASGU>
set(handle(newProp),'arrayData',arrayData)
end
newProp.setEditable(false);
end
end
end
else
% You can also use direct assignments, instead of the generic code above. For example:
% (Possible property types: signed, unsigned, float, file, folder, text or string, color, IPAddress, password, date, boolean, cell-array of strings)
propsList.add(newProperty(parameters, 'flag_prop_name', 'Flag value:', isEditable, 'boolean', 'Turn this on if you want to make extra plots', @propUpdatedCallback));
propsList.add(newProperty(parameters, 'float_prop_name', 'Boolean prop', isEditable, 'float', 'description 123...', @propUpdatedCallback));
propsList.add(newProperty(parameters, 'string_prop_name', 'My text msg:', isEditable, 'string', 'Yaba daba doo', @propUpdatedCallback));
propsList.add(newProperty(parameters, 'int_prop_name', 'Now an integer', isEditable, 'unsigned', '123 456...', @propUpdatedCallback));
propsList.add(newProperty(parameters, 'choice_prop_name', 'And a drop-down', isEditable, {'Yes','No','Maybe'}, 'no description here!', @propUpdatedCallback));
end
end % preparePropsList
% Get a normalized field label (see also checkFieldName() below)
function field_label = getFieldLabel(field_name)
field_label = regexprep(field_name, '__(.*)', ' ($1)');
field_label = strrep(field_label,'_',' ');
field_label(1) = upper(field_label(1));
end
% Prepare a data property
function prop = newProperty(dataStruct, propName, label, isEditable, dataType, description, propUpdatedCallback)
% Auto-generate the label from the property name, if the label was not specified
if isempty(label)
label = getFieldLabel(propName);
end
% Create a new property with the chosen label
prop = javaObjectEDT(com.jidesoft.grid.DefaultProperty); % UNDOCUMENTED internal MATLAB component
prop.setName(label);
prop.setExpanded(true);
% Set the property to the current patient's data value
try
thisProp = dataStruct.(propName);
catch
thisProp = dataStruct;
end
origProp = thisProp;
if isstruct(thisProp) %hasProperties(thisProp)
% Accept any object having data fields/properties
try
thisProp = get(thisProp);
catch
oldWarn = warning('off','MATLAB:structOnObject');
thisProp = struct(thisProp);
warning(oldWarn);
end
% Parse the children props and add them to this property
%summary = regexprep(evalc('disp(thisProp)'),' +',' ');
%prop.setValue(summary); % TODO: display summary dynamically
if numel(thisProp) < 2
prop.setValue('');
else
sz = size(thisProp);
szStr = regexprep(num2str(sz),' +','x');
prop.setValue(['[' szStr ' struct array]']);
end
prop.setEditable(false);
children = toArray(preparePropsList(thisProp, isEditable));
for childIdx = 1 : length(children)
prop.addChild(children(childIdx));
end
else
prop.setValue(thisProp);
prop.setEditable(isEditable);
end
% Set property editor, renderer and alignment
if iscell(dataType)
% treat this as drop-down values
% Set the defaults
firstIndex = 1;
cbIsEditable = false;
% Extract out the number of items in the user list
nItems = length(dataType);
% Check for any empty items
emptyItem = find(cellfun('isempty', dataType) == 1);
% If only 1 empty item found check editable rules
if length(emptyItem) == 1
% If at the end - then remove it and set editable flag
if emptyItem == nItems
cbIsEditable = true;
dataType(end) = []; % remove from the drop-down list
elseif emptyItem == nItems - 1
cbIsEditable = true;
dataType(end-1) = []; % remove from the drop-down list
end
end
% Try to find the initial (default) drop-down index
if ~isempty(dataType)
if iscell(dataType{end})
if isnumeric(dataType{end}{1})
firstIndex = dataType{end}{1};
dataType(end) = []; % remove the [] from drop-down list
end
else
try
if ismember(dataType{end}, dataType(1:end-1))
firstIndex = find(strcmp(dataType(1:end-1),dataType{end}));
dataType(end) = [];
end
catch
% ignore - possibly mixed data
end
end
% Build the editor
editor = com.jidesoft.grid.ListComboBoxCellEditor(dataType);
try editor.getComboBox.setEditable(cbIsEditable); catch, end % #ok<NOCOM>
%set(editor,'EditingStoppedCallback',{@propUpdatedCallback,tagName,propName});
alignProp(prop, editor);
try prop.setValue(origProp{firstIndex}); catch, end
end
else
switch lower(dataType)
case 'signed', %alignProp(prop, com.jidesoft.grid.IntegerCellEditor, 'int32');
model = javax.swing.SpinnerNumberModel(prop.getValue, -intmax, intmax, 1);
editor = com.jidesoft.grid.SpinnerCellEditor(model);
alignProp(prop, editor, 'int32');
case 'unsigned', %alignProp(prop, com.jidesoft.grid.IntegerCellEditor, 'uint32');
val = max(0, min(prop.getValue, intmax));
model = javax.swing.SpinnerNumberModel(val, 0, intmax, 1);
editor = com.jidesoft.grid.SpinnerCellEditor(model);
alignProp(prop, editor, 'uint32');
case 'float', %alignProp(prop, com.jidesoft.grid.CalculatorCellEditor, 'double'); % DoubleCellEditor
alignProp(prop, com.jidesoft.grid.DoubleCellEditor, 'double');
case 'boolean', alignProp(prop, com.jidesoft.grid.BooleanCheckBoxCellEditor, 'logical');
case 'folder', alignProp(prop, com.jidesoft.grid.FolderCellEditor);
case 'file', alignProp(prop, com.jidesoft.grid.FileCellEditor);
case 'ipaddress', alignProp(prop, com.jidesoft.grid.IPAddressCellEditor);
case 'password', alignProp(prop, com.jidesoft.grid.PasswordCellEditor);
case 'color', alignProp(prop, com.jidesoft.grid.ColorCellEditor);
case 'font', alignProp(prop, com.jidesoft.grid.FontCellEditor);
case 'text', alignProp(prop);
case 'time', alignProp(prop); % maybe use com.jidesoft.grid.FormattedTextFieldCellEditor ?
case 'date', dateModel = com.jidesoft.combobox.DefaultDateModel;
dateFormat = java.text.SimpleDateFormat('dd/MM/yyyy');
dateModel.setDateFormat(dateFormat);
editor = com.jidesoft.grid.DateCellEditor(dateModel, 1);
alignProp(prop, editor, 'java.util.Date');
try
prop.setValue(dateFormat.parse(prop.getValue)); % convert string => Date
catch
% ignore
end
otherwise, alignProp(prop); % treat as a simple text field
end
end % for all possible data types
prop.setDescription(description);
if ~isempty(description)
renderer = com.jidesoft.grid.CellRendererManager.getRenderer(prop.getType, prop.getEditorContext);
renderer.setToolTipText(description);
end
% Set the property's editability state
if prop.isEditable
% Set the property's label to be black
prop.setDisplayName(['<html><font color="black">' label]);
% Add callbacks for property-change events
hprop = handle(prop, 'CallbackProperties');
set(hprop,'PropertyChangeCallback',{propUpdatedCallback,propName});
else
% Set the property's label to be gray
prop.setDisplayName(['<html><font color="gray">' label]);
end
setPropName(prop,propName);
end % newProperty
% Set property name in the Java property reference
function setPropName(hProp,propName)
try
set(hProp,'UserData',propName)
catch
%setappdata(hProp,'UserData',propName)
hp = schema.prop(handle(hProp),'UserData','mxArray'); %#ok<NASGU>
set(handle(hProp),'UserData',propName)
end
end % setPropName
% Get property name from the Java property reference
function propName = getPropName(hProp)
try
propName = get(hProp,'UserData');
catch
%propName = char(getappdata(hProp,'UserData'));
propName = get(handle(hProp),'UserData');
end
end % getPropName
% Get recursive property name
function propName = getRecursivePropName(prop, propBaseName)
try
oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty');
try prop = java(prop); catch, end
if nargin < 2
propName = getPropName(prop);
else
propName = propBaseName;
end
while isa(prop,'com.jidesoft.grid.Property')
prop = get(prop,'Parent');
newName = getPropName(prop);
if isempty(newName)
%% check to see if it's a (1,1)
displayName = char(prop.getName);
[flag, index] = CheckStringForBrackets(displayName);
if flag
propName = sprintf('(%i).%s',index,propName);
else
break;
end
else
propName = [newName '.' propName]; %#ok<AGROW>
end
end
catch
% Reached the top of the property's heirarchy - bail out
warning(oldWarn);
end
end % getRecursivePropName
% Align a text property to right/left
function alignProp(prop, editor, propTypeStr, direction)
persistent propTypeCache
if isempty(propTypeCache), propTypeCache = java.util.Hashtable; end
if nargin < 2 || isempty(editor), editor = com.jidesoft.grid.StringCellEditor; end %(javaclass('char',1));
if nargin < 3 || isempty(propTypeStr), propTypeStr = 'cellstr'; end % => javaclass('char',1)
if nargin < 4 || isempty(direction), direction = javax.swing.SwingConstants.RIGHT; end
% Set this property's data type
propType = propTypeCache.get(propTypeStr);
if isempty(propType)
propType = javaclass(propTypeStr);
propTypeCache.put(propTypeStr,propType);
end
prop.setType(propType);
% Prepare a specific context object for this property
if strcmpi(propTypeStr,'logical')
%TODO - FIXME
context = editor.CONTEXT;
prop.setEditorContext(context);
%renderer = CheckBoxRenderer;
%renderer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
%com.jidesoft.grid.CellRendererManager.registerRenderer(propType, renderer, context);
else
context = com.jidesoft.grid.EditorContext(prop.getName);
prop.setEditorContext(context);
% Register a unique cell renderer so that each property can be modified seperately
%renderer = com.jidesoft.grid.CellRendererManager.getRenderer(propType, prop.getEditorContext);
renderer = com.jidesoft.grid.ContextSensitiveCellRenderer;
com.jidesoft.grid.CellRendererManager.registerRenderer(propType, renderer, context);
renderer.setBackground(java.awt.Color.white);
renderer.setHorizontalAlignment(direction);
%renderer.setHorizontalTextPosition(direction);
end
% Update the property's cell editor
try editor.setHorizontalAlignment(direction); catch, end
try editor.getTextField.setHorizontalAlignment(direction); catch, end
try editor.getComboBox.setHorizontalAlignment(direction); catch, end
% Set limits on unsigned int values
try
if strcmpi(propTypeStr,'uint32')
%pause(0.01);
editor.setMinInclusive(java.lang.Integer(0));
editor.setMinExclusive(java.lang.Integer(-1));
editor.setMaxExclusive(java.lang.Integer(intmax));
editor.setMaxInclusive(java.lang.Integer(intmax));
end
catch
% ignore
end
com.jidesoft.grid.CellEditorManager.registerEditor(propType, editor, context);
end % alignProp
% Property updated callback function
function propUpdatedCallback(prop, eventData, propName, fileData)
try if strcmpi(char(eventData.getPropertyName),'parent'), return; end; catch, end
% Retrieve the containing figure handle
%hFig = findall(0, '-depth',1, 'Tag','fpropertiesGUI');
hFig = get(0,'CurrentFigure'); %gcf;
if isempty(hFig)
hPropsPane = findall(0,'Tag','hpropertiesGUI');
if isempty(hPropsPane), return; end
hFig = ancestor(hPropsPane,'figure'); %=get(hPropsPane,'Parent');
end
if isempty(hFig), return; end
% Get the props data from the figure's ApplicationData
propsList = getappdata(hFig, 'propsList');
propsPane = getappdata(hFig, 'jPropsPane');
data = getappdata(hFig, 'mirror');
% Bail out if arriving from tableDataUpdatedCallback
try
s = dbstack;
if strcmpi(s(2).name, 'tableDataUpdatedCallback')
return;
end
catch
% ignore
end
% Get the updated property value
propValue = get(prop,'Value');
if isjava(propValue)
if isa(propValue,'java.util.Date')
sdf = java.text.SimpleDateFormat('MM-dd-yyyy');
propValue = datenum(sdf.format(propValue).char); %#ok<NASGU>
elseif isa(propValue,'java.awt.Color')
propValue = propValue.getColorComponents([])'; %#ok<NASGU>
else
propValue = char(propValue); %#ok<NASGU>
end
end
% Get the actual recursive propName
propName = getRecursivePropName(prop, propName);
% Find if the original item was a cell array and the mirror accordingly
items = strread(propName,'%s','delimiter','.');
if ~isempty(data)
cpy = data;
for idx = 1 : length(items)
% This is for dealing with structs with multiple levels...
[flag, index] = CheckStringForBrackets(items{idx});
if flag
cpy = cpy(index);
else
if isfield(cpy,items{idx})
cpy = cpy.(items{idx});
else
return
end
end
end
if nargin == 4
if iscell(cpy) && iscell(fileData) %%&& length(fileData)==1 % if mirror and filedata are cells then update the data -> otherwise overright.
propValue=UpdateCellArray(cpy,fileData);
end
else
if iscell(cpy)
propValue = UpdateCellArray(cpy, propValue);
end
end
end
% Check for loading from file and long string which has been truncated
if nargin == 4
propValue = checkCharFieldForAbreviation(propValue,fileData);
if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]'))
propValue = fileData;
end
if isempty(propValue) % a struct
propValue = fileData;
end
end
% For items with .(N) in the struct -> remove from path for eval
propName = regexprep(propName,'\.(','(');
% Update the mirror with the updated field value
%data.(propName) = propValue; % croaks on multiple sub-fields
eval(['data.' propName ' = propValue;']);
% Update the local mirror
setappdata(hFig, 'mirror',data);
% Update the display
checkProps(propsList, hFig);
try propsPane.repaint; catch; end
end % propUpdatedCallback
function selectedValue = UpdateCellArray(originalData,selectedValue)
if length(originalData)==length(selectedValue) || ~iscell(selectedValue)
index=find(strcmp(originalData,selectedValue)==1);
if iscell(originalData{end})
originalData{end}={index};
else
if index~=1 % If it's not first index then we can save it
originalData{end+1} = {index};
end
end
selectedValue=originalData;
else
selectedValue=originalData;
end
end % UpdateCellArray
% <OK> button callback function
function btOK_Callback(btOK, eventData) %#ok<INUSD>
global test_data
% Store the current data-info struct mirror in the global struct
hFig = ancestor(btOK, 'figure');
test_data = getappdata(hFig, 'mirror');
setappdata(0,'isParamsGUIApproved',true);
% Close the window
try
close(hFig);
catch
delete(hFig); % force-close
end
end % btOK_Callback
% Check whether all mandatory fields have been filled, update background color accordingly
function checkProps(propsList, hContainer, isInit)
if nargin < 3, isInit = false; end
okEnabled = 'on';
try propsArray = propsList.toArray(); catch, return; end
for propsIdx = 1 : length(propsArray)
isOk = checkProp(propsArray(propsIdx));
if ~isOk || isInit, okEnabled = 'off'; end
end
% Update the <OK> button's editability state accordingly
btOK = findall(hContainer, 'Tag','btOK');
set(btOK, 'Enable',okEnabled);
set(findall(get(hContainer,'parent'), 'tag','btApply'), 'Enable',okEnabled);
set(findall(get(hContainer,'parent'), 'tag','btRevert'), 'Enable',okEnabled);
try; drawnow; pause(0.01); end
% Update the figure title to indicate dirty-ness (if the figure is visible)
hFig = ancestor(hContainer,'figure');
if strcmpi(get(hFig,'Visible'),'on')
sTitle = regexprep(get(hFig,'Name'), '\*$','');
set(hFig,'Name',[sTitle '*']);
end
end % checkProps
function isOk = checkProp(prop)
isOk = true;
oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty');
warning off MATLAB:hg:PossibleDeprecatedJavaSetHGProperty
propName = getPropName(prop);
renderer = com.jidesoft.grid.CellRendererManager.getRenderer(get(prop,'Type'), get(prop,'EditorContext'));
warning(oldWarn);
mandatoryFields = {}; % TODO - add the mandatory field-names here
if any(strcmpi(propName, mandatoryFields)) && isempty(get(prop,'Value'))
propColor = java.awt.Color.yellow;
isOk = false;
elseif ~prop.isEditable
%propColor = java.awt.Color.gray;
%propColor = renderer.getBackground();
propColor = java.awt.Color.white;
else
propColor = java.awt.Color.white;
end
renderer.setBackground(propColor);
end % checkProp
% Return java.lang.Class instance corresponding to the Matlab type
function jclass = javaclass(mtype, ndims)
% Input arguments:
% mtype:
% the MatLab name of the type for which to return the java.lang.Class
% instance
% ndims:
% the number of dimensions of the MatLab data type
%
% See also: class
% Copyright 2009-2010 Levente Hunyadi
% Downloaded from: http://www.UndocumentedMatlab.com/files/javaclass.m
validateattributes(mtype, {'char'}, {'nonempty','row'});
if nargin < 2
ndims = 0;
else
validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'});
end
if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string
jclassname = 'java.lang.String';
elseif ndims > 0
jclassname = javaarrayclass(mtype, ndims);
else
% The static property .class applied to a Java type returns a string in
% MatLab rather than an instance of java.lang.Class. For this reason,
% use a string and java.lang.Class.forName to instantiate a
% java.lang.Class object; the syntax java.lang.Boolean.class will not do so
switch mtype
case 'logical' % logical vaule (true or false)
jclassname = 'java.lang.Boolean';
case 'char' % a singe character
jclassname = 'java.lang.Character';
case {'int8','uint8'} % 8-bit signed and unsigned integer
jclassname = 'java.lang.Byte';
case {'int16','uint16'} % 16-bit signed and unsigned integer
jclassname = 'java.lang.Short';
case {'int32','uint32'} % 32-bit signed and unsigned integer
jclassname = 'java.lang.Integer';
case {'int64','uint64'} % 64-bit signed and unsigned integer
jclassname = 'java.lang.Long';
case 'single' % single-precision floating-point number
jclassname = 'java.lang.Float';
case 'double' % double-precision floating-point number
jclassname = 'java.lang.Double';
case 'cellstr' % a single cell or a character array
jclassname = 'java.lang.String';
otherwise
jclassname = mtype;
%error('java:javaclass:InvalidArgumentValue', ...
% 'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
end
% Note: When querying a java.lang.Class object by name with the method
% jclass = java.lang.Class.forName(jclassname);
% MatLab generates an error. For the Class.forName method to work, MatLab
% requires class loader to be specified explicitly.
jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader());
end % javaclass
% Return the type qualifier for a multidimensional Java array
function jclassname = javaarrayclass(mtype, ndims)
switch mtype
case 'logical' % logical array of true and false values
jclassid = 'Z';
case 'char' % character array
jclassid = 'C';
case {'int8','uint8'} % 8-bit signed and unsigned integer array
jclassid = 'B';
case {'int16','uint16'} % 16-bit signed and unsigned integer array
jclassid = 'S';
case {'int32','uint32'} % 32-bit signed and unsigned integer array
jclassid = 'I';
case {'int64','uint64'} % 64-bit signed and unsigned integer array
jclassid = 'J';
case 'single' % single-precision floating-point number array
jclassid = 'F';
case 'double' % double-precision floating-point number array
jclassid = 'D';
case 'cellstr' % cell array of strings
jclassid = 'Ljava.lang.String;';
otherwise
jclassid = ['L' mtype ';'];
%error('java:javaclass:InvalidArgumentValue', ...
% 'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
jclassname = [repmat('[',1,ndims), jclassid];
end % javaarrayclass
% Set up the uitree context (right-click) menu
function showGridContextMenu(hFig, grid, clickX, clickY)
% Prepare the context menu (note the use of HTML labels)
import javax.swing.*
row = grid.rowAtPoint(java.awt.Point(clickX, clickY));
selectedProp = grid.getPropertyTableModel.getPropertyAt(row);
if ~isempty(selectedProp)
branchName = char(selectedProp.getName);
else
branchName = 'branch';
end
menuItem1 = JMenuItem(['Save ' branchName '...']);
menuItem2 = JMenuItem(['Load ' branchName '...']);
% Set the menu items' callbacks
set(handle(menuItem1,'CallbackProperties'),'ActionPerformedCallback',@(obj,event)fileIO_Callback(grid,selectedProp,'save',hFig));
set(handle(menuItem2,'CallbackProperties'),'ActionPerformedCallback',@(obj,event)fileIO_Callback(grid,selectedProp,'load',hFig));
% Add all menu items to the context menu (with internal separator)
jmenu = JPopupMenu;
jmenu.add(menuItem1);
jmenu.addSeparator;
jmenu.add(menuItem2);
% Display the context-menu
jmenu.show(grid, clickX, clickY);
jmenu.repaint;
end % setGridContextMenu
function fileIO_Callback(grid, selectedProp, mode, hFig, filename)
persistent lastdir
mirrorData = getappdata(hFig, 'mirror');
if nargin == 4 % interactive
filename = [];
end
% Initialize the persistent variable with the current Dir if not populated.
if isempty(lastdir); lastdir = pwd; end
switch mode
case 'save'
filename = saveBranch_Callback(grid, selectedProp, lastdir, mirrorData, hFig, filename);
case 'load'
filename = loadBranchCallback(grid, selectedProp, lastdir, mirrorData, filename);
case {'update', 'select'} % hidden calling method
runtimeUpdateBranch(grid,filename,mirrorData,selectedProp);
return
otherwise
error('propertiesGUI:fileIOCallback:invalidMethod', 'invalid calling method to propertiesGUI');
% setappdata(hFig, 'mirror',mirrorData);
end
% Check that the save/load wsa processed
if ischar(filename)
filePath = fileparts(filename);
if ~isempty(filePath)
lastdir = filePath;
end
end
end % fileIO_Callback
function filename = loadBranchCallback(grid, selectedProp, lastdir, mirrorData, filename)
if isempty(filename)
[filename, pathname] = uigetfile({'*.branch','Branch files (*.branch)'}, 'Load a file', lastdir);
if filename == 0
return
end
filename = fullfile(pathname, filename);
else
selectedProp = findUserProvidedProp(grid, selectedProp);
end
propName = char(selectedProp.getName);
propName = checkFieldName(propName);
data = load(filename, '-mat');
fnames = fieldnames(data);
index = strcmpi(fnames,propName);
% If a match was found then it's okay to proceed
if any(index)
% Remove any children
selectedProp.removeAllChildren();
% Make a new list
newList = preparePropsList(data, true);
% Conver the list to an array
newArray = newList.toArray();
updatedProp = newArray(1);
isStruct = false;
propValue = selectedProp.getValue;
if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]'))
isStruct = true;
end
% If individual value update it. TODO: Bug when it is a cell array....
if isStruct == false && ~isempty(propValue)
selectedProp.setValue (updatedProp.getValue)
propName = checkFieldName(char(updatedProp.getName));
if iscell(data.(fnames{index})) && ischar(data.(fnames{index}){end}) && ismember(data.(fnames{index})(end),data.(fnames{index})(1:end-1))
data.(fnames{index})(end) = [];
end
propUpdatedCallback(selectedProp, [], propName, data.(fnames{index}));
else
% Add children to the original property.
for ii=1:updatedProp.getChildrenCount
childProp = updatedProp.getChildAt(ii-1);
propName = checkFieldName(char(childProp.getName));
[flag, sIndex] = CheckStringForBrackets(propName);
if flag
% propUpdatedCallback(childProp, [], propName, data.(fnames{index}).(propName));
else
propUpdatedCallback(childProp, [], propName, data.(fnames{index}).(propName));
end
selectedProp.addChild(childProp);
end
end
else
errMsg = 'The selected branch does not match the data in the data file';
%error('propertieGUI:load:branchName', errMsg);
errordlg(errMsg, 'Load error');
end
end
% runtime update item in branch (undocumented - for easier testing)
function runtimeUpdateBranch(grid, selectedProp, mirrorData, newData)
userStr = strread(selectedProp,'%s','delimiter','.');
if length(userStr)~= 1
mirrorData = findMirrorDataLevel(mirrorData, userStr);
end
selectedProp = findUserProvidedProp(grid, selectedProp);
if ~isempty(selectedProp.getValue)
propName = checkFieldName(char(selectedProp.getName));
if iscell(newData) && length(newData)==1 && isnumeric(newData{1}) % user specifying index to select.
propData = mirrorData.(propName);
if iscell(mirrorData.(propName))
userSelection = propData{newData{1}};
else
userSelection = newData;
end
if any(ismember(propData,userSelection))
selectedProp.setValue (userSelection);
propUpdatedCallback(selectedProp, [], propName, propData);
end
end
end
end % runtimeUpdateBranch
% Save callback and subfunctions
function filename = saveBranch_Callback(grid, selectedProp, lastdir, mirrorData, hFig, filename)
% Interactive use
runtimeCall = isempty(filename);
if runtimeCall
[filename, pathname] = uiputfile ({'*.branch','Branch files (*.branch)'}, 'Save as', lastdir);
if filename == 0
return
end
filename = fullfile(pathname, filename);
else % from commandline
if isempty(selectedProp) % user wants to save everything.
selectedProp = grid;
else
userStr = strread(selectedProp,'%s','delimiter','.');
if length(userStr)~= 1
mirrorData = findMirrorDataLevel(mirrorData, userStr);
end
selectedProp = findUserProvidedProp(grid, selectedProp);
end
end
if ~isempty(selectedProp.getName)
fieldname = checkFieldName(selectedProp.getName);
data.(fieldname) = selfBuildStruct(selectedProp);
fieldname = {fieldname};
else
[rootProps, data] = buildFullStruct(hFig); % (grid,mirrorData)
fieldname = fieldnames(data);
selectedProp = rootProps{1};
end
% option to save combo boxes as well...
if nargin >= 4
for fieldIdx = 1 : length(fieldname)
if fieldIdx>1 % This only happens when loading to replace the full data
selectedProp = rootProps{fieldIdx};
end
dataNames = fieldnames(mirrorData);
match = strcmpi(dataNames,fieldname{fieldIdx});
% This sub function will add all the extra items
if any(match)
% This looks in the mirrorData to update the output with cell array items.
data.(fieldname{fieldIdx}) = addOptionsToOutput(data.(fieldname{fieldIdx}), mirrorData.(dataNames{match}), selectedProp);
% Update the original var names (case sensitive)
data = updateOriginalVarNames(data, mirrorData); %data is used in the save command.
else
propName = getRecursivePropName(selectedProp, fieldname{fieldIdx});
items = strread(propName,'%s','delimiter','.');
for idx = 1 : length(items)-1
if strcmp(items{idx}(1),'(') && strcmp(items{idx}(end),')')
index = str2double(items{idx}(2:end-1));
mirrorData = mirrorData(index);
else
mirrorData = mirrorData.(items{idx});
end
end
data.(fieldname{fieldIdx}) = addOptionsToOutput(data.(fieldname{fieldIdx}), mirrorData.(items{end}), selectedProp);
% Update the original var names (case sensitive)
data = updateOriginalVarNames(data, mirrorData); %data is used in the save command.
end
end
end
% Save the data to file
save(filename, '-struct', 'data')
end
% Descent through the mirror data to find the matching variable for the user requested data
function mirrorData = findMirrorDataLevel(mirrorData, userStr)
if length(userStr)==1
return
else
[flag, index] = CheckStringForBrackets(userStr{1});
if flag
mirrorData = findMirrorDataLevel(mirrorData(index), userStr(2:end));
else
mirrorData = mirrorData.(userStr{1});
mirrorData = findMirrorDataLevel(mirrorData, userStr(2:end));
end
end
end % findMirrorDataLevel
% Search for the user specified property to load or to save
function selectedProp = findUserProvidedProp(grid, selectedProp)
index = 0;
% Loop through the properties to find the matching branch
strItems = strread(selectedProp, '%s', 'delimiter', '.');
while true
incProp = grid.getPropertyTableModel.getPropertyAt(index);
if isempty(incProp)
error('propertiesGUI:InvalidBranch', 'User provied property name which was invalid')
end
% Search the full user defined string for the item to be saved.
selectedProp = searchForPropName(incProp, strItems);
if ~isempty(selectedProp); break; end
index = index + 1;
end
end % findUserProvidedProp
% Sub function for searching down through the user provided string when A.B.C provided.
function selectedProp = searchForPropName(parentNode, userString)
selectedProp = [];
nodeName = char(parentNode.getName);
% if strcmp(nodeName(1),'(') && strcmp(nodeName(end),')')
if strcmpi(userString{1},checkFieldName(nodeName)) % ? shoudl this be case sensitive?
if length(userString) == 1
selectedProp = parentNode;
else
for jj=1:parentNode.getChildrenCount
selectedProp = searchForPropName(parentNode.getChildAt(jj-1), userString(2:end));
if ~isempty(selectedProp)
break
end
end
end
end
end % searchForPropName
% Build full struct
function [rootProps, output] = buildFullStruct(hFig) % (grid,mirrorData)
%{
% This fails if some of the top-level props are expanded (open)
index = 0;
rootProps = {};
while true
incProp = grid.getPropertyTableModel.getPropertyAt(index);
if isempty(incProp); break; end
% Search the full user defined string for the item to be saved.
propName = checkFieldName(incProp.getName);
if isfield(mirrorData,propName)
output.(propName) = selfBuildStruct(incProp);
rootProps{end+1} = incProp;
end
index = index + 1;
end
%}
propsList = getappdata(hFig, 'propsList');
rootProps = cell(propsList.toArray)';
for propIdx = 1 : numel(rootProps)
thisProp = rootProps{propIdx};
propName = checkFieldName(thisProp.getName);
output.(propName) = selfBuildStruct(thisProp);
end
end % buildFullStruct
% Build the structure for saving from the selected Prop
function output = selfBuildStruct(selectedProp)
% Self calling loop to build the output structure.
propValue = selectedProp.getValue;
% If property empty then the selectedProp is a struct.
isStruct = isempty(propValue);
nStructs = 1;
% Check if it's an array of structs
M = 1;
if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]'))
isStruct = true;
nStructs = selectedProp.getChildrenCount;
xIndex = strfind(propValue,'x');
%spIndex = strfind(propValue,' ');
M=str2double(propValue(2:xIndex-1));
%N=str2double(propValue(xIndex+1:spIndex(1)-1));
end
if isStruct
output=struct;
% Extract out each child
for ii=1:nStructs;
if nStructs>1
structLoopProp = selectedProp.getChildAt(ii-1);
else
structLoopProp = selectedProp;
end
for jj=1:structLoopProp.getChildrenCount
child = structLoopProp.getChildAt(jj-1);
fieldname = checkFieldName(child.getName);
if M==1
output(1,ii).(fieldname) = selfBuildStruct(child);
else
output(ii,1).(fieldname) = selfBuildStruct(child);
end
end
end
else
switch class(propValue)
case 'java.io.File'
output = char(propValue);
otherwise
output = propValue;
end
end
end % selfBuildStruct
% Replace any ' ' with an '_' in the output fieldname (see also getFieldLabel() above)
function fieldname = checkFieldName(fieldname)
fieldname = char(fieldname);
fieldname = regexprep(fieldname, ' \((.*)\)', '__$1');
fieldname = strrep(fieldname, ' ', '_');
fieldname(1) = upper(fieldname(1));
end % checkFieldName
% Function to add the extra options (when popupmenu) to the output
function output = addOptionsToOutput(output, mirrorData, selectedProp)
if isstruct(output) && isstruct(mirrorData)
outputFields = fieldnames(output);
mirrorFields = fieldnames(mirrorData);
for ii=1:length(output)
if length(output)>1
structLoopProp = selectedProp.getChildAt(ii-1);
else
structLoopProp = selectedProp;
end
for jj=1:numel(outputFields)
childProp = structLoopProp.getChildAt(jj-1);
% sanity check this??????childProp.getName
mirrorIndex = strcmpi(mirrorFields,outputFields{jj});
if any(mirrorIndex)
mirrorField = mirrorFields{mirrorIndex};
if isfield(mirrorData(ii), mirrorField)
if ismember('arrayData',fieldnames(get(childProp)))
arrayData = get(childProp,'ArrayData');
output(ii).(outputFields{jj}) = arrayData;
else
if iscell(mirrorData(ii).(mirrorField))
% If original was a cell -> save originals as extra items in the cell array.
output(ii).(outputFields{jj}) = UpdateCellArray(mirrorData(ii).(outputFields{jj}),output(ii).(outputFields{jj}));
% selectedIndex = find(strcmp(mirrorData.(mirrorField),output.(outputFields{ii})))==1;
%
% output.(outputFields{ii}) = {mirrorData.(mirrorField){:} {selectedIndex}};
elseif isstruct(mirrorData(ii).(mirrorField))
output(ii).(outputFields{jj}) = addOptionsToOutput(output(ii).(outputFields{jj}),mirrorData(ii).(mirrorField), childProp);
else
output(ii).(outputFields{jj}) = checkCharFieldForAbreviation(output(ii).(outputFields{jj}),mirrorData(ii).(mirrorField));
end
end
end
end
end
end
else
if ismember('arrayData',fieldnames(get(selectedProp)))
arrayData = get(selectedProp,'ArrayData');
output = arrayData;
else
if iscell(mirrorData)
output = UpdateCellArray(mirrorData,output);
else
output = checkCharFieldForAbreviation(output,mirrorData);
end
end
end
end % addOptionsToOutput
% Check to see if a char was truncated on GUI building (>50)
function output = checkCharFieldForAbreviation(output,mirrorData)
% This is to replace the ... with the original data
if ischar(output) && ... % Is it a char which has been truncated?
length(output) == 53 && ...
length(mirrorData) > 50 && ...
strcmp(output(end-2:end),'...') && ...
strcmp(output(1:50),mirrorData(1:50))
output = mirrorData;
end
end % checkCharFieldForAbreviation
% Loop through the structure and replace any in case sensitive names
function output = updateOriginalVarNames(output, mirrorData)
outputFields = fieldnames(output);
for jj=1:length(output)
if isempty(outputFields)
output = mirrorData;
else
mirrorFields = fieldnames(mirrorData);
for ii=1:numel(outputFields)
mirrorIndex = strcmpi(mirrorFields,outputFields{ii});
if any(mirrorIndex)
mirrorField = mirrorFields{mirrorIndex};
if ~strcmp(mirrorField, outputFields{ii})
output(jj).(mirrorField) = output(jj).(outputFields{ii});
if jj==length(output)
output = rmfield(output,outputFields{ii});
end
end
if isstruct(output(jj).(mirrorField))
output(jj).(mirrorField) = updateOriginalVarNames(output(jj).(mirrorField), mirrorData(jj).(mirrorField));
end
end
end
end
end
end % updateOriginalVarNames
function [flag, index] = CheckStringForBrackets(str)
index = [];
flag = strcmp(str(1),'(') && strcmp(str(end),')');
if flag
index = max(str2num(regexprep(str,'[()]',''))); % this assumes it's always (1,N) or (N,1)
end
end % CheckStringForBrackets
|
github
|
philippboehmsturm/antx-master
|
statusbar2.m
|
.m
|
antx-master/mritools/others/statusbar2.m
| 5,517 |
utf_8
|
2e007da52415e6ab6672df267410c7ab
|
%% statusbar in commandwindow
%% function statusbar2(task,varargin)
% statusbar2(0) ;%start statusbar + timer starts
% statusbar2(0, 'info1', 'info2','info3') ;%start statusbar + timer starts+ optional up to 3 infos (string) can be displayed
% statusbar2(1, 'info1UPdate', 'info2UPdate','info3UPdate'); %update statusbar's infos, but timer is not reseted
% statusbar2(-1) ; %remove timer & delete statusbars infos
function statusbar2(task,varargin)
if 0
statusbar2(0) ;%start statusbar + timer starts
statusbar2(0, 'info1', 'info2','info3') ;%start statusbar + timer starts+ optional up to 3 infos (string) can be displayed
statusbar2(1, 'info1UPdate', 'info2UPdate','info3UPdate'); %update statusbar's infos, but timer is not reseted
statusbar2(-1) ; %remove timer & delete statusbars infos
end
if task==0
timex(varargin)
elseif task==1
change(varargin);
elseif task==-1
try;
tim=timerfind('tag','timex99');
us=get(tim,'userdata');
disp(sprintf([ ' FINNISHED... processing time: ' '%2.2fmin' ],toc(us.t)/60));
delete(timerfind('tag','timex99'));
end
try; statusbar(0) ; end
end
function change(varargin)
c=timerfind('tag','timex99');
us=get(c,'userdata');
us.tg1='';
us.tg2='';
us.tg3='';
us.tg4='';
try; us.tg1=varargin{1}{1}; end
try; us.tg2=varargin{1}{2}; end
try; us.tg3=varargin{1}{3}; end
set(c,'userdata',us);
function timex(varargin)
try; delete(timerfind('tag','timex99')); ; end
% us.tg1='busy..';
% us.tg2='WARPING';
% us.tg3=strrep(pwd,filesep,[filesep filesep]);
% us.tg4='';
us.tg1='';
us.tg2='';
us.tg3='';
us.tg4='';
try; us.tg1=varargin{1}{1}; end
try; us.tg2=varargin{1}{2}; end
try; us.tg3=varargin{1}{3}; end
us.t=tic;
t = timer('period',10,'userdata',us);
set(t,'ExecutionMode','fixedrate','StartDelay',0,'tag','timex99');
set(t,'timerfcn',@update);
% set(t,'timerfcn',['t=timerfind(''tag'',''timex99'') ; us=get(t,''userdata'');' ...
% 'dt=toc(us.t);' , 'statusbar(0, sprintf([ '' '' us.task ''%2.2fmin'' ],dt/60));' ]);
% 'dt=toc(us.t); statusbar(0,num2str(dt)) ' ]);
% 'dt=toc(us.t);' , 'statusbar(0, sprintf([''%2.2f min'' ],dt/60));' ]);
start(t);
return
function update(ha,ho)
t=ha;
% t=timerfind(''tag'',''timex99'')
us=get(t,'userdata');
dt=toc(us.t);
tim=sprintf([ ' dt' '%2.2fmin' ],dt/60);
us.tg4=tim;
% m=['<html>..BACK2: <font style="font-family:verdana;color:red"><i>' ['BBB' ] ' <font style="color:blue"> bla<<font style="color:green"> bla</html> ' ];
m=['<html>' us.tg1 ' <font style="font-family:verdana;color:red"><i>' us.tg2 ' <font style="color:blue"> ' us.tg3 '<<font style="color:green"> ' us.tg4 ' </html> ' ];
statusbar(0,m);
%setDesktopStatus(m);
% setCWtitle(m);
% changeWintitle
function setCWtitle(m);
% http://stackoverflow.com/questions/1924286/is-there-a-way-to-change-the-title-of-the-matlab-command-window
% For Matlab 7:
% jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
% jDesktop.getMainFrame.setTitle('my new title');
% *or specifically for the Command Window:
% cmdWin = jDesktop.getClient('Command Window');
% cmdWin.getTopLevelAncestor.setTitle('my new title');
%
% For Matlab 6:
% jDesktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop;
% jDesktop.getMainFrame.setTitle('my new title');
% *or for the Command Window:
% cmdWin = jDesktop.getClient('Command Window');
% cmdWin.getTopLevelWindow.setTitle('my new title');
try
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jDesktop.getMainFrame.setTitle(m);
catch
jDesktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop;
jDesktop.getMainFrame.setTitle(m);
end
function changeWintitle(oldName, newName)
wins = java.awt.Window.getOwnerlessWindows();
for i = 1:numel(wins)
if isequal(char(wins(i).getTitle()), oldName)
wins(i).setTitle(newName);
end
end
%% Set the status bar text of the Matlab desktop
function setDesktopStatus(statusText)
try
% First, get the desktop reference
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance; % Matlab 7+
catch
desktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop; % Matlab 6
end
% Schedule a timer to update the status text
% Note: can't update immediately, since it will be overridden by Matlab's 'busy' message...
try
t = timer('Name','statusbarTimer', 'TimerFcn',{@setText,desktop,statusText}, 'StartDelay',0.05, 'ExecutionMode','singleShot');
start(t);
catch
% Probably an old Matlab version that still doesn't have timer
desktop.setStatusText(statusText);
end
catch
%if any(ishandle(hFig)), delete(hFig); end
error('YMA:statusbar:desktopError',['error updating desktop status text: ' lasterr]);
end
%end %#ok for Matlab 6 compatibility
%% Utility function used as setDesktopStatus's internal timer's callback
function setText(varargin)
if nargin == 4 % just in case...
targetObj = varargin{3};
statusText = varargin{4};
targetObj.setStatusText(statusText);
else
% should never happen...
end
|
github
|
philippboehmsturm/antx-master
|
load_nii_ext.m
|
.m
|
antx-master/mritools/others/nii/load_nii_ext.m
| 5,544 |
utf_8
|
09a2960b9d48f4b0363d5065f1780cbd
|
% Load NIFTI header extension after its header is loaded using load_nii_hdr.
%
% Usage: ext = load_nii_ext(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function ext = load_nii_ext(filename)
if ~exist('filename','var'),
error('Usage: ext = load_nii_ext(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',filename) & strcmp(filename(end-3:end), '.nii')
new_ext = 1;
filename(end-3:end)='';
end
if findstr('.hdr',filename) & strcmp(filename(end-3:end), '.hdr')
filename(end-3:end)='';
end
if findstr('.img',filename) & strcmp(filename(end-3:end), '.img')
filename(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', filename);
error(msg);
end
else
fn = sprintf('%s.hdr',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', filename);
error(msg);
end
end
fid = fopen(fn,'r',machine);
vox_offset = 0;
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
end
end
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return % load_nii_ext
%---------------------------------------------------------------------
function ext = read_extension(fid, vox_offset)
ext = [];
if vox_offset
end_of_ext = vox_offset;
else
fseek(fid, 0, 'eof');
end_of_ext = ftell(fid);
end
if end_of_ext > 352
fseek(fid, 348, 'bof');
ext.extension = fread(fid,4)';
end
if isempty(ext) | ext.extension(1) == 0
ext = [];
return;
end
i = 1;
while(ftell(fid) < end_of_ext)
ext.section(i).esize = fread(fid,1,'int32');
ext.section(i).ecode = fread(fid,1,'int32');
ext.section(i).edata = char(fread(fid,ext.section(i).esize-8)');
i = i + 1;
end
ext.num_ext = length(ext.section);
return % read_extension
|
github
|
philippboehmsturm/antx-master
|
rri_orient.m
|
.m
|
antx-master/mritools/others/nii/rri_orient.m
| 2,357 |
utf_8
|
e1b7cfcaf2517b7887ac6e02d9ab504d
|
% Convert image of different orientations to standard Analyze orientation
%
% Usage: nii = rri_orient(nii);
% Jimmy Shen ([email protected]), 26-APR-04
%___________________________________________________________________
function [nii, orient, pattern] = rri_orient(nii, varargin)
if nargin > 1
pattern = varargin{1};
else
pattern = [];
end
if(nargin > 2)
orient = varargin{2};
if(length(find(orient>6)) || length(find(orient<1))) %value checking
orient=[1 2 3]; %set to default if bogus values set
end
else
orient = [1 2 3];
end
dim = double(nii.hdr.dime.dim([2:4]));
if ~isempty(pattern) & ~isequal(length(pattern), prod(dim))
return;
end
% get orient of the current image
%
if isequal(orient, [1 2 3])
orient = rri_orient_ui;
pause(.1);
end
% no need for conversion
%
if isequal(orient, [1 2 3])
return;
end
if isempty(pattern)
pattern = 1:prod(dim);
end
pattern = reshape(pattern, dim);
img = nii.img;
% calculate after flip orient
%
rot_orient = mod(orient + 2, 3) + 1;
% do flip:
%
flip_orient = orient - rot_orient;
for i = 1:3
if flip_orient(i)
pattern = flipdim(pattern, i);
img = flipdim(img, i);
end
end
% get index of orient (do inverse)
%
[tmp rot_orient] = sort(rot_orient);
% do rotation:
%
pattern = permute(pattern, rot_orient);
img = permute(img, [rot_orient 4 5 6]);
% rotate resolution, or 'dim'
%
new_dim = nii.hdr.dime.dim([2:4]);
new_dim = new_dim(rot_orient);
nii.hdr.dime.dim([2:4]) = new_dim;
% rotate voxel_size, or 'pixdim'
%
tmp = nii.hdr.dime.pixdim([2:4]);
tmp = tmp(rot_orient);
nii.hdr.dime.pixdim([2:4]) = tmp;
% re-calculate originator
%
tmp = nii.hdr.hist.originator([1:3]);
tmp = tmp(rot_orient);
flip_orient = flip_orient(rot_orient);
for i = 1:3
if flip_orient(i) & ~isequal(double(tmp(i)), 0)
tmp(i) = int16(double(new_dim(i)) - double(tmp(i)) + 1);
end
end
nii.hdr.hist.originator([1:3]) = tmp;
nii.img = img;
pattern = pattern(:);
return; % rri_orient
|
github
|
philippboehmsturm/antx-master
|
save_untouch0_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/save_untouch0_nii_hdr.m
| 8,813 |
utf_8
|
a0a201073cb18f09b62842e94094c451
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar');
fwrite(fid, hk.hkey_un0(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
pad = zeros(1, 4-length(dime.vox_units));
dime.vox_units = [dime.vox_units char(pad)];
fwrite(fid, dime.vox_units(1:4), 'uchar');
pad = zeros(1, 8-length(dime.cal_units));
dime.cal_units = [dime.cal_units char(pad)];
fwrite(fid, dime.cal_units(1:8), 'uchar');
fwrite(fid, dime.unused1(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.dim_un0(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.roi_scale(1), 'float32');
fwrite(fid, dime.funused1(1), 'float32');
fwrite(fid, dime.funused2(1), 'float32');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.compressed(1), 'int32');
fwrite(fid, dime.verified(1), 'int32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures - ANALYZE 7.5
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.orient(1), 'uchar');
fwrite(fid, hist.originator(1:5), 'int16');
pad = zeros(1, 10-length(hist.generated));
hist.generated = [hist.generated char(pad)];
fwrite(fid, hist.generated(1:10), 'uchar');
pad = zeros(1, 10-length(hist.scannum));
hist.scannum = [hist.scannum char(pad)];
fwrite(fid, hist.scannum(1:10), 'uchar');
pad = zeros(1, 10-length(hist.patient_id));
hist.patient_id = [hist.patient_id char(pad)];
fwrite(fid, hist.patient_id(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_date));
hist.exp_date = [hist.exp_date char(pad)];
fwrite(fid, hist.exp_date(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_time));
hist.exp_time = [hist.exp_time char(pad)];
fwrite(fid, hist.exp_time(1:10), 'uchar');
pad = zeros(1, 3-length(hist.hist_un0));
hist.hist_un0 = [hist.hist_un0 char(pad)];
fwrite(fid, hist.hist_un0(1:3), 'uchar');
fwrite(fid, hist.views(1), 'int32');
fwrite(fid, hist.vols_added(1), 'int32');
fwrite(fid, hist.start_field(1),'int32');
fwrite(fid, hist.field_skip(1), 'int32');
fwrite(fid, hist.omax(1), 'int32');
fwrite(fid, hist.omin(1), 'int32');
fwrite(fid, hist.smax(1), 'int32');
fwrite(fid, hist.smin(1), 'int32');
return; % data_history
|
github
|
philippboehmsturm/antx-master
|
rri_zoom_menu.m
|
.m
|
antx-master/mritools/others/nii/rri_zoom_menu.m
| 770 |
utf_8
|
f0bae2b3d88fd719c47fd467e867e19f
|
% Imbed a zoom menu to any figure.
%
% Usage: rri_zoom_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = rri_zoom_menu(fig)
if isnumeric(fig)
menu_hdl = uimenu('Parent',fig, ...
'Label','Zoom on', ...
'Userdata', 1, ...
'Callback','rri_zoom_menu(''zoom'');');
return;
end
zoom_on_state = get(gcbo,'Userdata');
if (zoom_on_state == 1)
zoom on;
set(gcbo,'Userdata',0,'Label','Zoom off');
set(gcbf,'pointer','crosshair');
else
zoom off;
set(gcbo,'Userdata',1,'Label','Zoom on');
set(gcbf,'pointer','arrow');
end
return % rri_zoom_menu
|
github
|
philippboehmsturm/antx-master
|
rri_select_file.m
|
.m
|
antx-master/mritools/others/nii/rri_select_file.m
| 17,235 |
utf_8
|
0e0b14435a670dd8805aa514f7dbb6bb
|
function [selected_file, selected_path] = rri_select_file(varargin)
%
% USAGE: [selected_file, selected_path] = ...
% rri_select_file(dir_name, fig_title)
%
% Allow user to select a file from a list of Matlab competible
% file format
%
% Example:
%
% [selected_file, selected_path] = ...
% rri_select_file('/usr','Select Data File');
%
% See Also RRI_GETFILES
% -- Created June 2001 by Wilkin Chau, Rotman Research Institute
%
% use rri_select_file to open & save Matlab recognized format
% -- Modified Dec 2002 by Jimmy Shen, Rotman Research Institute
%
if nargin == 0 | ischar(varargin{1}) % create rri_select_file figure
dir_name = '';
fig_title = 'Select a File';
if nargin > 0
dir_name = varargin{1};
end
if nargin > 1
fig_title = varargin{2};
end
Init(fig_title,dir_name);
uiwait; % wait for user finish
selected_path = getappdata(gcf,'SelectedDirectory');
selected_file = getappdata(gcf,'SelectedFile');
cd (getappdata(gcf,'StartDirectory'));
close(gcf);
return;
end;
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
action = varargin{1}{1};
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
if strcmp(action,'EditFilter'),
EditFilter;
% run delete_fig when figure is closing
%
elseif strcmp(action,'delete_fig'),
delete_fig;
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
elseif strcmp(action,'select_dir'),
select_dir;
% select 'Files':
% update 'File selection'
%
elseif strcmp(action,'select_file'),
select_file;
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
elseif strcmp(action,'EditSelection'),
EditSelection;
% clicked 'Select'
%
elseif strcmp(action,'DONE_BUTTON_PRESSED'),
h = findobj(gcf,'Tag','SelectionEdit');
[filepath,filename,fileext] = fileparts(get(h,'String'));
if isempty(filepath) | isempty(filename) | isempty(fileext)
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
else
if ~strcmp(filepath(end),filesep) % not end with filesep
filepath = [filepath filesep]; % add a filesep to filepath
end
setappdata(gcf,'SelectedDirectory',filepath);
setappdata(gcf,'SelectedFile',[filename fileext]);
end
if getappdata(gcf,'ready') % ready to exit
uiresume;
end
% clicked 'cancel'
%
elseif strcmp(action,'CANCEL_BUTTON_PRESSED'),
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
set(findobj(gcf,'Tag','FileList'),'String','');
uiresume;
end;
return;
% --------------------------------------------------------------------
function Init(fig_title,dir_name),
StartDirectory = pwd;
if isempty(StartDirectory),
StartDirectory = filesep;
end;
filter_disp = {'JPEG image (*.jpg)', ...
'TIFF image, compressed (*.tif)', ...
'EPS Level 1 (*.eps)', ...
'Adobe Illustrator 88 (*.ai)', ...
'Enhanced metafile (*.emf)', ...
'Matlab Figure (*.fig)', ...
'Matlab M-file (*.m)', ...
'Portable bitmap (*.pbm)', ...
'Paintbrush 24-bit (*.pcx)', ...
'Portable Graymap (*.pgm)', ...
'Portable Network Graphics (*.png)', ...
'Portable Pixmap (*.ppm)', ...
};
filter_string = {'*.jpg', ...
'*.tif', ...
'*.eps', ...
'*.ai', ...
'*.emf', ...
'*.fig', ...
'*.m', ...
'*.pbm', ...
'*.pcx', ...
'*.pgm', ...
'*.png', ...
'*.ppm', ...
};
% filter_disp = char(filter_disp);
filter_string = char(filter_string);
margine = 0.05;
line_height = 0.07;
char_height = line_height*0.8;
save_setting_status = 'on';
rri_select_file_pos = [];
try
load('pls_profile');
catch
end
if ~isempty(rri_select_file_pos) & strcmp(save_setting_status,'on')
pos = rri_select_file_pos;
else
w = 0.4;
h = 0.6;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
h0 = figure('parent',0, 'Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name',fig_title, ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position', pos, ...
'deleteFcn','rri_select_file({''delete_fig''});', ...
'WindowStyle', 'modal', ...
'Tag','GetFilesFigure', ...
'ToolBar','none');
x = margine;
y = 1 - 1*line_height - margine;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Filter Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','Choose one of the file format:', ...
'Tag','FilterLabel');
y = 1 - 2*line_height - margine + line_height*0.2;
w = 1-2*x;
pos = [x y w h];
h_filter = uicontrol('Parent',h0, ... % Filter list
'Style','popupmenu', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', filter_disp, ...
'user', filter_string, ...
'value', 1, ...
'Callback','rri_select_file({''EditFilter''});', ...
'Tag','FilterEdit');
y = 1 - 3*line_height - margine;
w = 0.5 - x - margine/2;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Directory Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Directories', ...
'Tag','DirectoryLabel');
x = 0.5;
y = 1 - 3*line_height - margine;
w = 0.5 - margine;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % File Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Files', ...
'Tag','FileLabel');
x = margine;
y = 4*line_height + margine;
w = 0.5 - x - margine/2;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_dir = uicontrol('Parent',h0, ... % Directory Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'Interruptible', 'off', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_dir''});', ...
'Tag','DirectoryList');
x = 0.5;
y = 4*line_height + margine;
w = 0.5 - margine;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_file = uicontrol('Parent',h0, ... % File Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_file''});', ...
'Tag','FileList');
x = margine;
y = 3*line_height + margine - line_height*0.2;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Selection Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','File you selected:', ...
'Tag','SelectionLabel');
y = 2*line_height + margine;
w = 1-2*x;
pos = [x y w h];
h_select = uicontrol('Parent',h0, ... % Selection Edit
'Style','edit', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''EditSelection''});', ...
'Tag','SelectionEdit');
x = 2*margine;
y = line_height/2 + margine;
w = 0.2;
h = line_height;
pos = [x y w h];
h_done = uicontrol('Parent',h0, ... % DONE
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Save', ... % 'Select', ...
'Callback','rri_select_file({''DONE_BUTTON_PRESSED''});', ...
'Tag','DONEButton');
x = 1 - x - w;
pos = [x y w h];
h_cancel = uicontrol('Parent',h0, ... % CANCEL
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Cancel', ...
'Callback','rri_select_file({''CANCEL_BUTTON_PRESSED''});', ...
'Tag','CANCELButton');
if isempty(dir_name)
dir_name = StartDirectory;
end
set(h_select,'string',dir_name);
filter_select = get(h_filter,'value');
filter_pattern = filter_string(filter_select,:);
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
setappdata(gcf,'filter_string',filter_string);
setappdata(gcf,'h_filter', h_filter);
setappdata(gcf,'h_dir', h_dir);
setappdata(gcf,'h_file', h_file);
setappdata(gcf,'h_select', h_select);
setappdata(gcf,'h_done', h_done);
setappdata(gcf,'h_cancel', h_cancel);
setappdata(gcf,'StartDirectory',StartDirectory);
EditSelection;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % Init
% called by all the actions, to update 'Directories' or 'Files'
% based on filter_pattern. Select first file in filelist.
%
% --------------------------------------------------------------------
function update_dirlist;
filter_path = getappdata(gcf,'curr_dir');
filter_pattern = getappdata(gcf,'FilterPattern');
if exist(filter_pattern) == 2 % user input specific filename
is_single_file = 1; % need manually take path out later
else
is_single_file = 0;
end
% take the file path out from filter_pattern
%
[fpath fname fext] = fileparts(filter_pattern);
filter_pattern = [fname fext];
dir_struct = dir(filter_path);
if isempty(dir_struct)
msg = 'ERROR: Directory not found!';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
old_pointer = get(gcf,'Pointer');
set(gcf,'Pointer','watch');
dir_list = dir_struct(find([dir_struct.isdir] == 1));
[sorted_dir_names,sorted_dir_index] = sortrows({dir_list.name}');
dir_struct = dir([filter_path filesep filter_pattern]);
if isempty(dir_struct)
sorted_file_names = [];
else
file_list = dir_struct(find([dir_struct.isdir] == 0));
if is_single_file % take out path
tmp = file_list.name;
[fpath fname fext] = fileparts(tmp);
file_list.name = [fname fext];
end
[sorted_file_names,sorted_file_index] = sortrows({file_list.name}');
end;
disp_dir_names = []; % if need full path, use this
% instead of sorted_dir_names
for i=1:length(sorted_dir_names)
tmp = [filter_path filesep sorted_dir_names{i}];
disp_dir_names = [disp_dir_names {tmp}];
end
h = findobj(gcf,'Tag','DirectoryList');
set(h,'String',sorted_dir_names,'Value',1);
h = findobj(gcf,'Tag','FileList');
set(h,'String',sorted_file_names,'value',1);
h_select = getappdata(gcf,'h_select');
if strcmp(filter_path(end),filesep) % filepath end with filesep
filter_path = filter_path(1:end-1); % take filesep out
end
if isempty(sorted_file_names)
set(h_select,'string',[filter_path filesep]);
else
set(h_select,'string',[filter_path filesep sorted_file_names{1}]);
end
set(gcf,'Pointer',old_pointer);
return; % update_dirlist
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function EditFilter()
filter_select = get(gcbo,'value');
filter_string = getappdata(gcf,'filter_string');
filter_pattern = filter_string(filter_select,:);
filter_path = getappdata(gcf,'curr_dir');
% update filter_pattern
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
if isempty(filter_path),
filter_path = filesep;
end;
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % EditFilter
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function select_dir()
listed_dir = get(gcbo,'String');
selected_dir_idx = get(gcbo,'Value');
selected_dir = listed_dir{selected_dir_idx};
curr_dir = getappdata(gcf,'curr_dir');
% update the selection box
%
try
cd ([curr_dir filesep selected_dir]);
catch
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
if isempty(pwd)
curr_dir = filesep;
else
curr_dir = pwd;
end;
setappdata(gcf,'curr_dir',curr_dir);
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % select_dir
% select 'Files':
% update 'File selection'
%
% --------------------------------------------------------------------
function select_file()
setappdata(gcf,'ready',1);
listed_file = get(gcbo,'String');
selected_file_idx = get(gcbo,'Value');
selected_file = listed_file{selected_file_idx};
curr_dir = getappdata(gcf,'curr_dir');
if strcmp(curr_dir(end),filesep) % filepath end with filesep
curr_dir = curr_dir(1:end-1); % take filesep out
end
h_select = getappdata(gcf,'h_select');
set(h_select,'string',[curr_dir filesep selected_file]);
return; % select_file
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
% --------------------------------------------------------------------
function EditSelection()
filter_string = getappdata(gcf,'filter_string');
h_select = getappdata(gcf,'h_select');
selected_file = get(h_select,'string');
if exist(selected_file) == 7 % if user enter a dir
setappdata(gcf,'ready',0);
setappdata(gcf,'curr_dir',selected_file); % get new dir
update_dirlist;
else
setappdata(gcf,'ready',1);
[fpath fname fext]= fileparts(selected_file);
if exist(fpath) ~=7 % fpath is not a dir
setappdata(gcf,'ready',0);
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
% if the file format user entered is not supported by matlab
if isempty(strmatch(['*',fext],filter_string,'exact'))
setappdata(gcf,'ready',0);
msg = 'ERROR: File format is not supported by Matlab.';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
end
return; % EditSelection
% --------------------------------------------------------------------
function delete_fig()
try
load('pls_profile');
pls_profile = which('pls_profile.mat');
rri_select_file_pos = get(gcbf,'position');
save(pls_profile, '-append', 'rri_select_file_pos');
catch
end
return;
|
github
|
philippboehmsturm/antx-master
|
clip_nii.m
|
.m
|
antx-master/mritools/others/nii/clip_nii.m
| 3,421 |
utf_8
|
19da887808bddae362df38b0e9f35076
|
% CLIP_NII: Clip the NIfTI volume from any of the 6 sides
%
% Usage: nii = clip_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be cut from which side.
%
% option.cut_from_L = ( number of voxel )
% option.cut_from_R = ( number of voxel )
% option.cut_from_P = ( number of voxel )
% option.cut_from_A = ( number of voxel )
% option.cut_from_I = ( number of voxel )
% option.cut_from_S = ( number of voxel )
%
% Options description in detail:
% ==============================
%
% cut_from_L: Number of voxels from Left side will be clipped.
%
% cut_from_R: Number of voxels from Right side will be clipped.
%
% cut_from_P: Number of voxels from Posterior side will be clipped.
%
% cut_from_A: Number of voxels from Anterior side will be clipped.
%
% cut_from_I: Number of voxels from Inferior side will be clipped.
%
% cut_from_S: Number of voxels from Superior side will be clipped.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = clip_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
cut_from_L = 0;
cut_from_R = 0;
cut_from_P = 0;
cut_from_A = 0;
cut_from_I = 0;
cut_from_S = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'cut_from_L')
cut_from_L = round(opt.cut_from_L);
if cut_from_L >= origin(1) | cut_from_L < 0
error('cut_from_L cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_P')
cut_from_P = round(opt.cut_from_P);
if cut_from_P >= origin(2) | cut_from_P < 0
error('cut_from_P cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_I')
cut_from_I = round(opt.cut_from_I);
if cut_from_I >= origin(3) | cut_from_I < 0
error('cut_from_I cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_R')
cut_from_R = round(opt.cut_from_R);
if cut_from_R > dims(1)-origin(1) | cut_from_R < 0
error('cut_from_R cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_A')
cut_from_A = round(opt.cut_from_A);
if cut_from_A > dims(2)-origin(2) | cut_from_A < 0
error('cut_from_A cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_S')
cut_from_S = round(opt.cut_from_S);
if cut_from_S > dims(3)-origin(3) | cut_from_S < 0
error('cut_from_S cannot be negative or cut beyond originator');
end
end
end
nii = make_nii(nii.img( (cut_from_L+1) : (dims(1)-cut_from_R), ...
(cut_from_P+1) : (dims(2)-cut_from_A), ...
(cut_from_I+1) : (dims(3)-cut_from_S), ...
:,:,:,:,:), nii.hdr.dime.pixdim(2:4), ...
[origin(1)-cut_from_L origin(2)-cut_from_P origin(3)-cut_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
philippboehmsturm/antx-master
|
affine.m
|
.m
|
antx-master/mritools/others/nii/affine.m
| 16,664 |
utf_8
|
419b609560eb98534c0e32cc4506cc7f
|
% Using 2D or 3D affine matrix to rotate, translate, scale, reflect and
% shear a 2D image or 3D volume. 2D image is represented by a 2D matrix,
% 3D volume is represented by a 3D matrix, and data type can be real
% integer or floating-point.
%
% You may notice that MATLAB has a function called 'imtransform.m' for
% 2D spatial transformation. However, keep in mind that 'imtransform.m'
% assumes y for the 1st dimension, and x for the 2nd dimension. They are
% equivalent otherwise.
%
% In addition, if you adjust the 'new_elem_size' parameter, this 'affine.m'
% is equivalent to 'interp2.m' for 2D image, and equivalent to 'interp3.m'
% for 3D volume.
%
% Usage: [new_img new_M] = ...
% affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);
%
% old_img - original 2D image or 3D volume. We assume x for the 1st
% dimension, y for the 2nd dimension, and z for the 3rd
% dimension.
%
% old_M - a 3x3 2D affine matrix for 2D image, or a 4x4 3D affine
% matrix for 3D volume. We assume x for the 1st dimension,
% y for the 2nd dimension, and z for the 3rd dimension.
%
% new_elem_size (optional) - size of voxel along x y z direction for
% a transformed 3D volume, or size of pixel along x y for
% a transformed 2D image. We assume x for the 1st dimension
% y for the 2nd dimension, and z for the 3rd dimension.
% 'new_elem_size' is 1 if it is default or empty.
%
% You can increase its value to decrease the resampling rate,
% and make the 2D image or 3D volume more coarse. It works
% just like 'interp3'.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by the interpolation. 0 in most cases. If it is
% default or empty, 'bg' will be the average of two corner
% voxel intensities in original data.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% new_img - transformed 2D image or 3D volume
%
% new_M - transformed affine matrix
%
% Example 1 (3D rotation):
% load mri.mat; old_img = double(squeeze(D));
% old_M = [0.88 0.5 3 -90; -0.5 0.88 3 -126; 0 0 2 -72; 0 0 0 1];
% new_img = affine(old_img, old_M, 2);
% [x y z] = meshgrid(1:128,1:128,1:27);
% sz = size(new_img);
% [x1 y1 z1] = meshgrid(1:sz(2),1:sz(1),1:sz(3));
% figure; slice(x, y, z, old_img, 64, 64, 13.5);
% shading flat; colormap(map); view(-66, 66);
% figure; slice(x1, y1, z1, new_img, sz(1)/2, sz(2)/2, sz(3)/2);
% shading flat; colormap(map); view(-66, 66);
%
% Example 2 (2D interpolation):
% load mri.mat; old_img=D(:,:,1,13)';
% old_M = [1 0 0; 0 1 0; 0 0 1];
% new_img = affine(old_img, old_M, [.2 .4]);
% figure; image(old_img); colormap(map);
% figure; image(new_img); colormap(map);
%
% This program is inspired by:
% SPM5 Software from Wellcome Trust Centre for Neuroimaging
% http://www.fil.ion.ucl.ac.uk/spm/software
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [new_img, new_M] = affine(old_img, old_M, new_elem_size, verbose, bg, method)
if ~exist('old_img','var') | ~exist('old_M','var')
error('Usage: [new_img new_M] = affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);');
end
if ndims(old_img) == 3
if ~isequal(size(old_M),[4 4])
error('old_M should be a 4x4 affine matrix for 3D volume.');
end
elseif ndims(old_img) == 2
if ~isequal(size(old_M),[3 3])
error('old_M should be a 3x3 affine matrix for 2D image.');
end
else
error('old_img should be either 2D image or 3D volume.');
end
if ~exist('new_elem_size','var') | isempty(new_elem_size)
new_elem_size = [1 1 1];
elseif length(new_elem_size) < 2
new_elem_size = new_elem_size(1)*ones(1,3);
elseif length(new_elem_size) < 3
new_elem_size = [new_elem_size(:); 1]';
end
if ~exist('method','var') | isempty(method)
method = 1;
elseif ~exist('bresenham_line3d.m','file') & method == 3
error([char(10) char(10) 'Please download 3D Bresenham''s line generation program from:' char(10) char(10) 'http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21057' char(10) char(10) 'to test Fischer''s Bresenham interpolation method.' char(10) char(10)]);
end
% Make compatible to MATLAB earlier than version 7 (R14), which
% can only perform arithmetic on double data type
%
old_img = double(old_img);
old_dim = size(old_img);
if ~exist('bg','var') | isempty(bg)
bg = mean([old_img(1) old_img(end)]);
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ndims(old_img) == 2
old_dim(3) = 1;
old_M = old_M(:, [1 2 3 3]);
old_M = old_M([1 2 3 3], :);
old_M(3,:) = [0 0 1 0];
old_M(:,3) = [0 0 1 0]';
end
% Vertices of img in voxel
%
XYZvox = [ 1 1 1
1 1 old_dim(3)
1 old_dim(2) 1
1 old_dim(2) old_dim(3)
old_dim(1) 1 1
old_dim(1) 1 old_dim(3)
old_dim(1) old_dim(2) 1
old_dim(1) old_dim(2) old_dim(3) ]';
old_R = old_M(1:3,1:3);
old_T = old_M(1:3,4);
% Vertices of img in millimeter
%
XYZmm = old_R*(XYZvox-1) + repmat(old_T, [1, 8]);
% Make scale of new_M according to new_elem_size
%
new_M = diag([new_elem_size 1]);
% Make translation so minimum vertex is moved to [1,1,1]
%
new_M(1:3,4) = round( min(XYZmm,[],2) );
% New dimensions will be the maximum vertices in XYZ direction (dim_vox)
% i.e. compute dim_vox via dim_mm = R*(dim_vox-1)+T
% where, dim_mm = round(max(XYZmm,[],2));
%
new_dim = ceil(new_M(1:3,1:3) \ ( round(max(XYZmm,[],2))-new_M(1:3,4) )+1)';
% Initialize new_img with new_dim
%
new_img = zeros(new_dim(1:3));
% Mask out any changes from Z axis of transformed volume, since we
% will traverse it voxel by voxel below. We will only apply unit
% increment of mask_Z(3,4) to simulate the cursor movement
%
% i.e. we will use mask_Z * new_XYZvox to replace new_XYZvox
%
mask_Z = diag(ones(1,4));
mask_Z(3,3) = 0;
% It will be easier to do the interpolation if we invert the process
% by not traversing the original volume. Instead, we traverse the
% transformed volume, and backproject each voxel in the transformed
% volume back into the original volume. If the backprojected voxel
% in original volume is within its boundary, the intensity of that
% voxel can be used by the cursor location in the transformed volume.
%
% First, we traverse along Z axis of transformed volume voxel by voxel
%
for z = 1:new_dim(3)
if verbose & ~mod(z,10)
fprintf('%.2f percent is done.\n', 100*z/new_dim(3));
end
% We need to find out the mapping from voxel in the transformed
% volume (new_XYZvox) to voxel in the original volume (old_XYZvox)
%
% The following equation works, because they all equal to XYZmm:
% new_R*(new_XYZvox-1) + new_T == old_R*(old_XYZvox-1) + old_T
%
% We can use modified new_M1 & old_M1 to substitute new_M & old_M
% new_M1 * new_XYZvox == old_M1 * old_XYZvox
%
% where: M1 = M; M1(:,4) = M(:,4) - sum(M(:,1:3),2);
% and: M(:,4) == [T; 1] == sum(M1,2)
%
% Therefore: old_XYZvox = old_M1 \ new_M1 * new_XYZvox;
%
% Since we are traverse Z axis, and new_XYZvox is replaced
% by mask_Z * new_XYZvox, the above formula can be rewritten
% as: old_XYZvox = old_M1 \ new_M1 * mask_Z * new_XYZvox;
%
% i.e. we find the mapping from new_XYZvox to old_XYZvox:
% M = old_M1 \ new_M1 * mask_Z;
%
% First, compute modified old_M1 & new_M1
%
old_M1 = old_M; old_M1(:,4) = old_M(:,4) - sum(old_M(:,1:3),2);
new_M1 = new_M; new_M1(:,4) = new_M(:,4) - sum(new_M(:,1:3),2);
% Then, apply unit increment of mask_Z(3,4) to simulate the
% cursor movement
%
mask_Z(3,4) = z;
% Here is the mapping from new_XYZvox to old_XYZvox
%
M = old_M1 \ new_M1 * mask_Z;
switch method
case 1
new_img(:,:,z) = trilinear(old_img, new_dim, old_dim, M, bg);
case 2
new_img(:,:,z) = nearest_neighbor(old_img, new_dim, old_dim, M, bg);
case 3
new_img(:,:,z) = bresenham(old_img, new_dim, old_dim, M, bg);
end
end; % for z
if ndims(old_img) == 2
new_M(3,:) = [];
new_M(:,3) = [];
end
return; % affine
%--------------------------------------------------------------------
function img_slice = trilinear(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
TINY = 5e-2; % tolerance
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X, and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
% within boundary of original image
%
if ( old_X > 1-TINY & old_X < xdim2+TINY & ...
old_Y > 1-TINY & old_Y < ydim2+TINY & ...
old_Z > 1-TINY & old_Z < zdim2+TINY )
% Calculate distance of old_XYZ to its neighbors for
% weighted intensity average
%
dx = old_X - floor(old_X);
dy = old_Y - floor(old_Y);
dz = old_Z - floor(old_Z);
x000 = floor(old_X);
x100 = x000 + 1;
if floor(old_X) < 1
x000 = 1;
x100 = x000;
elseif floor(old_X) > xdim2-1
x000 = xdim2;
x100 = x000;
end
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
y000 = floor(old_Y);
y010 = y000 + 1;
if floor(old_Y) < 1
y000 = 1;
y100 = y000;
elseif floor(old_Y) > ydim2-1
y000 = ydim2;
y010 = y000;
end
y100 = y000;
y001 = y000;
y101 = y000;
y110 = y010;
y011 = y010;
y111 = y010;
z000 = floor(old_Z);
z001 = z000 + 1;
if floor(old_Z) < 1
z000 = 1;
z001 = z000;
elseif floor(old_Z) > zdim2-1
z000 = zdim2;
z001 = z000;
end
z100 = z000;
z010 = z000;
z110 = z000;
z101 = z001;
z011 = z001;
z111 = z001;
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
v000 = double(img(x000, y000, z000));
v010 = double(img(x010, y010, z010));
v001 = double(img(x001, y001, z001));
v011 = double(img(x011, y011, z011));
v100 = double(img(x100, y100, z100));
v110 = double(img(x110, y110, z110));
v101 = double(img(x101, y101, z101));
v111 = double(img(x111, y111, z111));
img_slice(x,y) = v000*(1-dx)*(1-dy)*(1-dz) + ...
v010*(1-dx)*dy*(1-dz) + ...
v001*(1-dx)*(1-dy)*dz + ...
v011*(1-dx)*dy*dz + ...
v100*dx*(1-dy)*(1-dz) + ...
v110*dx*dy*(1-dz) + ...
v101*dx*(1-dy)*dz + ...
v111*dx*dy*dz;
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % trilinear
%--------------------------------------------------------------------
function img_slice = nearest_neighbor(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
xi = round(old_X);
yi = round(old_Y);
zi = round(old_Z);
% within boundary of original image
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % nearest_neighbor
%--------------------------------------------------------------------
function img_slice = bresenham(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
for y = 1:ydim1
start_old_XYZ = round(M*[0 y 0 1]');
end_old_XYZ = round(M*[xdim1 y 0 1]');
[X Y Z] = bresenham_line3d(start_old_XYZ, end_old_XYZ);
% line error correction
%
% del = end_old_XYZ - start_old_XYZ;
% del_dom = max(del);
% idx_dom = find(del==del_dom);
% idx_dom = idx_dom(1);
% idx_other = [1 2 3];
% idx_other(idx_dom) = [];
%del_x1 = del(idx_other(1));
% del_x2 = del(idx_other(2));
% line_slope = sqrt((del_x1/del_dom)^2 + (del_x2/del_dom)^2 + 1);
% line_error = line_slope - 1;
% line error correction removed because it is too slow
for x = 1:xdim1
% rescale ratio
%
i = round(x * length(X) / xdim1);
if i < 1
i = 1;
elseif i > length(X)
i = length(X);
end
xi = X(i);
yi = Y(i);
zi = Z(i);
% within boundary of the old XYZ space
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
% if line_error > 1
% x = x + 1;
% if x <= xdim1
% img_slice(x,y) = img(xi,yi,zi);
% line_error = line_slope - 1;
% end
% end % if line_error
% line error correction removed because it is too slow
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % bresenham
|
github
|
philippboehmsturm/antx-master
|
load_untouch_nii_img.m
|
.m
|
antx-master/mritools/others/nii/load_untouch_nii_img.m
| 15,224 |
utf_8
|
46fb6696904467f1848e2882cd7a72f6
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_untouch_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB],[slice_idx]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
tmp = hdr.dime.dim(2:end);
tmp(find(tmp < 1)) = 1;
hdr.dime.dim(2:end) = tmp;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(slice_idx)*length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
else
img = [];
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
% ROMAN: begin
if(roman)
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
else
img = [img fread(fid, img_siz, sprintf('*%s',precision))];
end; %if(roman)
% ROMAN: end
end
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(slice_idx)
hdr.dime.dim(4) = length(slice_idx);
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
philippboehmsturm/antx-master
|
load_untouch_nii.m
|
.m
|
antx-master/mritools/others/nii/load_untouch_nii.m
| 6,373 |
utf_8
|
303eb6438d7d37e2144d554504fbdf54
|
% Load NIFTI or ANALYZE dataset, but not applying any appropriate affine
% geometric transform or voxel intensity scaling.
%
% Although according to NIFTI website, all those header information are
% supposed to be applied to the loaded NIFTI image, there are some
% situations that people do want to leave the original NIFTI header and
% data untouched. They will probably just use MATLAB to do certain image
% processing regardless of image orientation, and to save data back with
% the same NIfTI header.
%
% Since this program is only served for those situations, please use it
% together with "save_untouch_nii.m", and do not use "save_nii.m" or
% "view_nii.m" for the data that is loaded by "load_untouch_nii.m". For
% normal situation, you should use "load_nii.m" instead.
%
% Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [slice_idx])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of image volume indices.
% Only the specified volumes will be loaded. All available image
% volumes will be loaded, if it is default or empty.
%
% The number of images scans can be obtained from get_nii_frame.m,
% or simply: hdr.dime.dim(5).
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% slice_idx (optional) - a numerical array of image slice indices.
% Only the specified slices will be loaded. All available image
% slices will be loaded, if it is default or empty.
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% - Jimmy Shen ([email protected])
%
function nii = load_untouch_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, slice_idx)
if ~exist('filename','var')
error('Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [slice_idx])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx)
slice_idx = [];
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
nii.ext = [];
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
% Read the header extension
%
nii.ext = load_nii_ext(filename);
end
% Read the dataset body
%
[nii.img,nii.hdr] = load_untouch_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
% Perform some of sform/qform transform
%
% nii = xform_nii(nii, tolerance, preferredForm);
nii.untouch = 1;
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_untouch_nii
|
github
|
philippboehmsturm/antx-master
|
collapse_nii_scan.m
|
.m
|
antx-master/mritools/others/nii/collapse_nii_scan.m
| 7,038 |
utf_8
|
2d30d10b884719503df2974ff39b7093
|
% Collapse multiple single-scan NIFTI files into a multiple-scan NIFTI file
%
% Usage: collapse_nii_scan(scan_file_pattern, [collapsed_fileprefix], [scan_file_folder])
%
% Here, scan_file_pattern should look like: 'myscan_0*.img'
% If collapsed_fileprefix is omit, 'multi_scan' will be used
% If scan_file_folder is omit, current file folder will be used
%
% The order of volumes in the collapsed file will be the order of
% corresponding filenames for those selected scan files.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function collapse_nii_scan(scan_pattern, fileprefix, scan_path)
if ~exist('fileprefix','var')
fileprefix = 'multi_scan';
else
[tmp fileprefix] = fileparts(fileprefix);
end
if ~exist('scan_path','var'), scan_path = pwd; end
pnfn = fullfile(scan_path, scan_pattern);
file_lst = dir(pnfn);
flist = {file_lst.name};
flist = flist(:);
filename = flist{1};
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
end
else
if ~strcmp(filename(end-3:end), '.img') & ...
~strcmp(filename(end-3:end), '.hdr') & ...
~strcmp(filename(end-3:end), '.nii')
error('Please check filename.');
end
end
nii = load_untouch_nii(fullfile(scan_path,filename));
nii.hdr.dime.dim(5) = length(flist);
if nii.hdr.dime.dim(1) < 4
nii.hdr.dime.dim(1) = 4;
end
hdr = nii.hdr;
filetype = nii.filetype;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
elseif filetype == 1
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid);
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
glmax = -inf;
glmin = inf;
for i = 1:length(flist)
nii = load_untouch_nii(fullfile(scan_path,flist{i}));
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if nii.hdr.dime.glmax > glmax
glmax = nii.hdr.dime.glmax;
end
if nii.hdr.dime.glmin < glmin
glmin = nii.hdr.dime.glmin;
end
fwrite(fid, nii.img, precision);
end
hdr.dime.glmax = round(glmax);
hdr.dime.glmin = round(glmin);
if filetype == 2
fseek(fid, 140, 'bof');
fwrite(fid, hdr.dime.glmax, 'int32');
fwrite(fid, hdr.dime.glmin, 'int32');
elseif filetype == 1
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch_nii_hdr(hdr, fid2);
if ~isempty(ext)
save_nii_ext(ext, fid2);
end
fclose(fid2);
else
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid2);
fclose(fid2);
end
fclose(fid);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
return; % collapse_nii_scan
|
github
|
philippboehmsturm/antx-master
|
rri_orient_ui.m
|
.m
|
antx-master/mritools/others/nii/rri_orient_ui.m
| 5,635 |
utf_8
|
3361ce417798ffe2c6b53cf194b2a146
|
% Return orientation of the current image:
% orient is orientation 1x3 matrix, in that:
% Three elements represent: [x y z]
% Element value: 1 - Left to Right; 2 - Posterior to Anterior;
% 3 - Inferior to Superior; 4 - Right to Left;
% 5 - Anterior to Posterior; 6 - Superior to Inferior;
% e.g.:
% Standard RAS Orientation: [1 2 3]
% Standard RHOS Orientation: [2 4 3]
% Jimmy Shen ([email protected]), 26-APR-04
%
function orient = rri_orient_ui(varargin)
if nargin == 0
init;
orient_ui_fig = gcf;
uiwait; % wait for user finish
orient = getappdata(gcf, 'orient');
if isempty(orient)
orient = [1 2 3];
end
if ishandle(orient_ui_fig)
close(gcf);
end
return;
end
action = varargin{1};
if strcmp(action, 'done')
click_done;
elseif strcmp(action, 'cancel')
uiresume;
end
return; % rri_orient_ui
%----------------------------------------------------------------------
function init
save_setting_status = 'on';
rri_orient_pos = [];
try
load('pls_profile');
catch
end
try
load('rri_pos_profile');
catch
end
if ~isempty(rri_orient_pos) & strcmp(save_setting_status,'on')
pos = rri_orient_pos;
else
w = 0.35;
h = 0.4;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
handles.figure = figure('Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name', 'Convert to standard RAS orientation', ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position',pos, ...
'WindowStyle', 'normal', ...
'ToolBar','none');
h0 = handles.figure;
Font.FontUnits = 'point';
Font.FontSize = 12;
margin = .1;
line_num = 6;
line_ht = (1 - margin*2) / line_num;
x = margin;
y = 1 - margin - line_ht;
w = 1 - margin * 2;
h = line_ht * .7;
pos = [x y w h];
handles.Ttit = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Please input orientation of the current image:');
y = y - line_ht;
w = .2;
pos = [x y w h];
handles.Tx_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'X Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Ty_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Y Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Tz_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Z Axes:');
choice = { 'From Left to Right', 'From Posterior to Anterior', ...
'From Inferior to Superior', 'From Right to Left', ...
'From Anterior to Posterior', 'From Superior to Inferior' };
y = 1 - margin - line_ht;
y = y - line_ht;
w = 1 - margin - x - w;
x = 1 - margin - w;
pos = [x y w h];
handles.x_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 1, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.y_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 2, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.z_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 3, ...
'background', [1 1 1]);
x = margin;
y = y - line_ht * 1.5;
w = .3;
pos = [x y w h];
handles.done = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''done'');', ...
'string', 'Done');
x = 1 - margin - w;
pos = [x y w h];
handles.cancel = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''cancel'');', ...
'string', 'Cancel');
setappdata(h0, 'handles', handles);
setappdata(h0, 'orient', [1 2 3]);
return; % init
%----------------------------------------------------------------------
function click_done
handles = getappdata(gcf, 'handles');
x_orient = get(handles.x_orient, 'value');
y_orient = get(handles.y_orient, 'value');
z_orient = get(handles.z_orient, 'value');
orient = [x_orient y_orient z_orient];
test_orient = [orient, orient + 3];
test_orient = mod(test_orient, 3);
if length(unique(test_orient)) ~= 3
msgbox('Please don''t choose same or opposite direction','Error','modal');
return;
end
setappdata(gcf, 'orient', [x_orient y_orient z_orient]);
uiresume;
return; % click_done
|
github
|
philippboehmsturm/antx-master
|
load_untouch0_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/load_untouch0_nii_hdr.m
| 8,293 |
utf_8
|
d823050e9ba931a2ba7f9d9a3893d2d1
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine)
fn = sprintf('%s.hdr',fileprefix);
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.hkey_un0 = fread(fid, 1,directchar)';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
dime.dim = fread(fid,8,'int16')';
dime.vox_units = deblank(fread(fid,4,directchar)');
dime.cal_units = deblank(fread(fid,8,directchar)');
dime.unused1 = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.dim_un0 = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.roi_scale = fread(fid,1,'float32')';
dime.funused1 = fread(fid,1,'float32')';
dime.funused2 = fread(fid,1,'float32')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.compressed = fread(fid,1,'int32')';
dime.verified = fread(fid,1,'int32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.orient = fread(fid, 1,'char')';
hist.originator = fread(fid, 5,'int16')';
hist.generated = deblank(fread(fid,10,directchar)');
hist.scannum = deblank(fread(fid,10,directchar)');
hist.patient_id = deblank(fread(fid,10,directchar)');
hist.exp_date = deblank(fread(fid,10,directchar)');
hist.exp_time = deblank(fread(fid,10,directchar)');
hist.hist_un0 = deblank(fread(fid, 3,directchar)');
hist.views = fread(fid, 1,'int32')';
hist.vols_added = fread(fid, 1,'int32')';
hist.start_field = fread(fid, 1,'int32')';
hist.field_skip = fread(fid, 1,'int32')';
hist.omax = fread(fid, 1,'int32')';
hist.omin = fread(fid, 1,'int32')';
hist.smax = fread(fid, 1,'int32')';
hist.smin = fread(fid, 1,'int32')';
return % data_history
|
github
|
philippboehmsturm/antx-master
|
load_nii.m
|
.m
|
antx-master/mritools/others/nii/load_nii.m
| 7,006 |
utf_8
|
71beffc9e2b0c7e14c2f8dc8adbadbf1
|
% Load NIFTI or ANALYZE dataset. Support both *.nii and *.hdr/*.img
% file extension. If file extension is not provided, *.hdr/*.img will
% be used as default.
%
% A subset of NIFTI transform is included. For non-orthogonal rotation,
% shearing etc., please use 'reslice_nii.m' to reslice the NIFTI file.
% It will not cause negative effect, as long as you remember not to do
% slice time correction after reslicing the NIFTI file. Output variable
% nii will be in RAS orientation, i.e. X axis from Left to Right,
% Y axis from Posterior to Anterior, and Z axis from Inferior to
% Superior.
%
% Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [tolerance], [preferredForm])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of 4th dimension indices,
% which is the indices of image scan volume. The number of images
% scan volumes can be obtained from get_nii_frame.m, or simply
% hdr.dime.dim(5). Only the specified volumes will be loaded.
% All available image volumes will be loaded, if it is default or
% empty.
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed in the loaded image for any
% non-orthogonal rotation or shearing of NIfTI affine matrix. If
% you set 'tolerance' to 0, it means that you do not allow any
% distortion. If you set 'tolerance' to 1, it means that you do
% not care any distortion. The image will fail to be loaded if it
% can not be tolerated. The tolerance will be set to 0.1 (10%), if
% it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% original - the original header before any affine transform.
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = load_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, tolerance, preferredForm)
if ~exist('filename','var')
error('Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [tolerance], [preferredForm])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1; % 10 percent
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
% Read the header extension
%
% nii.ext = load_nii_ext(filename);
% Read the dataset body
%
[nii.img,nii.hdr] = load_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
% Perform some of sform/qform transform
%
nii = xform_nii(nii, tolerance, preferredForm);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_nii
|
github
|
philippboehmsturm/antx-master
|
unxform_nii.m
|
.m
|
antx-master/mritools/others/nii/unxform_nii.m
| 1,221 |
utf_8
|
ff8be64760837046b931857d59ca304e
|
% Undo the flipping and rotations performed by xform_nii; spit back only
% the raw img data block. Initial cut will only deal with 3D volumes
% strongly assume we have called xform_nii to write down the steps used
% in xform_nii.
%
% Usage: a = load_nii('original_name');
% manipulate a.img to make array b;
%
% if you use unxform_nii to un-tranform the image (img) data
% block, then nii.original.hdr is the corresponding header.
%
% nii.original.img = unxform_nii(a, b);
% save_nii(nii.original,'newname');
%
% Where, 'newname' is created with data in the same space as the
% original_name data
%
% - Jeff Gunter, 26-JUN-06
%
function outblock = unxform_nii(nii, inblock)
if isempty(nii.hdr.hist.rot_orient)
outblock=inblock;
else
[dummy unrotate_orient] = sort(nii.hdr.hist.rot_orient);
outblock = permute(inblock, unrotate_orient);
end
if ~isempty(nii.hdr.hist.flip_orient)
flip_orient = nii.hdr.hist.flip_orient(unrotate_orient);
for i = 1:3
if flip_orient(i)
outblock = flipdim(outblock, i);
end
end
end;
return;
|
github
|
philippboehmsturm/antx-master
|
load_untouch_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/load_untouch_nii_hdr.m
| 8,739 |
utf_8
|
eb068c88e2b7bb518ea557d0734bc65d
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine, filetype)
if filetype == 2
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
return % data_history
|
github
|
philippboehmsturm/antx-master
|
save_nii_ext.m
|
.m
|
antx-master/mritools/others/nii/save_nii_ext.m
| 1,015 |
utf_8
|
db919f3a7a4b2f64dae641b1e97fa4a0
|
% Save NIFTI header extension.
%
% Usage: save_nii_ext(ext, fid)
%
% ext - struct with NIFTI header extension fields.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function save_nii_ext(ext, fid)
if ~exist('ext','var') | ~exist('fid','var')
error('Usage: save_nii_ext(ext, fid)');
end
if ~isfield(ext,'extension') | ~isfield(ext,'section') | ~isfield(ext,'num_ext')
error('Wrong header extension');
end
write_ext(ext, fid);
return; % save_nii_ext
%---------------------------------------------------------------------
function write_ext(ext, fid)
fwrite(fid, ext.extension, 'uchar');
for i=1:ext.num_ext
fwrite(fid, ext.section(i).esize, 'int32');
fwrite(fid, ext.section(i).ecode, 'int32');
fwrite(fid, ext.section(i).edata, 'uchar');
end
return; % write_ext
|
github
|
philippboehmsturm/antx-master
|
view_nii_menu.m
|
.m
|
antx-master/mritools/others/nii/view_nii_menu.m
| 14,895 |
utf_8
|
d81fb80884a14ae659630258fbc330bc
|
% Imbed Zoom, Interp, and Info menu to view_nii window.
%
% Usage: view_nii_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = view_nii_menu(fig, varargin)
if isnumeric(fig)
menu_hdl = init(fig);
return;
end
menu_hdl = [];
switch fig
case 'interp'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
nii_menu = getappdata(fig, 'nii_menu');
interp_on_state = get(nii_menu.Minterp,'Userdata');
if (interp_on_state == 1)
opt.useinterp = 1;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
reset_zoom(fig);
else
opt.useinterp = 0;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
reset_zoom(fig);
end
case 'reset_zoom'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
reset_zoom(fig);
case 'orient'
orient;
case 'editvox'
editvox;
case 'img_info'
img_info;
case 'img_hist'
img_hist;
case 'save_disp'
save_disp;
end
return % view_nii_menu
%--------------------------------------------------------------------
function menu_hdl = init(fig)
% search for edit, view menu
%
nii_menu.Mfile = [];
nii_menu.Medit = [];
nii_menu.Mview = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
nii_menu.Mfile = menuitems(i);
end
editlabel = get(menuitems(i),'label');
if strcmpi(strrep(editlabel, '&', ''), 'edit')
nii_menu.Medit = menuitems(i);
end
viewlabel = get(menuitems(i),'label');
if strcmpi(strrep(viewlabel, '&', ''), 'view')
nii_menu.Mview = menuitems(i);
end
end
set(fig, 'menubar', 'none');
if isempty(nii_menu.Mfile)
nii_menu.Mfile = uimenu('Parent',fig, ...
'Label','File');
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'Callback','view_nii_menu(''save_disp'');');
else
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'separator','on', ...
'Callback','view_nii_menu(''save_disp'');');
end
if isempty(nii_menu.Medit)
nii_menu.Medit = uimenu('Parent',fig, ...
'Label','Edit');
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
else
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'separator','on', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
end
if isempty(nii_menu.Mview)
nii_menu.Mview = uimenu('Parent',fig, ...
'Label','View');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
else
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'separator','on', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
end
nii_menu.Mzoom = rri_zoom_menu(fig);
nii_menu.Minterp = uimenu('Parent',fig, ...
'Label','Interp on', ...
'Userdata', 1, ...
'Callback','view_nii_menu(''interp'');');
setappdata(fig,'nii_menu',nii_menu);
menu_hdl = nii_menu.Minterp;
return % init
%----------------------------------------------------------------
function reset_zoom(fig)
old_handle_vis = get(fig, 'HandleVisibility');
set(fig, 'HandleVisibility', 'on');
nii_view = getappdata(fig, 'nii_view');
nii_menu = getappdata(fig, 'nii_menu');
set(nii_menu.Mzoom,'Userdata',1,'Label','Zoom on');
set(fig,'pointer','arrow');
zoom off;
axes(nii_view.handles.axial_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.coronal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.sagittal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
set(fig, 'HandleVisibility', old_handle_vis);
return; % reset_zoom
%----------------------------------------------------------------
function img_info
nii_view = getappdata(gcbf, 'nii_view');
hdr = nii_view.nii.hdr;
max_value = num2str(double(max(nii_view.nii.img(:))));
min_value = num2str(double(min(nii_view.nii.img(:))));
dim = sprintf('%d %d %d', double(hdr.dime.dim(2:4)));
vox = sprintf('%.3f %.3f %.3f', double(hdr.dime.pixdim(2:4)));
if double(hdr.dime.datatype) == 1
type = '1-bit binary';
elseif double(hdr.dime.datatype) == 2
type = '8-bit unsigned integer';
elseif double(hdr.dime.datatype) == 4
type = '16-bit signed integer';
elseif double(hdr.dime.datatype) == 8
type = '32-bit signed integer';
elseif double(hdr.dime.datatype) == 16
type = '32-bit single float';
elseif double(hdr.dime.datatype) == 64
type = '64-bit double precision';
elseif double(hdr.dime.datatype) == 128
type = '24-bit RGB true color';
elseif double(hdr.dime.datatype) == 256
type = '8-bit signed integer';
elseif double(hdr.dime.datatype) == 511
type = '96-bit RGB true color';
elseif double(hdr.dime.datatype) == 512
type = '16-bit unsigned integer';
elseif double(hdr.dime.datatype) == 768
type = '32-bit unsigned integer';
elseif double(hdr.dime.datatype) == 1024
type = '64-bit signed integer';
elseif double(hdr.dime.datatype) == 1280
type = '64-bit unsigned integer';
end
msg = {};
msg = [msg {''}];
msg = [msg {['Dimension: [', dim, ']']}];
msg = [msg {''}];
msg = [msg {['Voxel Size: [', vox, ']']}];
msg = [msg {''}];
msg = [msg {['Data Type: [', type, ']']}];
msg = [msg {''}];
msg = [msg {['Max Value: [', max_value, ']']}];
msg = [msg {''}];
msg = [msg {['Min Value: [', min_value, ']']}];
msg = [msg {''}];
if isfield(nii_view.nii, 'fileprefix')
if isfield(nii_view.nii, 'filetype') & nii_view.nii.filetype == 2
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.nii]']}];
msg = [msg {''}];
elseif isfield(nii_view.nii, 'filetype')
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.img]']}];
msg = [msg {''}];
else
msg = [msg {['File Prefix: [', nii_view.nii.fileprefix, ']']}];
msg = [msg {''}];
end
end
h = msgbox(msg, 'Image Information', 'modal');
set(h,'color',[1 1 1]);
return; % img_info
%----------------------------------------------------------------
function orient
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
nii = nii_view.nii;
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
[nii orient] = rri_orient(nii);
if isequal(orient, [1 2 3]) % do nothing
set(fig,'Pointer',old_pointer);
return;
end
oldopt = view_nii(fig);
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % orient
%----------------------------------------------------------------
function editvox
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
nii = nii_view.nii;
oldopt = view_nii(fig);
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(nii.img(sag,cor,axi,1,nii_view.scanid)) double(nii.img(sag,cor,axi,2,nii_view.scanid)) double(nii.img(sag,cor,axi,3,nii_view.scanid))];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(nii.img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(nii.img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(nii.img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [R G B];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
else
imgvalue = double(nii.img(sag,cor,axi,nii_view.scanid));
init_val = sprintf('%.6g',imgvalue);
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
repeat = 1;
while repeat
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
init_val = inputdlg({'Replace the current voxel values with 3 new numbers:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
else
init_val = inputdlg({'Replace the current voxel value with 1 new number:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
end
if isempty(init_val)
set(fig,'Pointer',old_pointer);
return
end
imgvalue = str2num(init_val{1});
if ( (nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511) ...
& length(imgvalue) ~= 3 ) | ...
( (nii_view.nii.hdr.dime.datatype ~= 128 & nii_view.nii.hdr.dime.datatype ~= 511) ...
& length(imgvalue) ~= 1 )
% do nothing
else
repeat = 0;
end
end
if nii_view.nii.hdr.dime.datatype == 128
nii.img(sag,cor,axi,1,nii_view.scanid) = imgvalue(1);
nii.img(sag,cor,axi,2,nii_view.scanid) = imgvalue(2);
nii.img(sag,cor,axi,3,nii_view.scanid) = imgvalue(3);
elseif nii_view.nii.hdr.dime.datatype == 511
nii.img(sag,cor,axi,1,nii_view.scanid) = (imgvalue(1) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,2,nii_view.scanid) = (imgvalue(2) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,3,nii_view.scanid) = (imgvalue(3) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
else
nii.img(sag,cor,axi,nii_view.scanid) = imgvalue;
end
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % editvox
%----------------------------------------------------------------
function save_disp
[filename pathname] = uiputfile('*.*', 'Save displayed image as (*.nii or *.img)');
if isequal(filename,0) | isequal(pathname,0)
return;
else
out_imgfile = fullfile(pathname, filename); % original image file
end
old_pointer = get(gcbf,'Pointer');
set(gcbf,'Pointer','watch');
nii_view = getappdata(gcbf, 'nii_view');
nii = nii_view.nii;
try
save_nii(nii, out_imgfile);
catch
msg = 'File can not be saved.';
msgbox(msg, 'File write error', 'modal');
end
set(gcbf,'Pointer',old_pointer);
return; % save_disp
%----------------------------------------------------------------
function img_hist
nii_view = getappdata(gcbf, 'nii_view');
N = hist(double(nii_view.nii.img(:)),256);
x = linspace(double(min(nii_view.nii.img(:))), double(max(nii_view.nii.img(:))), 256);
figure;bar(x,N);
set(gcf, 'number', 'off', 'name', 'Volume Histogram');
set(gcf, 'windowstyle', 'modal'); % no zoom ...
xspan = max(x) - min(x) + 1;
yspan = max(N) + 1;
set(gca, 'xlim', [min(x)-xspan/20, max(x)+xspan/20]);
set(gca, 'ylim', [-yspan/20, max(N)+yspan/20]);
return; % img_hist
|
github
|
philippboehmsturm/antx-master
|
save_untouch_header_only.m
|
.m
|
antx-master/mritools/others/nii/save_untouch_header_only.m
| 2,203 |
utf_8
|
6622b1835d5ad8ce504298473ab7684f
|
% This function is only used to save Analyze or NIfTI header that is
% ended with .hdr and loaded by load_untouch_header_only.m. If you
% have NIfTI file that is ended with .nii and you want to change its
% header only, you can use load_untouch_nii / save_untouch_nii pair.
%
% Usage: save_untouch_header_only(hdr, new_header_file_name)
%
% hdr - struct with NIfTI / Analyze header fields, which is obtained from:
% hdr = load_untouch_header_only(original_header_file_name)
%
% new_header_file_name - NIfTI / Analyze header name ended with .hdr.
% You can either copy original.img(.gz) to new.img(.gz) manually,
% or simply input original.hdr(.gz) in save_untouch_header_only.m
% to overwrite the original header.
%
% - Jimmy Shen ([email protected])
%
function save_untouch_header_only(hdr, filename)
if ~exist('hdr','var') | isempty(hdr) | ~exist('filename','var') | isempty(filename)
error('Usage: save_untouch_header_only(hdr, filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.hdr.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
filename = filename(1:end-3);
end
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
write_hdr(hdr, fileprefix);
% gzip output file if requested
%
if exist('gzFile', 'var')
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
end;
return % save_untouch_header_only
%-----------------------------------------------------------------------------------
function write_hdr(hdr, fileprefix)
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if isfield(hdr.hist,'magic')
save_untouch_nii_hdr(hdr, fid);
else
save_untouch0_nii_hdr(hdr, fid);
end
fclose(fid);
return % write_hdr
|
github
|
philippboehmsturm/antx-master
|
pad_nii.m
|
.m
|
antx-master/mritools/others/nii/pad_nii.m
| 3,854 |
utf_8
|
a38d813f9f822362d873bc92725f565b
|
% PAD_NII: Pad the NIfTI volume from any of the 6 sides
%
% Usage: nii = pad_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be padded from which side.
%
% option.pad_from_L = ( number of voxel )
% option.pad_from_R = ( number of voxel )
% option.pad_from_P = ( number of voxel )
% option.pad_from_A = ( number of voxel )
% option.pad_from_I = ( number of voxel )
% option.pad_from_S = ( number of voxel )
% option.bg = [0]
%
% Options description in detail:
% ==============================
%
% pad_from_L: Number of voxels from Left side will be padded.
%
% pad_from_R: Number of voxels from Right side will be padded.
%
% pad_from_P: Number of voxels from Posterior side will be padded.
%
% pad_from_A: Number of voxels from Anterior side will be padded.
%
% pad_from_I: Number of voxels from Inferior side will be padded.
%
% pad_from_S: Number of voxels from Superior side will be padded.
%
% bg: Background intensity, which is 0 by default.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = pad_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
pad_from_L = 0;
pad_from_R = 0;
pad_from_P = 0;
pad_from_A = 0;
pad_from_I = 0;
pad_from_S = 0;
bg = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'pad_from_L')
pad_from_L = round(opt.pad_from_L);
if pad_from_L >= origin(1) | pad_from_L < 0
error('pad_from_L cannot be negative');
end
end
if isfield(opt,'pad_from_P')
pad_from_P = round(opt.pad_from_P);
if pad_from_P >= origin(2) | pad_from_P < 0
error('pad_from_P cannot be negative');
end
end
if isfield(opt,'pad_from_I')
pad_from_I = round(opt.pad_from_I);
if pad_from_I >= origin(3) | pad_from_I < 0
error('pad_from_I cannot be negative');
end
end
if isfield(opt,'pad_from_R')
pad_from_R = round(opt.pad_from_R);
if pad_from_R > dims(1)-origin(1) | pad_from_R < 0
error('pad_from_R cannot be negative');
end
end
if isfield(opt,'pad_from_A')
pad_from_A = round(opt.pad_from_A);
if pad_from_A > dims(2)-origin(2) | pad_from_A < 0
error('pad_from_A cannot be negative');
end
end
if isfield(opt,'pad_from_S')
pad_from_S = round(opt.pad_from_S);
if pad_from_S > dims(3)-origin(3) | pad_from_S < 0
error('pad_from_S cannot be negative');
end
end
if isfield(opt,'bg')
bg = opt.bg;
end
end
blk = bg * ones( pad_from_L, dims(2), dims(3) );
nii.img = cat(1, blk, nii.img);
blk = bg * ones( pad_from_R, dims(2), dims(3) );
nii.img = cat(1, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), pad_from_P, dims(3) );
nii.img = cat(2, blk, nii.img);
blk = bg * ones( dims(1), pad_from_A, dims(3) );
nii.img = cat(2, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_I );
nii.img = cat(3, blk, nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_S );
nii.img = cat(3, nii.img, blk);
nii = make_nii(nii.img, nii.hdr.dime.pixdim(2:4), ...
[origin(1)+pad_from_L origin(2)+pad_from_P origin(3)+pad_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
philippboehmsturm/antx-master
|
load_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/load_nii_hdr.m
| 10,311 |
utf_8
|
ef81f82b43da4fbd79a9de1787b5ae22
|
% internal function
% - Jimmy Shen ([email protected])
function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix)
if ~exist('fileprefix','var'),
error('Usage: [hdr, filetype, fileprefix, machine] = load_nii_hdr(filename)');
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
hdr = read_header(fid);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
hdr = read_header(fid);
fclose(fid);
end
end
end
if strcmp(hdr.hist.magic, 'n+1')
filetype = 2;
elseif strcmp(hdr.hist.magic, 'ni1')
filetype = 1;
else
filetype = 0;
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
fseek(fid,253,'bof');
hist.originator = fread(fid, 5,'int16')';
return % data_history
|
github
|
philippboehmsturm/antx-master
|
save_untouch_slice.m
|
.m
|
antx-master/mritools/others/nii/save_untouch_slice.m
| 20,263 |
utf_8
|
833f175c0298d11697418454a03993db
|
% Save back to the original image with a portion of slices that was
% loaded by "load_untouch_nii". You can process those slices matrix
% in any way, as long as their dimension is not altered.
%
% Usage: save_untouch_slice(slice, filename, ...
% slice_idx, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx])
%
% slice - a portion of slices that was loaded by "load_untouch_nii".
% This should be a numeric matrix (i.e. only the .img field in the
% loaded structure)
%
% filename - NIfTI or ANALYZE file name.
%
% slice_idx (depending on slice size) - a numerical array of image
% slice indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% img_idx (depending on slice size) - a numerical array of image
% volume indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim5_idx (depending on slice size) - a numerical array of 5th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim6_idx (depending on slice size) - a numerical array of 6th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim7_idx (depending on slice size) - a numerical array of 7th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% Example:
% nii = load_nii('avg152T1_LR_nifti.nii');
% save_nii(nii, 'test.nii');
% view_nii(nii);
% nii = load_untouch_nii('test.nii','','','','','',[40 51:53]);
% nii.img = ones(91,109,4)*122;
% save_untouch_slice(nii.img, 'test.nii', [40 51:52]);
% nii = load_nii('test.nii');
% view_nii(nii);
%
% - Jimmy Shen ([email protected])
%
function save_untouch_slice(slice, filename, slice_idx, img_idx, dim5_idx, dim6_idx, dim7_idx)
if ~exist('slice','var') | ~isnumeric(slice)
msg = [char(10) '"slice" argument should be a portion of slices that was loaded' char(10)];
msg = [msg 'by "load_untouch_nii.m". This should be a numeric matrix (i.e.' char(10)];
msg = [msg 'only the .img field in the loaded structure).'];
error(msg);
end
if ~exist('filename','var') | ~exist(filename,'file')
error('In order to save back, original NIfTI or ANALYZE file must exist.');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | ~isequal(size(slice,3),length(slice_idx))
msg = [char(10) '"slice_idx" is a numerical array of image slice indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
if ~isequal(size(slice,4),1)
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,4),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
if ~isequal(size(slice,5),1)
msg = [char(10) '"dim5_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,5),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
if ~isequal(size(slice,6),1)
msg = [char(10) '"dim6_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,6),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
if ~isequal(size(slice,7),1)
msg = [char(10) '"dim7_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,7),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
% rmdir(tmpDir,'s');
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
% fileprefix = nii.fileprefix;
filetype = nii.filetype;
if ~isequal( nii.hdr.dime.dim(2:3), [size(slice,1),size(slice,2)] )
msg = [char(10) 'The first two dimensions of slice matrix should be the same as' char(10)];
msg = [msg 'the first two dimensions of image loaded by "load_untouch_nii".'];
error(msg);
end
% Save the dataset body
%
save_untouch_slice_img(slice, nii.hdr, filetype, fileprefix, ...
nii.machine, slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
% gzip output file if requested
%
if exist('gzFileName', 'var')
[p,f] = fileparts(gzFileName);
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
movefile([fileprefix, '.img.gz']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
movefile([fileprefix, '.hdr.gz']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
movefile([fileprefix, '.nii.gz']);
end;
rmdir(tmpDir,'s');
end;
return % save_untouch_slice
%--------------------------------------------------------------------------
function save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx]);');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
return % save_untouch_slice_img
%---------------------------------------------------------------------
function write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
else
fid = fopen(sprintf('%s.img',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.img.',fileprefix);
error(msg);
end
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
msg = [char(10) char(10) ' "save_untouch_slice" is used to save back to the original image a' char(10)];
msg = [msg ' portion of slices that were loaded by "load_untouch_nii". You can' char(10)];
msg = [msg ' process those slices matrix in any way, as long as their dimension' char(10)];
msg = [msg ' is not changed.'];
error(msg);
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fwrite will write precision of value
% in img_siz times
%
fwrite(fid, slice(:,:,s,t,i5,i6,i7), sprintf('*%s',precision));
end
end
end
end
end
end
fclose(fid);
return % write_image
|
github
|
philippboehmsturm/antx-master
|
load_nii_img.m
|
.m
|
antx-master/mritools/others/nii/load_nii_img.m
| 12,720 |
utf_8
|
5670adb84a76f241bd221003bee8187d
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(5:8),ones(1,4)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
% compute size of one image
%
img_siz = prod(hdr.dime.dim(2:4));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, 1, ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 hdr.dime.dim(4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
philippboehmsturm/antx-master
|
bresenham_line3d.m
|
.m
|
antx-master/mritools/others/nii/bresenham_line3d.m
| 4,682 |
utf_8
|
f2e52d1f3ac9779b22baf3bb4d2ac201
|
% Generate X Y Z coordinates of a 3D Bresenham's line between
% two given points.
%
% A very useful application of this algorithm can be found in the
% implementation of Fischer's Bresenham interpolation method in my
% another program that can rotate three dimensional image volume
% with an affine matrix:
% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21080
%
% Usage: [X Y Z] = bresenham_line3d(P1, P2, [precision]);
%
% P1 - vector for Point1, where P1 = [x1 y1 z1]
%
% P2 - vector for Point2, where P2 = [x2 y2 z2]
%
% precision (optional) - Although according to Bresenham's line
% algorithm, point coordinates x1 y1 z1 and x2 y2 z2 should
% be integer numbers, this program extends its limit to all
% real numbers. If any of them are floating numbers, you
% should specify how many digits of decimal that you would
% like to preserve. Be aware that the length of output X Y
% Z coordinates will increase in 10 times for each decimal
% digit that you want to preserve. By default, the precision
% is 0, which means that they will be rounded to the nearest
% integer.
%
% X - a set of x coordinates on Bresenham's line
%
% Y - a set of y coordinates on Bresenham's line
%
% Z - a set of z coordinates on Bresenham's line
%
% Therefore, all points in XYZ set (i.e. P(i) = [X(i) Y(i) Z(i)])
% will constitute the Bresenham's line between P1 and P1.
%
% Example:
% P1 = [12 37 6]; P2 = [46 3 35];
% [X Y Z] = bresenham_line3d(P1, P2);
% figure; plot3(X,Y,Z,'s','markerface','b');
%
% This program is ported to MATLAB from:
%
% B.Pendleton. line3d - 3D Bresenham's (a 3D line drawing algorithm)
% ftp://ftp.isc.org/pub/usenet/comp.sources.unix/volume26/line3d, 1992
%
% Which is also referenced by:
%
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [X,Y,Z] = bresenham_line3d(P1, P2, precision)
if ~exist('precision','var') | isempty(precision) | round(precision) == 0
precision = 0;
P1 = round(P1);
P2 = round(P2);
else
precision = round(precision);
P1 = round(P1*(10^precision));
P2 = round(P2*(10^precision));
end
d = max(abs(P2-P1)+1);
X = zeros(1, d);
Y = zeros(1, d);
Z = zeros(1, d);
x1 = P1(1);
y1 = P1(2);
z1 = P1(3);
x2 = P2(1);
y2 = P2(2);
z2 = P2(3);
dx = x2 - x1;
dy = y2 - y1;
dz = z2 - z1;
ax = abs(dx)*2;
ay = abs(dy)*2;
az = abs(dz)*2;
sx = sign(dx);
sy = sign(dy);
sz = sign(dz);
x = x1;
y = y1;
z = z1;
idx = 1;
if(ax>=max(ay,az)) % x dominant
yd = ay - ax/2;
zd = az - ax/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(x == x2) % end
break;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - ax;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ax;
end
x = x + sx; % move along x
yd = yd + ay;
zd = zd + az;
end
elseif(ay>=max(ax,az)) % y dominant
xd = ax - ay/2;
zd = az - ay/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(y == y2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - ay;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ay;
end
y = y + sy; % move along y
xd = xd + ax;
zd = zd + az;
end
elseif(az>=max(ax,ay)) % z dominant
xd = ax - az/2;
yd = ay - az/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(z == z2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - az;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - az;
end
z = z + sz; % move along z
xd = xd + ax;
yd = yd + ay;
end
end
if precision ~= 0
X = X/(10^precision);
Y = Y/(10^precision);
Z = Z/(10^precision);
end
return; % bresenham_line3d
|
github
|
philippboehmsturm/antx-master
|
make_nii.m
|
.m
|
antx-master/mritools/others/nii/make_nii.m
| 7,105 |
utf_8
|
6b1565392965b164217621e71d213ddd
|
% Make NIfTI structure specified by an N-D matrix. Usually, N is 3 for
% 3D matrix [x y z], or 4 for 4D matrix with time series [x y z t].
% Optional parameters can also be included, such as: voxel_size,
% origin, datatype, and description.
%
% Once the NIfTI structure is made, it can be saved into NIfTI file
% using "save_nii" command (for more detail, type: help save_nii).
%
% Usage: nii = make_nii(img, [voxel_size], [origin], [datatype], [description])
%
% Where:
%
% img: Usually, img is a 3D matrix [x y z], or a 4D
% matrix with time series [x y z t]. However,
% NIfTI allows a maximum of 7D matrix. When the
% image is in RGB format, make sure that the size
% of 4th dimension is always 3 (i.e. [R G B]). In
% that case, make sure that you must specify RGB
% datatype, which is either 128 or 511.
%
% voxel_size (optional): Voxel size in millimeter for each
% dimension. Default is [1 1 1].
%
% origin (optional): The AC origin. Default is [0 0 0].
%
% datatype (optional): Storage data type:
% 2 - uint8, 4 - int16, 8 - int32, 16 - float32,
% 32 - complex64, 64 - float64, 128 - RGB24,
% 256 - int8, 511 - RGB96, 512 - uint16,
% 768 - uint32, 1792 - complex128
% Default will use the data type of 'img' matrix
% For RGB image, you must specify it to either 128
% or 511.
%
% description (optional): Description of data. Default is ''.
%
% e.g.:
% origin = [33 44 13]; datatype = 64;
% nii = make_nii(img, [], origin, datatype); % default voxel_size
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = make_nii(varargin)
nii.img = varargin{1};
dims = size(nii.img);
dims = [length(dims) dims ones(1,8)];
dims = dims(1:8);
voxel_size = [0 ones(1,7)];
origin = zeros(1,5);
descrip = '';
switch class(nii.img)
case 'uint8'
datatype = 2;
case 'int16'
datatype = 4;
case 'int32'
datatype = 8;
case 'single'
if isreal(nii.img)
datatype = 16;
else
datatype = 32;
end
case 'double'
if isreal(nii.img)
datatype = 64;
else
datatype = 1792;
end
case 'int8'
datatype = 256;
case 'uint16'
datatype = 512;
case 'uint32'
datatype = 768;
otherwise
error('Datatype is not supported by make_nii.');
end
if nargin > 1 & ~isempty(varargin{2})
voxel_size(2:4) = double(varargin{2});
end
if nargin > 2 & ~isempty(varargin{3})
origin(1:3) = double(varargin{3});
end
if nargin > 3 & ~isempty(varargin{4})
datatype = double(varargin{4});
if datatype == 128 | datatype == 511
dims(5) = [];
dims(1) = dims(1) - 1;
dims = [dims 1];
end
end
if nargin > 4 & ~isempty(varargin{5})
descrip = varargin{5};
end
if ndims(nii.img) > 7
error('NIfTI only allows a maximum of 7 Dimension matrix.');
end
maxval = round(double(max(nii.img(:))));
minval = round(double(min(nii.img(:))));
nii.hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval);
switch nii.hdr.dime.datatype
case 2
nii.img = uint8(nii.img);
case 4
nii.img = int16(nii.img);
case 8
nii.img = int32(nii.img);
case 16
nii.img = single(nii.img);
case 32
nii.img = single(nii.img);
case 64
nii.img = double(nii.img);
case 128
nii.img = uint8(nii.img);
case 256
nii.img = int8(nii.img);
case 511
img = double(nii.img(:));
img = single((img - min(img))/(max(img) - min(img)));
nii.img = reshape(img, size(nii.img));
nii.hdr.dime.glmax = double(max(img));
nii.hdr.dime.glmin = double(min(img));
case 512
nii.img = uint16(nii.img);
case 768
nii.img = uint32(nii.img);
case 1792
nii.img = double(nii.img);
otherwise
error('Datatype is not supported by make_nii.');
end
return; % make_nii
%---------------------------------------------------------------------
function hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval)
hdr.hk = header_key;
hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);
hdr.hist = data_history(origin, descrip);
return; % make_header
%---------------------------------------------------------------------
function hk = header_key
hk.sizeof_hdr = 348; % must be 348!
hk.data_type = '';
hk.db_name = '';
hk.extents = 0;
hk.session_error = 0;
hk.regular = 'r';
hk.dim_info = 0;
return; % header_key
%---------------------------------------------------------------------
function dime = image_dimension(dims, voxel_size, datatype, maxval, minval)
dime.dim = dims;
dime.intent_p1 = 0;
dime.intent_p2 = 0;
dime.intent_p3 = 0;
dime.intent_code = 0;
dime.datatype = datatype;
switch dime.datatype
case 2,
dime.bitpix = 8; precision = 'uint8';
case 4,
dime.bitpix = 16; precision = 'int16';
case 8,
dime.bitpix = 32; precision = 'int32';
case 16,
dime.bitpix = 32; precision = 'float32';
case 32,
dime.bitpix = 64; precision = 'float32';
case 64,
dime.bitpix = 64; precision = 'float64';
case 128
dime.bitpix = 24; precision = 'uint8';
case 256
dime.bitpix = 8; precision = 'int8';
case 511
dime.bitpix = 96; precision = 'float32';
case 512
dime.bitpix = 16; precision = 'uint16';
case 768
dime.bitpix = 32; precision = 'uint32';
case 1792,
dime.bitpix = 128; precision = 'float64';
otherwise
error('Datatype is not supported by make_nii.');
end
dime.slice_start = 0;
dime.pixdim = voxel_size;
dime.vox_offset = 0;
dime.scl_slope = 0;
dime.scl_inter = 0;
dime.slice_end = 0;
dime.slice_code = 0;
dime.xyzt_units = 0;
dime.cal_max = 0;
dime.cal_min = 0;
dime.slice_duration = 0;
dime.toffset = 0;
dime.glmax = maxval;
dime.glmin = minval;
return; % image_dimension
%---------------------------------------------------------------------
function hist = data_history(origin, descrip)
hist.descrip = descrip;
hist.aux_file = 'none';
hist.qform_code = 0;
hist.sform_code = 0;
hist.quatern_b = 0;
hist.quatern_c = 0;
hist.quatern_d = 0;
hist.qoffset_x = 0;
hist.qoffset_y = 0;
hist.qoffset_z = 0;
hist.srow_x = zeros(1,4);
hist.srow_y = zeros(1,4);
hist.srow_z = zeros(1,4);
hist.intent_name = '';
hist.magic = '';
hist.originator = origin;
return; % data_history
|
github
|
philippboehmsturm/antx-master
|
verify_nii_ext.m
|
.m
|
antx-master/mritools/others/nii/verify_nii_ext.m
| 1,721 |
utf_8
|
0339aeb8d7286e4f08165c9eeeb4c2cd
|
% Verify NIFTI header extension to make sure that each extension section
% must be an integer multiple of 16 byte long that includes the first 8
% bytes of esize and ecode. If the length of extension section is not the
% above mentioned case, edata should be padded with all 0.
%
% Usage: [ext, esize_total] = verify_nii_ext(ext)
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% esize_total - Sum of all esize variable in all header sections.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ext, esize_total] = verify_nii_ext(ext)
if ~isfield(ext, 'section')
error('Incorrect NIFTI header extension structure.');
elseif ~isfield(ext, 'num_ext')
ext.num_ext = length(ext.section);
elseif ~isfield(ext, 'extension')
ext.extension = [1 0 0 0];
end
esize_total = 0;
for i=1:ext.num_ext
if ~isfield(ext.section(i), 'ecode') | ~isfield(ext.section(i), 'edata')
error('Incorrect NIFTI header extension structure.');
end
ext.section(i).esize = ceil((length(ext.section(i).edata)+8)/16)*16;
ext.section(i).edata = ...
[ext.section(i).edata ...
zeros(1,ext.section(i).esize-length(ext.section(i).edata)-8)];
esize_total = esize_total + ext.section(i).esize;
end
return % verify_nii_ext
|
github
|
philippboehmsturm/antx-master
|
get_nii_frame.m
|
.m
|
antx-master/mritools/others/nii/get_nii_frame.m
| 4,497 |
utf_8
|
cc9b1b92f34e5ae67dc34c35a5174c75
|
% Return time frame of a NIFTI dataset. Support both *.nii and
% *.hdr/*.img file extension. If file extension is not provided,
% *.hdr/*.img will be used as default.
%
% It is a lightweighted "load_nii_hdr", and is equivalent to
% hdr.dime.dim(5)
%
% Usage: [ total_scan ] = get_nii_frame(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% total_scan - total number of image scans for the time frame
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ total_scan ] = get_nii_frame(filename)
if ~exist('filename','var'),
error('Usage: [ total_scan ] = get_nii_frame(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
fileprefix = filename;
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
if hdr.sizeof_hdr ~= 348
% first try reading the opposite endian to 'machine'
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
end
if hdr.sizeof_hdr ~= 348
% Now throw an error
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
total_scan = hdr.dim(5);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return; % get_nii_frame
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
fseek(fid,0,'bof');
dsr.sizeof_hdr = fread(fid,1,'int32')'; % should be 348!
fseek(fid,40,'bof');
dsr.dim = fread(fid,8,'int16')';
return; % read_header
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.