-
Notifications
You must be signed in to change notification settings - Fork 13
/
mhd_utils_3d.py
138 lines (121 loc) · 4.36 KB
/
mhd_utils_3d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python
#coding=utf-8
#======================================================================
#Program: Diffusion Weighted MRI Reconstruction
#Module: $RCSfile: mhd_utils.py,v $
#Language: Python
#Author: $Author: bjian $
#Date: $Date: 2008/10/27 05:55:55 $
#Version: $Revision: 1.1 $
# Last Edited by PJackson 2013/06/06
#======================================================================
import os
import numpy
import array
from distutils import *
def read_meta_header(filename):
"""Return a dictionary of meta data from meta header file"""
fileIN = open(filename, "r")
line = fileIN.readline()
meta_dict = {}
tag_set1 = ['ObjectType','NDims','DimSize','ElementType','ElementDataFile']
tag_set2 = ['BinaryData','BinaryDataByteOrderMSB','CompressedData','CompressedDataSize']
tag_set3 = ['Offset','CenterOfRotation','AnatomicalOrientation','ElementSpacing','TransformMatrix']
tag_set4 = ['Comment','SeriesDescription','AcquisitionDate','AcquisitionTime','StudyDate','StudyTime']
tag_set = []
tag_set.extend(tag_set1)
tag_set.extend(tag_set2)
tag_set.extend(tag_set3)
tag_set.extend(tag_set4)
tag_flag = [False]*len(tag_set)
while line:
tags = str.split(line,'=')
#print tags[0]
for i in range(len(tag_set)):
tag = tag_set[i]
if (str.strip(tags[0]) == tag) and (not tag_flag[i]):
#print tags[1]
meta_dict[tag] = str.strip(tags[1])
tag_flag[i] = True
line = fileIN.readline()
#print comment
fileIN.close()
return meta_dict
def load_raw_data_with_mhd(filename):
meta_dict = read_meta_header(filename)
dim = int(meta_dict['NDims'])
#print dim
#print meta_dict['ElementType']
#assert(meta_dict['ElementType']=='MET_FLOAT')
print meta_dict['DimSize']
print dim
arr = [int(i) for i in meta_dict['DimSize'].split()]
#print arr
volume = reduce(lambda x,y: x*y, arr[0:dim-1], 1)
#print volume
pwd = os.path.split(filename)[0]
if pwd:
data_file = pwd +'/' + meta_dict['ElementDataFile']
else:
data_file = meta_dict['ElementDataFile']
#print data_file
fid = open(data_file,'rb')
binvalues = array.array('f')
binvalues.read(fid, volume*arr[dim-1])
fid.close()
data = numpy.array(binvalues, numpy.float)
data = numpy.reshape(data, (arr[dim-1], volume))
#Begin 3D fix
dimensions = [int(i) for i in meta_dict['DimSize'].split()]
dimensions.reverse()
data = data.reshape(dimensions)
#End 3D fix
return (data, meta_dict)
def write_meta_header(filename, meta_dict):
header = ''
# do not use tags = meta_dict.keys() because the order of tags matters
tags = ['ObjectType','NDims','BinaryData',
'BinaryDataByteOrderMSB','CompressedData','CompressedDataSize',
'TransformMatrix','Offset','CenterOfRotation',
'AnatomicalOrientation',
'ElementSpacing',
'DimSize',
'ElementType',
'ElementDataFile',
'Comment','SeriesDescription','AcquisitionDate','AcquisitionTime','StudyDate','StudyTime']
for tag in tags:
if tag in meta_dict.keys():
header += '%s = %s\n'%(tag,meta_dict[tag])
f = open(filename,'w')
f.write(header)
f.close()
def dump_raw_data(filename, data):
""" Write the data into a raw format file. Big endian is always used. """
#Begin 3D fix
data=data.reshape([data.shape[0],data.shape[1]*data.shape[2]])
#End 3D fix
rawfile = open(filename,'wb')
a = array.array('f')
for o in data:
a.fromlist(list(o))
#if is_little_endian():
# a.byteswap()
a.tofile(rawfile)
rawfile.close()
def write_mhd_file(mhdfile, data, dsize):
assert(mhdfile[-4:]=='.mhd')
meta_dict = {}
meta_dict['ObjectType'] = 'Image'
meta_dict['BinaryData'] = 'True'
meta_dict['BinaryDataByteOrderMSB'] = 'False'
meta_dict['ElementType'] = 'MET_FLOAT'
meta_dict['NDims'] = str(len(dsize))
meta_dict['DimSize'] = ' '.join([str(i) for i in dsize])
meta_dict['ElementDataFile'] = os.path.split(mhdfile)[1].replace('.mhd','.raw')
write_meta_header(mhdfile, meta_dict)
pwd = os.path.split(mhdfile)[0]
if pwd:
data_file = pwd +'/' + meta_dict['ElementDataFile']
else:
data_file = meta_dict['ElementDataFile']
dump_raw_data(data_file, data)