nrrdWriter.m 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. % ========================================================================
  2. %
  3. % nrrdwriter_dan
  4. %
  5. % filename - 'myimage.ext' - 'veins.nrrd'
  6. % matrix - data - Matlab matrix
  7. % pixelspacing - boxel size
  8. % origin - point from the image is generated
  9. % encoding - raw, ascii, gzip
  10. %
  11. % ========================================================================
  12. function ok = nrrdWriter(filename, matrix, pixelspacing, origin, encoding)
  13. % This line gets the path, name and extension of our file:
  14. % pathf = /home/mario/.../myfile.myext
  15. % fname = myfile
  16. % ext = .myext
  17. [pathf, fname, ext] = fileparts(filename);
  18. format=ext(2:end); % We remove the . from .ext
  19. % so we extract the output format from the argument filename, instead of
  20. % put two different arguments
  21. matrix = permute(matrix, [2 1 3]); % so we undo permute of index in nrrdreader
  22. dims=(size(matrix)); % matrix dimensions (size NxMxP)
  23. ndims=length(dims); % number of dimensions (dim n)
  24. % =====================================================================
  25. % Conditions to make sure our file is goint to be created succesfully.
  26. %
  27. % First the code puts the argument 'encoding' in lowercase
  28. encoding = lower(encoding);
  29. encodingCond = isequal(encoding, 'ascii') || isequal(encoding, 'raw') || isequal(encoding, 'gzip');
  30. assert(encodingCond, 'Unsupported encoding')
  31. % The same with output format
  32. format = lower(format);
  33. formatCond = isequal(format,'nhdr') || isequal(format,'nrrd');
  34. assert(formatCond, 'Unexpected format');
  35. % ======================================================================
  36. % Now, if our conditions are satisfied:
  37. if (encodingCond && formatCond)
  38. % Header
  39. % Open, filename (which specifies output format) and write binary
  40. fid = fopen(filename, 'wb');
  41. fprintf(fid,'NRRD0004\n'); % NRRD type 4
  42. % Type of variable we're storing in our file
  43. mtype=class(matrix);
  44. outtype=setDatatype(mtype);
  45. fprintf(fid,['type: ', outtype, '\n']);
  46. %
  47. fprintf(fid,['dimension: ', num2str(ndims), '\n']);
  48. if isequal(ndims, 2)
  49. fprintf(fid,'space: left-posterior\n');
  50. elseif isequal (ndims, 3)
  51. fprintf(fid,'space: left-posterior-superior\n');
  52. end
  53. fprintf(fid,['sizes: ', num2str(dims), '\n']);
  54. if isequal(ndims, 2)
  55. fprintf(fid,['space directions: (', num2str(pixelspacing(1)), ...
  56. ',0) (0,', num2str(pixelspacing(2)), ')\n']);
  57. fprintf(fid,'kinds: domain domain\n');
  58. elseif isequal (ndims, 3)
  59. fprintf(fid,['space directions: (', num2str(pixelspacing(1)), ...
  60. ',0,0) (0,', num2str(pixelspacing(2)), ',0) (0,0,', ...
  61. num2str(pixelspacing(3)), ')\n']);
  62. fprintf(fid,'kinds: domain domain domain\n');
  63. end
  64. fprintf(fid,['encoding: ', encoding, '\n']);
  65. [~,~,endian] = computer();
  66. if (isequal(endian, 'B'))
  67. fprintf(fid,'endian: big\n');
  68. else
  69. fprintf(fid,'endian: little\n');
  70. end
  71. if isequal(ndims, 2)
  72. fprintf(fid,['space origin: (', num2str(origin(1)),',', num2str(origin(2)),')\n']);
  73. elseif isequal (ndims, 3)
  74. fprintf(fid,['space origin: (', num2str(origin(1)), ...
  75. ',',num2str(origin(2)),',', num2str(origin(3)),')\n']);
  76. end
  77. if (isequal(format, 'nhdr')) % Si hay que separar
  78. % Escribir el nombre del fichero con los datos
  79. fprintf(fid, ['data file: ', [fname, '.', encoding], '\n']);
  80. fclose(fid);
  81. if isequal(length(pathf),0)
  82. fid = fopen([fname, '.', encoding], 'wb');
  83. else
  84. fid = fopen([pathf, filesep, fname, '.', encoding], 'wb');
  85. end
  86. else
  87. fprintf(fid,'\n');
  88. end
  89. ok = writeData(fid, matrix, outtype, encoding);
  90. fclose(fid);
  91. end
  92. % ========================================================================
  93. % Determine the datatype --> From mtype (matlab) to outtype (NRRD) -->
  94. % ========================================================================
  95. function datatype = setDatatype(metaType)
  96. % Determine the datatype
  97. switch (metaType)
  98. case {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64',...
  99. 'uint64', 'double'}
  100. datatype = metaType;
  101. case {'single'}
  102. datatype = 'float';
  103. otherwise
  104. assert(false, 'Unknown datatype')
  105. end
  106. % HACER!!!!!!!!!!!!!!!!!!!!!!!!!
  107. % ========================================================================
  108. % writeData -->
  109. % fidIn is the open file we're overwriting
  110. % matrix - data that have to be written
  111. % datatype - type of data: int8, string, double...
  112. % encoding - raw, gzip, ascii
  113. % ========================================================================
  114. function ok = writeData(fidIn, matrix, datatype, encoding)
  115. switch (encoding)
  116. case {'raw'}
  117. ok = fwrite(fidIn, matrix(:), datatype);
  118. case {'gzip'}
  119. % Store in a raw file before compressing
  120. tmpBase = tempname(pwd);
  121. tmpFile = [tmpBase '.gz'];
  122. fidTmpRaw = fopen(tmpBase, 'wb');
  123. assert(fidTmpRaw > 3, 'Could not open temporary file for GZIP compression');
  124. fwrite(fidTmpRaw, matrix(:), datatype);
  125. fclose(fidTmpRaw);
  126. % Now we gzip our raw file
  127. gzip(tmpBase);
  128. % Finally, we put this info into our nrrd file (fidIn)
  129. fidTmpRaw = fopen(tmpFile, 'rb');
  130. tmp = fread(fidTmpRaw, inf, [datatype '=>' datatype]);
  131. cleaner = onCleanup(@() fclose(fidTmpRaw));
  132. ok = fwrite (fidIn, tmp, datatype);
  133. delete (tmpBase);
  134. delete (tmpFile);
  135. case {'ascii'}
  136. ok = fprintf(fidIn,'%u ',matrix(:));
  137. %ok = fprintf(fidIn,matrix(:), class(matrix));
  138. otherwise
  139. assert(false, 'Unsupported encoding')
  140. end