-
Notifications
You must be signed in to change notification settings - Fork 0
/
sirf_recon_resample.py
293 lines (227 loc) · 9.21 KB
/
sirf_recon_resample.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# Copyright University College London Hospital, 2020
# Author: Eric Einspaenner, Institute of Nuclear Medicine
# For internal research only.
#%% import all necessary modules
import os
import shutil
import sys
import glob
import re
import numpy
import matplotlib.pyplot as plt
from art import *
from sirf import SIRF
import sirf.STIR as Pet
import sirf.Reg as Reg
import sirf.Reg as Eng_ref
import sirf.Reg as Eng_flo
#%% functions
# function to display an image
def imshow(image, limits, title=''):
"""Display an image with a colourbar, returning the plot handle.
Arguments:
image -- a 2D array of numbers
limits -- colourscale limits as [min,max]. An empty [] uses the full range
title -- a string for the title of the plot (default "")
"""
plt.title(title)
bitmap = plt.imshow(image)
if len(limits) == 0:
limits = [image.min(), image.max()]
plt.clim(limits[0], limits[1])
plt.colorbar(shrink=.6)
plt.axis('on')
return bitmap
# function for sorting lists, containing strings with numbers (https://stackoverflow.com/a/48413757)
def sorted_alphanumeric(data):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(data, key=alphanum_key, reverse=False)
# generate a list, contains the time intervalls (sum of frames)
def sum_list(lists):
sum_liste = []
add = int(0)
sum_liste.append(add)
for frame in lists[0:]:
add += frame
sum_liste.append(add)
return sum_liste
# Set the STIR verbosity
Pet.set_verbosity(1)
#%% data path and set filenames
# data path to list-mode and normalisation files
data_path_LM = '/home/rich/Documents/ReCo/UKL_data/LM/20190417/'
data_path_MR = '/home/rich/Documents/ReCo/UKL_data/Processed/MedPhys_MoCo_Test_20190417_7/'
# avoid cluttering of files, delete working-folder and start from scratch
working_folder = '/home/rich/Documents/ReCo/working'
if os.path.exists(working_folder):
shutil.rmtree(working_folder)
if not os.path.exists(working_folder):
os.makedirs(working_folder, mode=0o770)
# change the current working directory to the given path
os.chdir(working_folder)
# input files
list_file = data_path_LM + '1.3.12.2.1107.5.2.38.51008.30000019041705474367000000006.l.hdr'
print('LM data: {}'.format(list_file))
norm_file = data_path_LM + '1.3.12.2.1107.5.2.38.51008.30000019041705474367000000008.n.hdr'
print('Norm data: {}'.format(norm_file))
attn_file = data_path_MR + 'stir_mu_map.hv' # .nii possible, requires ITK
print('mu-Map: {}'.format(attn_file))
# output filename prefixes
sino_file = 'sino'
#%% redirect STIR messages to some files
# you can check these if things go wrong
msg_red = Pet.MessageRedirector('info.txt', 'warn.txt')
#%% create template and set lm2sino converter
# template for acq_data
template_acq_data = Pet.AcquisitionData('Siemens_mMR', span=11, max_ring_diff=16, view_mash_factor=2)
template_acq_data.write('template.hs')
#%% create listmode-to-sinograms converter object
lm2sino = Pet.ListmodeToSinograms()
# set input, output and template files
lm2sino.set_input(list_file)
lm2sino.set_output_prefix(sino_file)
lm2sino.set_template('template.hs')
#%% from template sinogram, ensure that mu-map has spacing/offset
# that matches the reconstructed image
attn_image = Pet.ImageData(attn_file)
template_image = template_acq_data.create_uniform_image(1.0)
resampler = Reg.NiftyResample()
resampler.set_reference_image(template_image)
resampler.set_floating_image(attn_image)
resampler.set_padding_value(0)
resampler.set_interpolation_type_to_linear()
attn_image = resampler.forward(attn_image)
attn_image.write(working_folder + '/stir_mu_map_in_recon_space')
#%% create folders for results
path_sino = working_folder + '/sino'
path_rando = working_folder + '/rando'
path_recon = working_folder + '/recon'
if not os.path.exists(path_sino):
os.makedirs(path_sino, mode=0o770)
print('Create Folder: {}'.format(path_sino))
if not os.path.exists(path_rando):
os.makedirs(path_rando, mode=0o770)
print('Create Folder: {}'.format(path_rando))
if not os.path.exists(path_recon):
os.makedirs(path_recon, mode=0o770)
print('Create Folder: {}'.format(path_recon))
#%% define time frames (read frames.txt) and time intervals
# path to folder with frames.txt
frames_path = '/home/rich/tmp/processed/home/rich/Documents/ReCo/UKL_data/MedPhys_MoCo_Test_20190417_7/40004__30x20sec_4moco_PRR_AC_Images/'
with open(frames_path + 'frames.txt', 'r') as f:
time_frames = [int(line.rstrip()) for line in f]
print('Frames: {}'.format(time_frames))
# define time intervals
time_intervals = sum_list(time_frames)
print('Time intervals: {}'.format(time_intervals))
#%% settings for reconstruction
# set acq_model
acq_model = Pet.AcquisitionModelUsingRayTracingMatrix()
acq_model.set_num_tangential_LORs(5)
# set recon, OSEM
recon = Pet.OSMAPOSLReconstructor()
num_subsets = 7
num_subiterations = 4
recon.set_num_subsets(num_subsets)
recon.set_num_subiterations(num_subiterations)
# definitions for attenuation
attn_acq_model = Pet.AcquisitionModelUsingRayTracingMatrix()
asm_attn = Pet.AcquisitionSensitivityModel(attn_image, attn_acq_model)
# definitions for detector sensitivity modelling
asm_norm = Pet.AcquisitionSensitivityModel(norm_file)
acq_model.set_acquisition_sensitivity(asm_norm)
#%% for-loop, reconstruction of time intervals
tprint('Start Recon')
for i in range(len(time_intervals)-1):
print('Begin reconstruction: Frame {}'.format(i))
# listmode-to-sinogram
lm2sino.set_time_interval(time_intervals[i], time_intervals[i+1])
lm2sino.set_up()
lm2sino.process()
acq_data = lm2sino.get_output()
acq_data.write(working_folder + '/sino/sino'+str(i))
# randoms estimate
randoms = lm2sino.estimate_randoms()
randoms.write(working_folder + '/rando/rando'+str(i))
# reconstruct the data (includes all)
obj_fun = Pet.make_Poisson_loglikelihood(acq_data)
asm_attn.set_up(acq_data)
attn_factors = Pet.AcquisitionData(acq_data)
attn_factors.fill(1.0)
asm_attn.unnormalise(attn_factors)
asm_attn = Pet.AcquisitionSensitivityModel(attn_factors)
asm = Pet.AcquisitionSensitivityModel(asm_norm, asm_attn)
acq_model.set_acquisition_sensitivity(asm)
acq_model.set_background_term(randoms)
obj_fun.set_acquisition_model(acq_model)
recon.set_objective_function(obj_fun)
initial_image = acq_data.create_uniform_image(1.0)
image = initial_image
recon.set_up(image)
recon.set_current_estimate(image)
recon.process()
# save recon images
recon_image = recon.get_output()
recon_image.write(working_folder + '/recon/recon' + str(i))
# save Image as .nii
recon_image = Reg.NiftiImageData(recon.get_output())
recon_image.write(working_folder + '/floates/recon'+str(i))
print('Reconstruction successful: Frame {}'.format(i))
tprint('Finish Recon')
#%% create folder for motion corrected images
path_moco = working_folder + '/moco/'
if not os.path.exists(path_moco):
os.makedirs(path_moco, mode=0o770)
print('Create Folder: {}'.format(path_moco))
#%% convert a array to a SIRF transformation matrix and then resample the float image
# define reference image and float-path
ref_file = working_folder + '/floates/recon0.nii'
ref = Eng_ref.ImageData(ref_file)
flo_path = working_folder + '/floates/'
# path to folder, contain the MCFLIRT matrices
path_mat_mcflirt = frames_path + "epi_frames.mat/"
tprint('Start Reg')
# for loop, simultaneous matrices and images
for mat, image in zip(sorted(os.listdir(path_mat_mcflirt)), sorted_alphanumeric(os.listdir(flo_path))):
print('TM: {}, Float-Image: {}'.format(mat, image))
# read tm-matrix as numpy array and read load float image
matrix = numpy.loadtxt(path_mat_mcflirt + mat)
flo = Eng_flo.ImageData(flo_path + image)
# create affine transformation from numpy array
tm = Reg.AffineTransformation(matrix)
# motion information from another source and resample an image with this informations
print('Begin resampling: {}'.format(image))
resampler = Reg.NiftyResample()
resampler.set_reference_image(ref)
resampler.set_floating_image(flo)
resampler.add_transformation(tm)
resampler.set_padding_value(0)
resampler.set_interpolation_type_to_linear()
output = resampler.forward(flo)
output.write(working_folder + '/moco/moco_'+str(mat))
print('Resampling successful: {}'.format(image))
tprint('Finish Reg')
#%% define RTA method
# define initial image (first image, first frame)
initial = Reg.NiftiImageData(working_folder + '/moco/moco_MAT_0000.nii')
initial_array = initial.as_array()
# sum over all images (as array)
for image in sorted_alphanumeric(os.listdir(path_moco))[1:]:
print(image)
array = Reg.NiftiImageData(path_moco + image).as_array()
initial_array += array
print('Final array (RTA): {}'.format(initial_array))
# create image
final_image = Reg.NiftiImageData(working_folder + '/moco/moco_MAT_0000.nii')
print(type(final_image))
final_image.fill(initial_array)
print(type(final_image))
final_image.write(working_folder + '/final_image_RTA.nii')
tprint('DONE!')
#%% plot image
# dataset must be an array
slice_num = initial_array.shape[0]//2
# plot figure
plt.figure()
imshow(initial_array[slice_num, :, :, ], [], 'MoCo - RTA')