source: aedes_data_read.m @ 131

Last change on this file since 131 was 123, checked in by tjniskan, 9 years ago
  • Fixed a bug in reading MAT-files

M aedes_data_read.m
M aedes_revision.m

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

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