source: an2_data_read.m @ 77

Last change on this file since 77 was 77, checked in by tjniskan, 10 years ago
  • Fixed a strange bug related to resizing Aedes window in Matlab

R2008a (and possibly R2008b and R2009a).

  • Fixed bugs of Voxel TimeSeries? and Overlay Control figure

handles not being properly destroyed on exit.

  • Changed default values for reading VNMR files (now Fast Read is on

by default, output precision is single and data is oriented using
PROCPAR.orient)

  • Fixed a bug in the calculate SNR -plugin
  • Made a temporary workaround for controlling the output in the "View

ROI statistics" -table. A proper GUI implementation will (hopefully) follow
shortly. The output can be controlled by using Aedes preferences. For
example setpref('Aedes','StatPrintDirs?','TXYZV') will print in the
output Total, X-dir, Y-dir, Z-dir and V-dir statistics.

M an2_revision.m
M an2_data_read.m
M an2_resviewer.m
M aedes.m
M an2_res2table.m
M plugins/calculate_snr.m
M an2_readfid.m
M an2_readfidprefs.m
M an2_roi_stats.m

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

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