source: an2_data_read.m @ 48

Last change on this file since 48 was 46, checked in by tjniskan, 11 years ago
  • Added preliminary support for reading multiple 3D files into Aedes

as 4D data.

  • Added new function an2_getdataformat.m which tries to determine data

format of a file. The code in an2_checkcthdr.m is now part of
an2_getdataformat.m and hence the depricated an2_checkcthdr.m was
removed.

  • Removed depricated function an2_mrdread.m
  • Fixed a small bug in an2_juigetfiles.m that appeared in Linux

version of Matlab.

M an2_getfilefilter.m
D an2_checkcthdr.m
M an2_read_nifti.m
M an2_data_read.m
D an2_mrdread.m
M aedes.m
M an2_juigetfiles.m
M an2_editstack.m
A an2_getdataformat.m
M an2_write_nifti.m

File size: 13.7 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.DataType = class(DATA.FTDATA);
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 the DATA was loaded from MAT-File, it might also contain rotation
204  %% and flipping and clim information
205  if strcmpi(dataformat,'mat') && iscell(DATA)
206        if isfield(DATA{1},'DataRotation') && isfield(DATA{1},'DataFlip')
207          Dat.DataRotation = DATA{1}.DataRotation;
208          Dat.DataFlip = DATA{1}.DataFlip;
209          DATA{1}=rmfield(DATA{1},'DataRotation');
210          DATA{1}=rmfield(DATA{1},'DataFlip');
211        end
212        if isfield(DATA{1},'SliceClim')
213          Dat.SliceClim = DATA{1}.SliceClim;
214          DATA{1}=rmfield(DATA{1},'SliceClim');
215        end
216  end
217       
218  if showWbar
219        pause(0.3)
220    delete(h)
221  end
222 
223 
224 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
225 % Read S.M.I.S. SUR-files
226 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
227 case {'sur','mri'}
228 
229  %% Set data format string
230  try
231        DATA=an2_smisread(filename);
232  catch
233        DATA=[];
234        error('Could not read file "%s"!',filename)
235  end
236 
237  %%%%%%%%%%%%%%%%%%%%%%%%%%%
238  % Read S.M.I.S. MRD-files
239  %%%%%%%%%%%%%%%%%%%%%%%%%%%
240  case 'mrd'
241       
242        % To be written ...
243        error('Reading of S.M.I.S. MRD-Files has not been implemented!')
244 
245  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
246  % Read Analyze 7.5 and NIfTI files
247  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
248 case {'nifti'}
249 
250  % Show an2_calc_wait
251  if showWbar
252    [h,txh]=an2_calc_wait('Reading data in NIfTI/Analyze75 format...');
253  end
254 
255  % Read NIfTI and Analyze 7.5 header
256  [fp,fn,fe] = fileparts(filename);
257  if ~isempty(fe) && strcmpi(fe,'.img')
258    [DATA,msg]=an2_read_nifti(filename);
259    if isempty(DATA)
260      if showWbar
261        delete(h)
262          end
263        error('Could not read data from file "%s"!',filename)
264    end
265    delete(h);
266  else
267    [DATA,msg]=an2_read_nifti(filename,'header');
268    if isempty(DATA)
269      if showWbar
270        delete(h)
271          end
272          error('Could not read header from file "%s"!',filename)
273    end
274   
275    % Read NIfTI and Analyze 7.5 format data
276    [DATA,msg]=an2_read_nifti(DATA.HDR);
277    if isempty(DATA)
278      if showWbar
279        delete(h)
280          end
281          error('Could not read data from file "%s"!',filename)
282    end
283    if showWbar
284      delete(h);
285    end
286  end
287 
288  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
289  % Read Varian VNMR files (FID)
290  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
291 case 'vnmr'
292 
293  if showWbar
294    showWbar = 'on';
295  else
296    showWbar = 'off';
297  end
298 
299  %% Read parameters from procpar file
300  try
301    [procpar,msg]=an2_readprocpar([f_path,'procpar']);%,'wbar',showWbar);
302    if isempty(procpar)
303      DATA=[];
304      return
305    end
306  catch
307        DATA=[];
308        error('An error occurred while reading procpar file!')
309  end
310 
311  %% Get defaults for Return
312  if ispref('Aedes','ReadfidReturn')
313        ReadfidReturn = getpref('Aedes','ReadfidReturn');
314  else
315        ReadfidReturn = 1;
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  else
326        ReadfidDCcorrection = 'off';
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  else
341        ReadfidZeropadding = 'auto';
342  end
343
344  %% Get defaults for Sorting
345  if ispref('Aedes','ReadfidSorting')
346        if getpref('Aedes','ReadfidSorting')
347          ReadfidSorting = 'on';
348        else
349          ReadfidSorting = 'off';
350        end
351  else
352        ReadfidSorting = 'on';
353  end
354
355  %% Get defaults for FastRead
356  if ispref('Aedes','ReadfidFastRead')
357        if getpref('Aedes','ReadfidFastRead')
358          ReadfidFastRead = 'on';
359        else
360          ReadfidFastRead = 'off';
361        end
362  else
363        ReadfidFastRead = 'off';
364  end
365 
366  %% Get defaults for Precision
367  if ispref('Aedes','ReadfidPrecision')
368        if strcmpi(getpref('Aedes','ReadfidPrecision'),'single')
369          ReadfidPrecision = 'single';
370        else
371          ReadfidPrecision = 'double';
372        end
373  else
374        ReadfidPrecision = 'double';
375  end
376 
377  %% Read data from fid file
378  try
379    [DATA,msg]=an2_readfid([f_path,'fid'],...
380          'procpar',procpar,...
381          'wbar',showWbar,...
382          'Return',ReadfidReturn,...
383          'DCcorrection',ReadfidDCcorrection,...
384          'Zeropadding',ReadfidZeropadding,...
385          'sorting',ReadfidSorting,...
386          'FastRead',ReadfidFastRead,...
387          'Precision',ReadfidPrecision);
388    if isempty(DATA)
389      DATA=[];
390      return
391    end
392  catch
393        DATA=[];
394        error('An error occurred while reading data from "%s"!',...
395          [f_path,'fid'])
396  end
397 
398 
399  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
400  % Read DICOM image files (DCM)
401  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
402 case 'dcm'
403 
404  % Show an2_calc_wait
405  if showWbar
406    [h,txh]=an2_calc_wait('Reading data from DICOM file...');
407  end
408   
409  %% Set data format string
410  DATA.DataFormat = 'dcm';
411 
412  %% Read DICOM header
413  try
414    hdr = dicominfo(filename);
415    DATA.HDR=hdr;
416    DATA.HDR.fname = f_name;
417    DATA.HDR.fpath = f_path;
418  catch
419        DATA=[];
420        if showWbar
421          delete(h)
422        end
423        error('Could not read header from DICOM file "%s"',...
424          filename);
425       
426  end
427 
428  %% Read DICOM data
429  try
430    DATA.FTDATA=dicomread(hdr);
431  catch
432        DATA=[];
433        if showWbar
434          delete(h)
435        end
436        error('Could not read image data from DICOM file "%s"',...
437          filename);
438  end
439  if showWbar
440        delete(h)
441  end
442 
443 
444  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
445  % Read SPECT/CT Files
446  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
447 case 'spect/ct'
448 
449  %% Read Data
450  try
451    [DATA,msg]=an2_readctdata(filename);
452    if isempty(DATA)
453      return
454    end
455  catch
456        DATA=[];
457        error('An error occurred while reading SPECT/CT data from "%s"!',...
458          filename)
459  end
460 
461  %% Set data format string
462  DATA.DataFormat = 'spect/ct';
463 
464 
465  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
466  % Read Varian FDF Files
467  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
468  case 'fdf'
469   
470    %% Read data
471    [DATA,msg]=an2_readfdf(filename);
472    if isempty(DATA)
473          DATA=[];
474          error('An error occurred while reading FDF file "%s"!',...
475                filename)
476        end
477       
478        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
479        % Read Aedes ROI-Files
480        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
481  case 'roi'
482       
483        %% Try to load the ROI-file
484    try
485      roifile = load(filename,'-mat');
486        catch
487          error('Error while reading ROI-file "%s".',...
488                filename)
489    end
490   
491    %% See if the ROI-file includes file information
492    if ~isfield(roifile,'FileInfo') || ...
493        any(cellfun(@isempty,roifile.FileInfo.DataFileName))
494          error('The ROI-file does not contain file information.')
495    end
496   
497    filenames=roifile.FileInfo.DataFileName;
498    pathnames=roifile.FileInfo.DataPathName;
499   
500    DATA={};
501        if showWbar
502          [calc_h,txh]=an2_calc_wait({['Reading file 1/' num2str(length(filenames))], ...
503                '""'});
504        end
505
506    %% Read the files
507    for ii=1:length(filenames)
508     
509      %% Check if the file exists
510      if exist([pathnames{ii},filenames{ii}],'file')==0
511        delete(calc_h)
512                DATA=[];
513                error('Cannot find the data file "%s".',...
514                  [pathnames{ii},filenames{ii}])
515      end
516     
517      set(txh,'String',...
518              sprintf('%s\n%s',...
519                      ['Reading file ' num2str(ii) ...
520                       '/' num2str(length(filenames))],...
521                      ['"',pathnames{ii},filenames{ii},'"']))
522      drawnow
523         
524          try
525                DATA{ii}=an2_data_read([pathnames{ii},filenames{ii}],'wbar','off');
526          catch
527                error(['Unknown error occurred while reading ROI-file "%s". ',...
528                  lasterr],...
529                  [pathnames{ii},filenames{ii}])
530          end
531    end
532    delete(calc_h)
533   
534    %Dat.LoadRoiAtStartUp = true;
535   
536    %% Use rotation information
537    if isfield(roifile,'RotateFlip')
538      DataRotation = roifile.RotateFlip.Rotate;
539      DataFlip = roifile.RotateFlip.Flip;
540        else
541          DataRotation = false(1,length(DATA));
542          DataFlip = false(1,length(DATA));
543        end
544       
545        %% Use SliceClim information
546        if isfield(roifile,'SliceClim')
547          DATA{1}.SliceClim = SliceClim;
548        end
549   
550    %% Assign the ROI-structure to the first structure
551    DATA{1}.ROI = roifile.ROI;
552    clear('roifile')
553   
554    % Initialize GUI
555    %l_Initialize([],[]);
556   
557    %% Rotate images if necessary
558    if ( ~all(DataRotation==0) || ~all(DataFlip==0) )
559      for ii=1:length(DATA)
560        if DataRotation(ii)~=0
561          DATA{ii}.FTDATA = rot90(DATA{ii}.FTDATA,DataRotation(ii));
562        end
563     
564        if DataFlip(ii)~=0
565          if DataFlip(ii)==1
566            DATA{ii}.FTDATA = flipud(DATA{ii}.FTDATA);
567          elseif DataFlip(ii)==2
568            DATA{ii}.FTDATA = fliplr(DATA{ii}.FTDATA);
569          end
570        end
571          end
572          DATA{1}.DataRotation = DataRotation;
573          DATA{1}.DataFlip = DataFlip;
574        end
575       
576   
577 
578        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
579        % Unknown File Format
580        %%%%%%%%%%%%%%%%%%%%%%%%%%%%
581  otherwise
582        DATA=[];
583        error('Unknown file format')
584end
585
Note: See TracBrowser for help on using the repository browser.

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