0001 function matRad_writeMHA(filepath,cube,metadata)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036 dimensions = size(cube);
0037 if numel(dimensions) ~= 3
0038 error('Sorry! matRad only supports 3-dimensional MHA output');
0039 end
0040
0041 fid = fopen(filepath, 'wb');
0042 if fid <= 0
0043 error('Could not open MHA destination file!');
0044 end
0045 cleaner = onCleanup(@() fclose(fid));
0046
0047
0048 if isfield(metadata,'axisPermutation')
0049 cube = permute(cube,metadata.axisPermutation);
0050 end
0051
0052 transformMatrix = diag(ones(1,numel(dimensions)));
0053 tmString = sprintf(' %d',transformMatrix(:));
0054
0055
0056 [~,~,endian] = computer;
0057 switch endian
0058 case 'L'
0059 byteOrderMSB = 'True';
0060 case 'B'
0061 byteOrderMSB = 'False';
0062 otherwise
0063 error('Unknown endian!');
0064 end
0065
0066 fprintf(fid, 'ObjectType = Image\n');
0067 fprintf(fid, 'NDims = %d\n',numel(dimensions));
0068 fprintf(fid, 'BinaryData = True\n');
0069 fprintf(fid, 'BinaryDataByteOrderMSB = %s\n',byteOrderMSB);
0070 fprintf(fid, 'ElementByteOrderMSB = %s\n',byteOrderMSB);
0071 fprintf(fid, 'TransformMatrix =%s\n',tmString);
0072 fprintf(fid, 'Offset = %f %f %f\n',metadata.imageOrigin(1),metadata.imageOrigin(2),metadata.imageOrigin(3));
0073 fprintf(fid, 'AnatomicalOrientation = RAI\n');
0074 fprintf(fid, 'ElementSpacing = %f %f %f\n',metadata.resolution(1),metadata.resolution(2),metadata.resolution(3));
0075 fprintf(fid, 'DimSize = %d %d %d\n',dimensions(1),dimensions(2),dimensions(3));
0076 fprintf(fid, 'ElementType = %s\n',matlabTypeToMHAtype(metadata.datatype));
0077 fprintf(fid, 'ElementDataFile = LOCAL\n');
0078 fwrite(fid,cube,metadata.datatype,'b');
0079 fclose(fid);
0080
0081 end
0082
0083 function newType = matlabTypeToMHAtype(datatype)
0084 switch datatype
0085 case {'single','float'}
0086 newType = 'MET_FLOAT';
0087 case 'double'
0088 newType = 'MET_DOUBLE';
0089 case {'uchar','uint8'}
0090 newType = 'MET_UCHAR';
0091 case {'logical','int8','char'}
0092 newType = 'MET_CHAR';
0093 case 'int16'
0094 newType = 'MET_SHORT';
0095 case 'uint16'
0096 newType = 'MET_USHORT';
0097 case 'int32'
0098 newType = 'MET_INT';
0099 case 'int64'
0100 newType = 'MET_LONG';
0101 case 'uint32'
0102 newType = 'MET_UINT';
0103 case 'uint64'
0104 newType = 'MET_ULONG';
0105 otherwise
0106 error(['Datatype ' datatype ' not supported by MHA exporter!']);
0107 end
0108 end
0109
0110