mat_into_hdr.m 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. %MAT_INTO_HDR The old versions of SPM (any version before SPM5) store
  2. % an affine matrix of the SPM Reoriented image into a matlab file
  3. % (.mat extension). The file name of this SPM matlab file is the
  4. % same as the SPM Reoriented image file (.img/.hdr extension).
  5. %
  6. % This program will convert the ANALYZE 7.5 SPM Reoriented image
  7. % file into NIfTI format, and integrate the affine matrix in the
  8. % SPM matlab file into its header file (.hdr extension).
  9. %
  10. % WARNING: Before you run this program, please save the header
  11. % file (.hdr extension) into another file name or into another
  12. % folder location, because all header files (.hdr extension)
  13. % will be overwritten after they are converted into NIfTI
  14. % format.
  15. %
  16. % Usage: mat_into_hdr(filename);
  17. %
  18. % filename: file name(s) with .hdr or .mat file extension, like:
  19. % '*.hdr', or '*.mat', or a single .hdr or .mat file.
  20. % e.g. mat_into_hdr('T1.hdr')
  21. % mat_into_hdr('*.mat')
  22. %
  23. % - Jimmy Shen (jimmy@rotman-baycrest.on.ca)
  24. %
  25. %-------------------------------------------------------------------------
  26. function mat_into_hdr(files)
  27. pn = fileparts(files);
  28. file_lst = dir(files);
  29. file_lst = {file_lst.name};
  30. file1 = file_lst{1};
  31. [p n e]= fileparts(file1);
  32. for i=1:length(file_lst)
  33. [p n e]= fileparts(file_lst{i});
  34. disp(['working on file ', num2str(i) ,' of ', num2str(length(file_lst)), ': ', n,e]);
  35. process=1;
  36. if isequal(e,'.hdr')
  37. mat=fullfile(pn, [n,'.mat']);
  38. hdr=fullfile(pn, file_lst{i});
  39. if ~exist(mat,'file')
  40. warning(['Cannot find file "',mat , '". File "', n, e, '" will not be processed.']);
  41. process=0;
  42. end
  43. elseif isequal(e,'.mat')
  44. hdr=fullfile(pn, [n,'.hdr']);
  45. mat=fullfile(pn, file_lst{i});
  46. if ~exist(hdr,'file')
  47. warning(['Can not find file "',hdr , '". File "', n, e, '" will not be processed.']);
  48. process=0;
  49. end
  50. else
  51. warning(['Input file must have .mat or .hdr extension. File "', n, e, '" will not be processed.']);
  52. process=0;
  53. end
  54. if process
  55. load(mat);
  56. R=M(1:3,1:3);
  57. T=M(1:3,4);
  58. T=R*ones(3,1)+T;
  59. M(1:3,4)=T;
  60. [h filetype fileprefix machine]=load_nii_hdr(hdr);
  61. h.hist.qform_code=0;
  62. h.hist.sform_code=1;
  63. h.hist.srow_x=M(1,:);
  64. h.hist.srow_y=M(2,:);
  65. h.hist.srow_z=M(3,:);
  66. h.hist.magic='ni1';
  67. fid = fopen(hdr,'w',machine);
  68. save_nii_hdr(h,fid);
  69. fclose(fid);
  70. end
  71. end
  72. return; % mat_into_hdr