1 function V = mha_read_volume(info)
2 % Function for reading the volume of a Insight Meta-Image (.mha, .mhd) file
4 % volume = tk_read_volume(file-header)
7 % 1: info = mha_read_header()
8 % V = mha_read_volume(info);
9 % imshow(squeeze(V(:,:,round(end/2))),[]);
11 % 2: V = mha_read_volume('test.mha');
13 if(~isstruct(info)), info=mha_read_header(info); end
16 switch(lower(info.DataFile))
20 info.Filename=fullfile(fileparts(info.Filename),info.DataFile);
24 switch(info.ByteOrder(1))
26 fid=fopen(info.Filename,'rb','ieee-be');
28 fid=fopen(info.Filename,'rb','ieee-le');
31 switch(lower(info.DataFile))
34 fseek(fid,info.HeaderSize,'bof');
39 datasize=prod(info.Dimensions)*info.BitDepth/8; % in bytes
41 switch(info.CompressedData(1))
46 V = int8(fread(fid,datasize,'char'));
48 V = uint8(fread(fid,datasize,'uchar'));
50 V = int16(fread(fid,datasize,'short'));
52 V = uint16(fread(fid,datasize,'ushort'));
54 V = int32(fread(fid,datasize,'int'));
56 V = uint32(fread(fid,datasize,'uint'));
58 V = single(fread(fid,datasize,'float'));
60 V = double(fread(fid,datasize,'double'));
64 case 'char', DataType='int8';
65 case 'uchar', DataType='uint8';
66 case 'short', DataType='int16';
67 case 'ushort', DataType='uint16';
68 case 'int', DataType='int32';
69 case 'uint', DataType='uint32';
70 case 'float', DataType='single';
71 case 'double', DataType='double';
73 Z = fread(fid,inf,'uchar=>uint8');
74 V = zlib_decompress(Z,DataType);
79 V = reshape(V,info.Dimensions);
81 function M = zlib_decompress(Z,DataType)
82 import com.mathworks.mlwidgets.io.InterruptibleStreamCopier
83 a=java.io.ByteArrayInputStream(Z);
84 b=java.util.zip.InflaterInputStream(a);
85 isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
86 c = java.io.ByteArrayOutputStream;
88 M=typecast(c.toByteArray,DataType);