source: aedes_data_read.m @ 181

Last change on this file since 181 was 181, checked in by tjniskan, 8 years ago
  • Added a workaround for the uigetfile-bug in OSX version of Matlab, where uigetfile in some situations returns a directory instead of a file. This bug seems to be present at least in R2011a version of Matlab.

M aedes_getfilefilter.m
M aedes_data_read.m
M aedes_revision.m

File size: 16.0 KB
Line 
1function DATA = aedes_data_read(filename,varargin)
2% AEDES_DATA_READ - Read various image data formats to data structure
3%   
4%
5% Synopsis:
6%       DATA=aedes_data_read(filename,file_format,default_dir,varargin)
7%       
8%       or
9%
10%       DATA=aedes_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
18%       format strings are: 'vnmr', 'nifti', 'sur', 'mri', '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=aedes_data_read;   % Read image data
29%       aedes(DATA)    % Open data in Aedes
30%
31% See also:
32%       AEDES_READFID, AEDES_READCTDATA, AEDES_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, 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] = aedes_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       
84        filename = fullfile(f_path,f_name);
85       
86        % There is a bug in uigetfile in OSX version of Matlab and the
87        % fid-directory may be returned instead of the fid-file.
88        if ismac
89                if length(f_name)>3 && strcmpi(f_name(end-3:end),'.fid')
90                        filename = [filename,filesep,'fid'];
91                end
92        end
93        dataformat = aedes_getdataformat(filename);
94       
95 
96elseif nargin>=1
97  if ischar(filename)
98    [f_path,f_name,f_ext] = fileparts(filename);
99    f_path=[f_path,filesep];
100        f_name = [f_name,f_ext];
101        dataformat = aedes_getdataformat(filename);
102  else
103    error('First input argument has to be of class STRING!')
104  end
105end
106
107% Parse varargin
108for ii=1:2:length(varargin)
109  switch lower(varargin{ii})
110   case 'wbar'
111    if strcmpi(varargin{ii+1},'on')
112      showWbar = true;
113    else
114      showWbar = false;
115    end
116   
117    case 'dataformat'
118          if ~isempty(varargin{ii+1})
119                dataformat = varargin{ii+1};
120          end
121     
122    case 'default_dir'
123      % This is just a dummy case to prevent from accidently going to
124      % the "otherwise" case...
125     
126    otherwise
127      error('Unknown parameter "%s"',varargin{ii})
128   
129  end
130end
131
132
133%% Read data
134switch dataformat
135 
136  %%%%%%%%%%%%%%%%%%%%%%%%%%%
137  % Read Matlab MAT-File
138  %%%%%%%%%%%%%%%%%%%%%%%%%%%
139 case 'mat'
140
141  % Show aedes_calc_wait
142  if showWbar
143    [h,txh]=aedes_calc_wait('Loading data from Matlab MAT-File...');
144    drawnow
145  end
146 
147  %% Set data format string
148  DATA.DataFormat = 'mat';
149 
150  %% Check variables in the MAT-file
151  tmp=who('-file',filename);
152  if isempty(tmp) || ~(any(strncmpi(tmp,'data',4)) || ...
153      any(strncmpi(tmp,'images',6)))
154    if showWbar
155      delete(h)
156    end
157    DATA=[];
158    error('The MAT-file doesn''t contain the required variable "Data" or "images"!')
159  end
160 
161  % Use the "data" variable by default
162  ind=find(strncmpi(tmp,'data',4));
163  if isempty(ind)
164    % If "data" variable is not found, use the "images" variable
165    ind=find(strncmpi(tmp,'images',6));
166  end
167  dataFieldName = tmp{ind(1)};
168 
169  if showWbar
170    set(txh,'string',sprintf('%s\n%s',...
171          'Loading data from Matlab MAT-File...',...
172          ['using variable "',dataFieldName,'"']));
173    drawnow
174  end
175 
176  % Load MAT-file
177  try
178    img=load(filename,'-mat');
179  catch
180    if showWbar
181      delete(h)
182        end
183        DATA=[];
184        error('Could not read MAT-file "%s"',filename)
185  end
186 
187  % Check if data is structure or matrix
188  data = img.(dataFieldName);
189  if isstruct(data) || iscell(data)
190    DATA = data;
191    if isfield(img,'DataRotation') && ...
192        isfield(img,'DataFlip') && iscell(DATA)
193      DATA{1}.DataRotation = img.DataRotation;
194      DATA{1}.DataFlip = img.DataFlip;
195    end
196    if isfield(img,'SliceClim') && iscell(DATA)
197      DATA{1}.SliceClim = img.SliceClim;
198    end
199  elseif isnumeric(data) || islogical(data)
200     DATA.FTDATA = img.(dataFieldName);
201     DATA.HDR.fname = f_name;
202     DATA.HDR.fpath = f_path;
203     DATA.HDR.DataFormat = dataformat;
204  else
205    if showWbar
206      delete(h)
207    end
208    clear img data;
209        DATA=[];
210        error('The variable "DATA" is invalid!')
211  end
212       
213  if showWbar
214        pause(0.3)
215    delete(h)
216  end
217 
218 
219 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
220 % Read S.M.I.S. SUR-files
221 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
222 case {'sur','mri'}
223 
224  %% Set data format string
225  try
226        DATA=aedes_smisread(filename);
227  catch
228        DATA=[];
229        error('Could not read file "%s"!',filename)
230  end
231 
232  %%%%%%%%%%%%%%%%%%%%%%%%%%%
233  % Read S.M.I.S. MRD-files
234  %%%%%%%%%%%%%%%%%%%%%%%%%%%
235  case 'mrd'
236       
237        % To be written ...
238        error('Reading of S.M.I.S. MRD-Files has not been implemented!')
239 
240  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
241  % Read Analyze 7.5 and NIfTI files
242  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
243 case {'nifti'}
244 
245  % Show aedes_calc_wait
246  if showWbar
247    [h,txh]=aedes_calc_wait('Reading data in NIfTI/Analyze75 format...');
248  end
249 
250  % Read NIfTI and Analyze 7.5 header
251  [fp,fn,fe] = fileparts(filename);
252  if ~isempty(fe) && strcmpi(fe,'.img')
253    [DATA,msg]=aedes_read_nifti(filename);
254    if isempty(DATA)
255      if showWbar
256        delete(h)
257      end
258      error('Could not read data from file "%s"!',filename)
259    end
260    delete(h);
261  else
262    [DATA,msg]=aedes_read_nifti(filename,'header');
263    if isempty(DATA)
264      if showWbar
265        delete(h)
266      end
267      error('Could not read header from file "%s"!',filename)
268    end
269   
270    % Read NIfTI and Analyze 7.5 format data
271    [DATA,msg]=aedes_read_nifti(DATA.HDR);
272    if isempty(DATA)
273      if showWbar
274        delete(h)
275          end
276          error('Could not read data from file "%s"!',filename)
277    end
278    if showWbar
279      delete(h);
280    end
281  end
282 
283  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
284  % Read Varian VNMR files (FID)
285  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
286 case 'vnmr'
287 
288  if showWbar
289    showWbar = 'on';
290  else
291    showWbar = 'off';
292  end
293 
294  %% Read parameters from procpar file
295  [procpar,msg]=aedes_readprocpar([f_path,'procpar']);%,'wbar',showWbar);
296  if isempty(procpar)
297    DATA=[];
298    error(msg);
299    return
300  end
301 
302  %% Fallback defaults for reading VNMR files
303  ReadfidReturn = 1;
304  ReadfidDCcorrection = 'off';
305  ReadfidZeropadding = 'auto';
306  ReadfidSorting = 'on';
307  ReadfidFastRead = 'on';
308  ReadfidPrecision = 'single';
309  OrientImages = 'on';
310  RemoveEPIphaseIm = 'off';
311  VnmrUseOldReadFcn = true;
312 
313  %% Get defaults for Return
314  if ispref('Aedes','ReadfidReturn')
315    ReadfidReturn = getpref('Aedes','ReadfidReturn');
316  end
317
318  %% Get defaults for DC correction
319  if ispref('Aedes','ReadfidDCcorrection')
320    if getpref('Aedes','ReadfidDCcorrection')
321      ReadfidDCcorrection = 'on';
322    else
323      ReadfidDCcorrection = 'off';
324    end
325  end
326
327  %% Get defaults for Zeropadding
328  if ispref('Aedes','ReadfidZeropadding')
329    if getpref('Aedes','ReadfidZeropadding')==0
330      ReadfidZeropadding = 'off';
331    elseif getpref('Aedes','ReadfidZeropadding')==1
332      ReadfidZeropadding = 'on';
333    elseif getpref('Aedes','ReadfidZeropadding')==2
334      ReadfidZeropadding = 'auto';
335    else
336      ReadfidZeropadding = 'auto';
337    end
338  end
339
340  %% Get defaults for Sorting
341  if ispref('Aedes','ReadfidSorting')
342    if getpref('Aedes','ReadfidSorting')
343      ReadfidSorting = 'on';
344    else
345      ReadfidSorting = 'off';
346    end
347  end
348 
349  %% Get defaults for FastRead
350  if ispref('Aedes','ReadfidFastRead')
351    if getpref('Aedes','ReadfidFastRead')
352      ReadfidFastRead = 'on';
353    else
354      ReadfidFastRead = 'off';
355    end
356  end
357 
358  %% Get defaults for Precision
359  if ispref('Aedes','ReadfidPrecision')
360    if strcmpi(getpref('Aedes','ReadfidPrecision'),'single')
361      ReadfidPrecision = 'single';
362    else
363      ReadfidPrecision = 'double';
364    end
365  end
366 
367%   %% Get defaults for Reorienting EPI data
368%   if ispref('Aedes','ReadfidReorientEPI')
369%     ReorientEPI = getpref('Aedes','ReadfidReorientEPI');
370%   else
371%     ReorientEPI = 'off';
372%   end
373 
374  %% Get defaults for Reorienting EPI data
375  if ispref('Aedes','ReadfidOrientImages')
376    OrientImages = getpref('Aedes','ReadfidOrientImages');
377  else
378    OrientImages = 'on';
379  end
380 
381  %% Get defaults for removing phase image from EPI
382  if ispref('Aedes','ReadfidRemoveEPIphaseIm')
383    RemoveEPIphaseIm = getpref('Aedes','ReadfidRemoveEPIphaseIm');
384  else
385    RemoveEPIphaseIm = 'off';
386  end
387 
388  %% Get default read function
389  if ispref('Aedes','VnmrUseOldReadFcn')
390    VnmrUseOldReadFcn = getpref('Aedes','VnmrUseOldReadFcn');
391  else
392    VnmrUseOldReadFcn = true;
393  end
394 
395 
396 
397  %% Read data from fid file
398  try
399    if VnmrUseOldReadFcn
400      DATA=aedes_readfid([f_path,'fid'],...
401        'procpar',procpar,...
402        'wbar',showWbar,...
403        'Return',ReadfidReturn,...
404        'DCcorrection',ReadfidDCcorrection,...
405        'Zeropadding',ReadfidZeropadding,...
406        'sorting',ReadfidSorting,...
407        'FastRead',ReadfidFastRead,...
408        'Precision',ReadfidPrecision,...
409        'OrientImages',OrientImages,...
410        'RemoveEPIphaseIm',RemoveEPIphaseIm);
411    else
412      DATA=aedes_readvnmr([f_path,'fid'],...
413        'procpar',procpar,...
414        'wbar',showWbar,...
415        'Return',ReadfidReturn,...
416        'DCcorrection',ReadfidDCcorrection,...
417        'Zeropadding',ReadfidZeropadding,...
418        'sorting',ReadfidSorting,...
419        'FastRead',ReadfidFastRead,...
420        'Precision',ReadfidPrecision,...
421        'OrientImages',OrientImages,...
422        'RemoveEPIphaseIm',RemoveEPIphaseIm);
423    end
424    if isempty(DATA)
425      DATA=[];
426      error('Unknown error while reading "%s".',[f_path,'fid'])
427      return
428    end
429  catch
430    DATA=[];
431    error(lasterr)
432        end
433 
434        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
435  % Read Bruker file formats
436  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
437        case {'bruker_raw','bruker_reco'}
438
439                % Read Bruker data file
440                DATA = aedes_readbruker(filename);
441               
442               
443  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
444  % Read DICOM image files (DCM)
445  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
446 case 'dcm'
447 
448  % Show aedes_calc_wait
449  if showWbar
450    [h,txh]=aedes_calc_wait('Reading data from DICOM file...');
451  end
452   
453  %% Set data format string
454  DATA.DataFormat = 'dcm';
455 
456  %% Read DICOM header
457  try
458    hdr = dicominfo(filename);
459    DATA.HDR.FileHeader=hdr;
460    DATA.HDR.fname = f_name;
461    DATA.HDR.fpath = f_path;
462  catch
463        DATA=[];
464        if showWbar
465          delete(h)
466        end
467        error('Could not read header from DICOM file "%s"',...
468          filename);
469       
470  end
471 
472  %% Read DICOM data
473  try
474    DATA.FTDATA=dicomread(hdr);
475  catch
476        DATA=[];
477        if showWbar
478          delete(h)
479        end
480        error('Could not read image data from DICOM file "%s"',...
481          filename);
482  end
483  if showWbar
484        delete(h)
485  end
486 
487 
488  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
489  % Read SPECT/CT Files
490  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
491 case 'spect/ct'
492 
493  %% Read Data
494  try
495    [DATA,msg]=aedes_readctdata(filename);
496    if isempty(DATA)
497      return
498    end
499  catch
500        DATA=[];
501        error('An error occurred while reading SPECT/CT data from "%s"!',...
502          filename)
503  end
504 
505  %% Set data format string
506  DATA.DataFormat = 'spect/ct';
507 
508 
509  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
510  % Read Varian FDF Files
511  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
512  case 'fdf'
513   
514    %% Read data
515    DATA=aedes_readfdf(filename);
516    if isempty(DATA)
517      DATA=[];
518      error('An error occurred while reading FDF file "%s"!',...
519        filename)
520    end
521 
522  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
523  % Read SWIFT SGL-Files
524  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
525  case 'swift_sgl'
526   
527    % Read data
528    [DATA,msg]=aedes_readswiftsgl(filename,...
529      'datainterpsizeprompt',true,...
530      'wbar',true);
531    if isempty(DATA)
532      error(msg)
533    end
534   
535        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
536        % Read Aedes ROI-Files
537        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
538  case 'roi'
539       
540        %% Try to load the ROI-file
541    try
542      roifile = load(filename,'-mat');
543        catch
544          error('Error while reading ROI-file "%s".',...
545                filename)
546    end
547   
548    %% See if the ROI-file includes file information
549    if ~isfield(roifile,'FileInfo') || ...
550        any(cellfun(@isempty,roifile.FileInfo.DataFileName))
551          error('The ROI-file does not contain file information.')
552    end
553   
554    filenames=roifile.FileInfo.DataFileName;
555    pathnames=roifile.FileInfo.DataPathName;
556   
557    DATA={};
558        if showWbar
559          [calc_h,txh]=aedes_calc_wait({['Reading file 1/' num2str(length(filenames))], ...
560                '""'});
561        end
562
563    %% Read the files
564    for ii=1:length(filenames)
565     
566      %% Check if the file exists
567      if exist([pathnames{ii},filenames{ii}],'file')==0
568        delete(calc_h)
569                DATA=[];
570                error('Cannot find the data file "%s".',...
571                  [pathnames{ii},filenames{ii}])
572      end
573     
574      set(txh,'String',...
575              sprintf('%s\n%s',...
576                      ['Reading file ' num2str(ii) ...
577                       '/' num2str(length(filenames))],...
578                      ['"',pathnames{ii},filenames{ii},'"']))
579      drawnow
580         
581          try
582                DATA{ii}=aedes_data_read([pathnames{ii},filenames{ii}],'wbar','off');
583          catch
584                error(['Unknown error occurred while reading ROI-file "%s". ',...
585                  lasterr],...
586                  [pathnames{ii},filenames{ii}])
587          end
588    end
589    delete(calc_h)
590   
591    %Dat.LoadRoiAtStartUp = true;
592   
593    %% Use rotation information
594    if isfield(roifile,'RotateFlip')
595          if iscell(roifile.RotateFlip)
596                RotateFlip3d = roifile.RotateFlip;
597                DataRotation = false(1,length(DATA));
598                DataFlip = false(1,length(DATA));
599          else
600                DataRotation = roifile.RotateFlip.Rotate;
601                DataFlip = roifile.RotateFlip.Flip;
602                RotateFlip3d = {};
603          end
604        else
605          DataRotation = false(1,length(DATA));
606          DataFlip = false(1,length(DATA));
607          RotateFlip3d = {};
608        end
609       
610        %% Use SliceClim information
611        if isfield(roifile,'SliceClim')
612          DATA{1}.SliceClim = SliceClim;
613        end
614   
615    %% Assign the ROI-structure to the first structure
616    DATA{1}.ROI = roifile.ROI;
617    clear('roifile')
618   
619    %% Rotate images if necessary
620        if ~isempty(RotateFlip3d)
621         
622          for ii=1:length(RotateFlip3d)
623                if strcmpi(RotateFlip3d{ii}{1},'rotate')
624                  k = RotateFlip3d{ii}{2};
625                  dim = RotateFlip3d{ii}{3};
626                  DATA{1}.FTDATA = aedes_rot3d(DATA{1}.FTDATA,k,dim);
627                elseif strcmpi(RotateFlip3d{ii}{1},'flip')
628                  dim = RotateFlip3d{ii}{2};
629                  DATA{1}.FTDATA = flipdim(DATA{1}.FTDATA,dim);
630                end
631          end
632          DATA{1}.RotateFlip3d = RotateFlip3d;
633        elseif ( ~all(DataRotation==0) || ~all(DataFlip==0) )
634      for ii=1:length(DATA)
635        if DataRotation(ii)~=0
636          DATA{ii}.FTDATA = rot90(DATA{ii}.FTDATA,DataRotation(ii));
637        end
638     
639        if DataFlip(ii)~=0
640          if DataFlip(ii)==1
641            DATA{ii}.FTDATA = flipud(DATA{ii}.FTDATA);
642          elseif DataFlip(ii)==2
643            DATA{ii}.FTDATA = fliplr(DATA{ii}.FTDATA);
644          end
645        end
646          end
647          DATA{1}.DataRotation = DataRotation;
648          DATA{1}.DataFlip = DataFlip;
649        end
650       
651   
652 
653        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
654        % Unknown File Format
655        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
656  otherwise
657        DATA=[];
658        error('Unknown file format')
659end
660
Note: See TracBrowser for help on using the repository browser.

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