source: aedes_data_read.m

Last change on this file was 183, checked in by tjniskan, 6 years ago

M aedes_data_read.m
M aedes_revision.m

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

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