-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsimplefft.py
executable file
·139 lines (105 loc) · 4.83 KB
/
simplefft.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
137
import ismrmrd
import os
import itertools
import logging
import numpy as np
import numpy.fft as fft
import ctypes
import mrdhelper
from datetime import datetime
# Folder for debug output files
debugFolder = "/tmp/share/debug"
def groups(iterable, predicate):
group = []
for item in iterable:
group.append(item)
if predicate(item):
yield group
group = []
def conditionalGroups(iterable, predicateAccept, predicateFinish):
group = []
try:
for item in iterable:
if item is None:
break
if predicateAccept(item):
group.append(item)
if predicateFinish(item):
yield group
group = []
finally:
iterable.send_close()
def process(connection, config, metadata):
logging.info("Config: \n%s", config)
logging.info("Metadata: \n%s", metadata)
# Discard phase correction lines and accumulate lines until "ACQ_LAST_IN_SLICE" is set
for group in conditionalGroups(connection, lambda acq: not acq.is_flag_set(ismrmrd.ACQ_IS_PHASECORR_DATA), lambda acq: acq.is_flag_set(ismrmrd.ACQ_LAST_IN_SLICE)):
image = process_group(group, config, metadata)
logging.debug("Sending image to client:\n%s", image)
connection.send_image(image)
def process_group(group, config, metadata):
if len(group) == 0:
return []
# Create folder, if necessary
if not os.path.exists(debugFolder):
os.makedirs(debugFolder)
logging.debug("Created folder " + debugFolder + " for debug output files")
# Format data into single [cha RO PE] array
data = [acquisition.data for acquisition in group]
data = np.stack(data, axis=-1)
logging.debug("Raw data is size %s" % (data.shape,))
np.save(debugFolder + "/" + "raw.npy", data)
# Fourier Transform
data = fft.fftshift( data, axes=(1, 2))
data = fft.ifft2( data, axes=(1, 2))
data = fft.ifftshift(data, axes=(1, 2))
data *= np.prod(data.shape) # FFT scaling for consistency with ICE
# Sum of squares coil combination
data = np.abs(data)
data = np.square(data)
data = np.sum(data, axis=0)
data = np.sqrt(data)
logging.debug("Image data is size %s" % (data.shape,))
np.save(debugFolder + "/" + "img.npy", data)
# Determine max value (12 or 16 bit)
BitsStored = 12
if (mrdhelper.get_userParameterLong_value(metadata, "BitsStored") is not None):
BitsStored = mrdhelper.get_userParameterLong_value(metadata, "BitsStored")
maxVal = 2**BitsStored - 1
# Normalize and convert to int16
data *= maxVal/data.max()
data = np.around(data)
data = data.astype(np.int16)
# Remove readout oversampling
offset = int((data.shape[0] - metadata.encoding[0].reconSpace.matrixSize.x)/2)
data = data[offset:offset+metadata.encoding[0].reconSpace.matrixSize.x,:]
# Remove phase oversampling
offset = int((data.shape[1] - metadata.encoding[0].reconSpace.matrixSize.y)/2)
data = data[:,offset:offset+metadata.encoding[0].reconSpace.matrixSize.y]
logging.debug("Image without oversampling is size %s" % (data.shape,))
np.save(debugFolder + "/" + "imgCrop.npy", data)
# Format as ISMRMRD image data
# data has shape [RO PE], i.e. [x y].
# from_array() should be called with 'transpose=False' to avoid warnings, and when called
# with this option, can take input as: [cha z y x], [z y x], or [y x]
image = ismrmrd.Image.from_array(data.transpose(), acquisition=group[0], transpose=False)
image.image_index = 1
# Set field of view
image.field_of_view = (ctypes.c_float(metadata.encoding[0].reconSpace.fieldOfView_mm.x),
ctypes.c_float(metadata.encoding[0].reconSpace.fieldOfView_mm.y),
ctypes.c_float(metadata.encoding[0].reconSpace.fieldOfView_mm.z))
# Set ISMRMRD Meta Attributes
meta = ismrmrd.Meta({'DataRole': 'Image',
'ImageProcessingHistory': ['FIRE', 'PYTHON'],
'WindowCenter': str((maxVal+1)/2),
'WindowWidth': str((maxVal+1))})
# Add image orientation directions to MetaAttributes if not already present
if meta.get('ImageRowDir') is None:
meta['ImageRowDir'] = ["{:.18f}".format(image.getHead().read_dir[0]), "{:.18f}".format(image.getHead().read_dir[1]), "{:.18f}".format(image.getHead().read_dir[2])]
if meta.get('ImageColumnDir') is None:
meta['ImageColumnDir'] = ["{:.18f}".format(image.getHead().phase_dir[0]), "{:.18f}".format(image.getHead().phase_dir[1]), "{:.18f}".format(image.getHead().phase_dir[2])]
xml = meta.serialize()
logging.debug("Image MetaAttributes: %s", xml)
logging.debug("Image data has %d elements", image.data.size)
image.attribute_string = xml
return image