]> Creatis software - CreaPhase.git/blob - utilities_LW/mha_read_volume.m
Useful functions for simulations (created by LW, free to use)
[CreaPhase.git] / utilities_LW / mha_read_volume.m
1 function V = mha_read_volume(info)
2 % Function for reading the volume of a Insight Meta-Image (.mha, .mhd) file
3
4 % volume = tk_read_volume(file-header)
5 %
6 % examples:
7 % 1: info = mha_read_header()
8 %    V = mha_read_volume(info);
9 %    imshow(squeeze(V(:,:,round(end/2))),[]);
10 %
11 % 2: V = mha_read_volume('test.mha');
12
13 if(~isstruct(info)), info=mha_read_header(info); end
14
15
16 switch(lower(info.DataFile))
17     case 'local'
18     otherwise
19     % Seperate file
20     info.Filename=fullfile(fileparts(info.Filename),info.DataFile);
21 end
22         
23 % Open file
24 switch(info.ByteOrder(1))
25     case ('true')
26         fid=fopen(info.Filename,'rb','ieee-be');
27     otherwise
28         fid=fopen(info.Filename,'rb','ieee-le');
29 end
30
31 switch(lower(info.DataFile))
32     case 'local'
33         % Skip header
34         fseek(fid,info.HeaderSize,'bof');
35     otherwise
36         fseek(fid,0,'bof');
37 end
38
39 datasize=prod(info.Dimensions)*info.BitDepth/8; % in bytes
40
41 switch(info.CompressedData(1))
42     case 'f'
43         % Read the Data
44         switch(info.DataType)
45             case 'char'
46                  V = int8(fread(fid,datasize,'char')); 
47             case 'uchar'
48                 V = uint8(fread(fid,datasize,'uchar')); 
49             case 'short'
50                 V = int16(fread(fid,datasize,'short')); 
51             case 'ushort'
52                 V = uint16(fread(fid,datasize,'ushort')); 
53             case 'int'
54                  V = int32(fread(fid,datasize,'int')); 
55             case 'uint'
56                  V = uint32(fread(fid,datasize,'uint')); 
57             case 'float'
58                  V = single(fread(fid,datasize,'float'));   
59             case 'double'
60                 V = double(fread(fid,datasize,'double'));
61         end
62     case 't'
63         switch(info.DataType)
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';
72         end
73         Z  = fread(fid,inf,'uchar=>uint8');
74         V = zlib_decompress(Z,DataType);
75
76 end
77
78 fclose(fid);
79 V = reshape(V,info.Dimensions);
80
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;
87 isc.copyStream(b,c);
88 M=typecast(c.toByteArray,DataType);