source: an2_data_read.m @ 44

Last change on this file since 44 was 40, checked in by tjniskan, 11 years ago
  • Rewrote the handling of the old SUR and MRI formats

(an2_smiswrite.m,an2_smisread.m). Consider this as "legacy support"...

  • Removed depricated functions write_mri.m, an2_surread.m and

an2_mriread.m

  • Now (hopefully) the name change is complete and all the license

issues are resolved...

A an2_smiswrite.m
M misclib/spectrsum.m
M misclib/shiftind.m
M misclib/nifti4dto3d.m
M misclib/nifti3dto4d.m
M misclib/dcm_info.m
M misclib/addicon.m
M misclib/makelcmraw.m
M an2_revision.m
D write_mri.m
M an2_data_read.m
D an2_surread.m
A an2_smisread.m
M aedes.m
D an2_mriread.m

File size: 15.1 KB
Line 
1function DATA = an2_data_read(filename,varargin)
2% AN2_DATA_READ - Read various image data formats to data structure
3%   
4%
5% Synopsis:
6%       DATA=an2_data_read(filename,file_format,default_dir,varargin)
7%       
8%       or
9%
10%       DATA=an2_data_read;  % (interactive mode, opens a file dialog)
11%
12% Description:
13%       The function reads image data from various different file formats
14%       into a DATA-structure. The first input argument "filename" is the
15%       full path to the data file. If the first input argument is given as
16%       an empty string, the open file dialog is shown. The second input
17%       argument is format string that defines the data format; valid format
18%       strings are: 'vnmr', 'nifti', 'sur', 'mri', 'mrd', 'ima', 'dcm',
19%       'spect/ct', 'mat'. If the format string is not given as an input
20%       argument the file extension is used to determine the data format.
21%
22%       The "default_dir" input argument is a path string defining the
23%       default directory for the open file dialog. If "default_dir" is
24%       omitted, the current directory (pwd) is used to open the file
25%       dialog.
26%
27% Examples:
28%       DATA=an2_data_read;   % Read image data
29%       aedes(DATA)    % Open data in Aedes
30%
31% See also:
32%       AN2_READFID, AN2_READCTDATA, AN2_READ_NIFTI, AEDES
33
34% This function is a part of Aedes - A graphical tool for analyzing
35% medical images
36%
37% Copyright (C) 2006 Juha-Pekka Niskanen <Juha-Pekka.Niskanen@uku.fi>
38%
39% Department of Physics, (or Department of Neurobiology)
40% University of Kuopio, FINLAND
41%
42% This program may be used under the terms of the GNU General Public
43% License version 2.0 as published by the Free Software Foundation
44% and appearing in the file LICENSE.TXT included in the packaging of
45% this program.
46%
47% This program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
48% WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
49
50
51showWbar = true; % Show wbar by default
52ddir = [pwd,filesep];
53if ~isempty(varargin)
54  if any(strcmpi(varargin,'default_dir'))
55    ind=find((strcmpi(varargin,'default_dir')));
56    try
57      ddir = varargin{ind+1};
58    catch
59      ddir = [pwd,filesep];
60    end
61  end
62end
63
64
65%% Parse input arguments
66if nargin<1 || isempty(filename)
67 
68  % Check if default directory is given
69  %if nargin==3
70  %  ddir = default_dir;
71  %else
72  %  ddir = [pwd,filesep];
73  %end
74  [filefilt,dataformats] = an2_getfilefilter;
75  [f_name, f_path, f_index] = uigetfile(...
76        filefilt, ...
77        'Select data file',ddir,...
78        'MultiSelect', 'off');
79  if isequal(f_name,0) % Cancel is pressed
80        DATA=[];
81        return
82  end
83  filename = fullfile(f_path,f_name);
84  f_ext = '';
85  dataformat = dataformats{f_index};
86 
87  if isempty(dataformat)
88        dataformat = l_GetDataFormat(filename);
89  end
90 
91elseif nargin>=1
92  if ischar(filename)
93    [f_path,f_name,f_ext] = fileparts(filename);
94    f_path=[f_path,filesep];
95        f_name = [f_name,f_ext];
96        dataformat = l_GetDataFormat(filename);
97  else
98    error('First input argument has to be of class STRING!')
99  end
100end
101
102% Parse varargin
103for ii=1:2:length(varargin)
104  switch lower(varargin{ii})
105   case 'wbar'
106    if strcmpi(varargin{ii+1},'on')
107      showWbar = true;
108    else
109      showWbar = false;
110    end
111   
112    case 'dataformat'
113          if ~isempty(varargin{ii+1})
114                dataformat = varargin{ii+1};
115          end
116     
117    case 'default_dir'
118      % This is just a dummy case to prevent from accidently going to
119      % the "otherwise" case...
120     
121    otherwise
122      error('Unknown parameter "%s"',varargin{ii})
123   
124  end
125end
126
127
128%% Read data
129switch dataformat
130 
131  %%%%%%%%%%%%%%%%%%%%%%%%%%%
132  % Read Matlab MAT-File
133  %%%%%%%%%%%%%%%%%%%%%%%%%%%
134 case 'mat'
135
136  % Show an2_calc_wait
137  if showWbar
138    [h,txh]=an2_calc_wait('Loading data from Matlab MAT-File...');
139    drawnow
140  end
141 
142  %% Set data format string
143  DATA.DataFormat = 'mat';
144 
145  %% Check variables in the MAT-file
146  tmp=who('-file',filename);
147  if isempty(tmp) || ~any(ismember(lower(tmp),{'data','images'}))
148    if showWbar
149      delete(h)
150        end
151        DATA=[];
152        error('The MAT-file doesn''t contain the required variable "Data" or "images"!')
153  end
154 
155  % Use the "data" variable by default
156  ind=find(strcmpi(tmp,'data'));
157  if isempty(ind)
158        % If "data" variable is not found, use the "images" variable
159        ind=find(strcmpi(tmp,'images'));
160  end
161  dataFieldName = tmp{ind(1)};
162 
163  if showWbar
164    set(txh,'string',sprintf('%s\n%s',...
165          'Loading data from Matlab MAT-File...',...
166          ['using variable "',dataFieldName,'"']));
167    drawnow
168  end
169 
170  % Load MAT-file
171  try
172    img=load(filename,'-mat');
173  catch
174    if showWbar
175      delete(h)
176        end
177        DATA=[];
178        error('Could not read MAT-file "%s"',filename)
179  end
180 
181  % Check if data is structure or matrix
182  data = img.(dataFieldName);
183  if isstruct(data) || iscell(data)
184    DATA = data;
185    if isfield(img,'DataRotation') && ...
186        isfield(img,'DataFlip') && iscell(DATA)
187      DATA{1}.DataRotation = img.DataRotation;
188      DATA{1}.DataFlip = img.DataFlip;
189    end
190    if isfield(img,'SliceClim') && iscell(DATA)
191      DATA{1}.SliceClim = img.SliceClim;
192    end
193  elseif isnumeric(data) || islogical(data)
194     DATA.FTDATA = img.(dataFieldName);
195     DATA.HDR.fname = f_name;
196     DATA.HDR.fpath = f_path;
197     DATA.HDR.DataType = class(DATA.FTDATA);
198     DATA.HDR.DataFormat = dataformat;
199  else
200    if showWbar
201      delete(h)
202    end
203    clear img data;
204        DATA=[];
205        error('The variable "DATA" is invalid!')
206  end
207 
208  %% If the DATA was loaded from MAT-File, it might also contain rotation
209  %% and flipping and clim information
210  if strcmpi(dataformat,'mat') && iscell(DATA)
211        if isfield(DATA{1},'DataRotation') && isfield(DATA{1},'DataFlip')
212          Dat.DataRotation = DATA{1}.DataRotation;
213          Dat.DataFlip = DATA{1}.DataFlip;
214          DATA{1}=rmfield(DATA{1},'DataRotation');
215          DATA{1}=rmfield(DATA{1},'DataFlip');
216        end
217        if isfield(DATA{1},'SliceClim')
218          Dat.SliceClim = DATA{1}.SliceClim;
219          DATA{1}=rmfield(DATA{1},'SliceClim');
220        end
221  end
222       
223  if showWbar
224        pause(0.3)
225    delete(h)
226  end
227 
228 
229 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
230 % Read S.M.I.S. SUR-files
231 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
232 case {'sur','mri'}
233 
234  %% Set data format string
235  try
236        DATA=an2_smisread(filename);
237  catch
238        DATA=[];
239        error('Could not read file "%s"!',filename)
240  end
241 
242  %%%%%%%%%%%%%%%%%%%%%%%%%%%
243  % Read S.M.I.S. MRD-files
244  %%%%%%%%%%%%%%%%%%%%%%%%%%%
245  case 'mrd'
246       
247        % To be written ...
248        error('Reading of S.M.I.S. MRD-Files has not been implemented!')
249 
250  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
251  % Read Analyze 7.5 and NIfTI files
252  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
253 case {'nifti'}
254 
255  % Show an2_calc_wait
256  if showWbar
257    [h,txh]=an2_calc_wait('Reading data in NIfTI/Analyze75 format...');
258  end
259 
260  % Read NIfTI and Analyze 7.5 header
261  if ~isempty(f_ext) && strcmpi(f_ext,'.img')
262    [DATA,msg]=an2_read_nifti(filename);
263    if isempty(DATA)
264      if showWbar
265        delete(h)
266          end
267        error('Could not read data from file "%s"!',filename)
268    end
269    delete(h);
270  else
271    [DATA,msg]=an2_read_nifti(filename,'header');
272    if isempty(DATA)
273      if showWbar
274        delete(h)
275          end
276          error('Could not read header from file "%s"!',filename)
277    end
278   
279    % Read NIfTI and Analyze 7.5 format data
280    [DATA,msg]=an2_read_nifti(DATA.HDR);
281    if isempty(DATA)
282      if showWbar
283        delete(h)
284          end
285          error('Could not read data from file "%s"!',filename)
286    end
287    if showWbar
288      delete(h);
289    end
290  end
291 
292  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
293  % Read Varian VNMR files (FID)
294  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
295 case 'vnmr'
296 
297  if showWbar
298    showWbar = 'on';
299  else
300    showWbar = 'off';
301  end
302 
303  %% Read parameters from procpar file
304  try
305    [procpar,msg]=an2_readprocpar([f_path,'procpar']);%,'wbar',showWbar);
306    if isempty(procpar)
307      DATA=[];
308      return
309    end
310  catch
311        DATA=[];
312        error('An error occurred while reading procpar file!')
313  end
314 
315  %% Get defaults for Return
316  if ispref('Aedes','ReadfidReturn')
317        ReadfidReturn = getpref('Aedes','ReadfidReturn');
318  else
319        ReadfidReturn = 1;
320  end
321
322  %% Get defaults for DC correction
323  if ispref('Aedes','ReadfidDCcorrection')
324        if getpref('Aedes','ReadfidDCcorrection')
325          ReadfidDCcorrection = 'on';
326        else
327          ReadfidDCcorrection = 'off';
328        end
329  else
330        ReadfidDCcorrection = 'off';
331  end
332
333  %% Get defaults for Zeropadding
334  if ispref('Aedes','ReadfidZeropadding')
335        if getpref('Aedes','ReadfidZeropadding')==0
336          ReadfidZeropadding = 'off';
337        elseif getpref('Aedes','ReadfidZeropadding')==1
338          ReadfidZeropadding = 'on';
339        elseif getpref('Aedes','ReadfidZeropadding')==2
340          ReadfidZeropadding = 'auto';
341        else
342          ReadfidZeropadding = 'auto';
343        end
344  else
345        ReadfidZeropadding = 'auto';
346  end
347
348  %% Get defaults for Sorting
349  if ispref('Aedes','ReadfidSorting')
350        if getpref('Aedes','ReadfidSorting')
351          ReadfidSorting = 'on';
352        else
353          ReadfidSorting = 'off';
354        end
355  else
356        ReadfidSorting = 'on';
357  end
358
359  %% Get defaults for FastRead
360  if ispref('Aedes','ReadfidFastRead')
361        if getpref('Aedes','ReadfidFastRead')
362          ReadfidFastRead = 'on';
363        else
364          ReadfidFastRead = 'off';
365        end
366  else
367        ReadfidFastRead = 'off';
368  end
369 
370  %% Get defaults for Precision
371  if ispref('Aedes','ReadfidPrecision')
372        if strcmpi(getpref('Aedes','ReadfidPrecision'),'single')
373          ReadfidPrecision = 'single';
374        else
375          ReadfidPrecision = 'double';
376        end
377  else
378        ReadfidPrecision = 'double';
379  end
380 
381  %% Read data from fid file
382  try
383    [DATA,msg]=an2_readfid([f_path,'fid'],...
384          'procpar',procpar,...
385          'wbar',showWbar,...
386          'Return',ReadfidReturn,...
387          'DCcorrection',ReadfidDCcorrection,...
388          'Zeropadding',ReadfidZeropadding,...
389          'sorting',ReadfidSorting,...
390          'FastRead',ReadfidFastRead,...
391          'Precision',ReadfidPrecision);
392    if isempty(DATA)
393      DATA=[];
394      return
395    end
396  catch
397        DATA=[];
398        error('An error occurred while reading data from "%s"!',...
399          [f_path,'fid'])
400  end
401 
402 
403  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
404  % Read DICOM image files (DCM)
405  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
406 case 'dcm'
407 
408  % Show an2_calc_wait
409  if showWbar
410    [h,txh]=an2_calc_wait('Reading data from DICOM file...');
411  end
412   
413  %% Set data format string
414  DATA.DataFormat = 'dcm';
415 
416  %% Read DICOM header
417  try
418    hdr = dicominfo(filename);
419    DATA.HDR=hdr;
420    DATA.HDR.fname = f_name;
421    DATA.HDR.fpath = f_path;
422  catch
423        DATA=[];
424        if showWbar
425          delete(h)
426        end
427        error('Could not read header from DICOM file "%s"',...
428          filename);
429       
430  end
431 
432  %% Read DICOM data
433  try
434    DATA.FTDATA=dicomread(hdr);
435  catch
436        DATA=[];
437        if showWbar
438          delete(h)
439        end
440        error('Could not read image data from DICOM file "%s"',...
441          filename);
442  end
443  if showWbar
444        delete(h)
445  end
446 
447 
448  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
449  % Read SPECT/CT Files
450  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
451 case 'spect/ct'
452 
453  %% Read Data
454  try
455    [DATA,msg]=an2_readctdata(filename);
456    if isempty(DATA)
457      return
458    end
459  catch
460        DATA=[];
461        error('An error occurred while reading SPECT/CT data from "%s"!',...
462          filename)
463  end
464 
465  %% Set data format string
466  DATA.DataFormat = 'spect/ct';
467 
468 
469  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
470  % Read Varian FDF Files
471  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
472  case 'fdf'
473   
474    %% Read data
475    [DATA,msg]=an2_readfdf(filename);
476    if isempty(DATA)
477          DATA=[];
478          error('An error occurred while reading FDF file "%s"!',...
479                filename)
480        end
481       
482        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
483        % Read Aedes ROI-Files
484        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
485  case 'roi'
486       
487        %% Try to load the ROI-file
488    try
489      roifile = load(filename,'-mat');
490        catch
491          error('Error while reading ROI-file "%s".',...
492                filename)
493    end
494   
495    %% See if the ROI-file includes file information
496    if ~isfield(roifile,'FileInfo') || ...
497        any(cellfun(@isempty,roifile.FileInfo.DataFileName))
498          error('The ROI-file does not contain file information.')
499    end
500   
501    filenames=roifile.FileInfo.DataFileName;
502    pathnames=roifile.FileInfo.DataPathName;
503   
504    DATA={};
505        if showWbar
506          [calc_h,txh]=an2_calc_wait({['Reading file 1/' num2str(length(filenames))], ...
507                '""'});
508        end
509
510    %% Read the files
511    for ii=1:length(filenames)
512     
513      %% Check if the file exists
514      if exist([pathnames{ii},filenames{ii}],'file')==0
515        delete(calc_h)
516                DATA=[];
517                error('Cannot find the data file "%s".',...
518                  [pathnames{ii},filenames{ii}])
519      end
520     
521      set(txh,'String',...
522              sprintf('%s\n%s',...
523                      ['Reading file ' num2str(ii) ...
524                       '/' num2str(length(filenames))],...
525                      ['"',pathnames{ii},filenames{ii},'"']))
526      drawnow
527         
528          try
529                DATA{ii}=an2_data_read([pathnames{ii},filenames{ii}],'wbar','off');
530          catch
531                error(['Unknown error occurred while reading ROI-file "%s". ',...
532                  lasterr],...
533                  [pathnames{ii},filenames{ii}])
534          end
535    end
536    delete(calc_h)
537   
538    %Dat.LoadRoiAtStartUp = true;
539   
540    %% Use rotation information
541    if isfield(roifile,'RotateFlip')
542      DataRotation = roifile.RotateFlip.Rotate;
543      DataFlip = roifile.RotateFlip.Flip;
544        else
545          DataRotation = false(1,length(DATA));
546          DataFlip = false(1,length(DATA));
547        end
548       
549        %% Use SliceClim information
550        if isfield(roifile,'SliceClim')
551          DATA{1}.SliceClim = SliceClim;
552        end
553   
554    %% Assign the ROI-structure to the first structure
555    DATA{1}.ROI = roifile.ROI;
556    clear('roifile')
557   
558    % Initialize GUI
559    %l_Initialize([],[]);
560   
561    %% Rotate images if necessary
562    if ( ~all(DataRotation==0) || ~all(DataFlip==0) )
563      for ii=1:length(DATA)
564        if DataRotation(ii)~=0
565          DATA{ii}.FTDATA = rot90(DATA{ii}.FTDATA,DataRotation(ii));
566        end
567     
568        if DataFlip(ii)~=0
569          if DataFlip(ii)==1
570            DATA{ii}.FTDATA = flipud(DATA{ii}.FTDATA);
571          elseif DataFlip(ii)==2
572            DATA{ii}.FTDATA = fliplr(DATA{ii}.FTDATA);
573          end
574        end
575          end
576          DATA{1}.DataRotation = DataRotation;
577          DATA{1}.DataFlip = DataFlip;
578        end
579       
580   
581 
582        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
583        % Unknown File Format
584        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
585  otherwise
586        DATA=[];
587        error('Unknown file format')
588end
589
590
591%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
592%% Local function: get the dataformat for a file
593%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
594function dataformat = l_GetDataFormat(filename)
595
596[f_path,f_name,f_ext] = fileparts(filename);
597f_path=[f_path,filesep];
598
599% Check if is gzipped NIfTI
600if strcmpi(f_ext,'.gz') && length(f_name)>3 && ...
601        strcmpi(f_name(end-3:end),'.nii')
602  f_name = f_name(1:length(f_name)-4);
603  f_ext = '.nii.gz';
604end
605
606if strcmpi(f_ext,'.fid') || isempty(f_ext) && strcmpi(f_name,'fid')
607  % Try to open as Varian VNMR file if there is no file extension
608  dataformat = 'vnmr';
609else
610  if strcmpi(f_ext,'.xxm')
611        dataformat='spect/ct';
612  elseif any(strcmpi(f_ext,{'.nii','.nii.gz','.hdr','.img'}))
613        dataformat = 'nifti';
614  elseif any(strcmpi(f_ext(2:end),...
615          {'t1r','s1r','t2r','s2r','t1','t2','s1','s2','df','sf','r2'}))
616        dataformat = 'mri';
617  else
618        dataformat = lower(f_ext(2:end)); % Remove the dot
619  end
620end
621
622if strcmpi(f_ext,'.hdr')
623  % Check if data is in Analyze/NIfTI or SPECT/CT format
624  isCtHdr = an2_checkcthdr(filename);
625  if isCtHdr
626    dataformat = 'spect/ct';
627  else
628    dataformat = 'nifti';
629  end
630end
631
632%% Check if the file is a MAT-file
633if any(strcmpi(f_ext(2:end),...
634               {'t1r','s1r','t2r','s2r','t1','t2','s1','s2','df','sf','mri','r2'}))
635  if isempty(who('-file',filename))
636    dataformat = 'mri';
637  else
638    dataformat = 'mat';
639  end
640end
Note: See TracBrowser for help on using the repository browser.

Powered by Trac 1.0.9.Copyright © Juha-Pekka Niskanen 2008