/
registration_handler_WIP.py
440 lines (362 loc) · 20 KB
/
registration_handler_WIP.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
"""
Create by Jacques STOUT
VERY WIP
Used to register TRKs
Mostly taken from dipy advice/tutorials, will probably be completely deprecated in future
"""
import numpy as np
from dipy.viz import regtools
from dipy.data import fetch_stanford_hardi, read_stanford_hardi
from dipy.data.fetcher import fetch_syn_data, read_syn_data
from dipy.align.imaffine import (transform_centers_of_mass,
AffineMap,
MutualInformationMetric,
AffineRegistration)
from dipy.align.transforms import (TranslationTransform3D,
RigidTransform3D,
AffineTransform3D)
from dipy.io.image import save_nifti
import nibabel as nib
from file_catcher import get_anat, get_niftis, get_trks
from dipy.io.streamline import load_tractogram, save_tractogram
from dipy.tracking.streamline import deform_streamlines
from dipy.viz import has_fury
from dipy.io.stateful_tractogram import Space, StatefulTractogram
from dipy.align.imwarp import SymmetricDiffeomorphicRegistration
from dipy.align.metrics import CCMetric
import os
from dipy.viz import window, actor
def show_template_bundles(bundles, static, show=True, fname=None):
scene = window.Scene()
template_actor = actor.slicer(static)
scene.add(template_actor)
lines_actor = actor.streamtube(bundles, window.colors.orange,
linewidth=0.3)
scene.add(lines_actor)
if show:
window.show(scene)
if fname is not None:
window.record(scene, n_frames=1, out_path=fname, size=(900, 900))
class registrationparams(object):
def __init__(self, nbins=32, sampling_proportion=None, level_iters=[10000, 1000, 100], sigmas = [3.0, 1.0, 0.0],
factors = [4, 2, 1]):
r"""Initialize an instance of the Mutual Information metric.
This class implements the methods required by Optimizer to drive the
registration process.
Parameters
----------
nbins : int, optional
the number of bins to be used for computing the intensity
histograms. The default is 32.
sampling_proportion : None or float in interval (0, 1], optional
There are two types of sampling: dense and sparse. Dense sampling
uses all voxels for estimating the (joint and marginal) intensity
histograms, while sparse sampling uses a subset of them. If
`sampling_proportion` is None, then dense sampling is
used. If `sampling_proportion` is a floating point value in (0,1]
then sparse sampling is used, where `sampling_proportion`
specifies the proportion of voxels to be used. The default is
None.
Notes
-----
Since we use linear interpolation, images are not, in general,
differentiable at exact voxel coordinates, but they are differentiable
between voxel coordinates. When using sparse sampling, selected voxels
are slightly moved by adding a small random displacement within one
voxel to prevent sampling points from being located exactly at voxel
coordinates. When using dense sampling, this random displacement is
not applied.
"""
self.nbins = nbins
self.sampling_prop = sampling_proportion
self.level_iters = level_iters
self.sigmas = sigmas
self.factors = factors
def register_save(inputpathdir, target_path, subject, outputpath, figspath, params, registration_types, applydirs,
verbose):
anat_path = get_anat(inputpathdir, subject)
#myanat = load_nifti(anat_path)
myanat = nib.load(anat_path)
anat_data = np.squeeze(myanat.get_data()[..., 0])
anat_affine = myanat.affine
anat_hdr = myanat.header
vox_size = myanat.header.get_zooms()[0]
#mynifti = load_nifti("/Volumes/Data/Badea/Lab/19abb14/N57437_nii4D.nii")
#anat_data = np.squeeze(myanat[0])[..., 0]
#anat_affine = myanat[1]
#hdr = myanat.header
mytarget = nib.load(target_path)
target_data = np.squeeze(mytarget.get_data()[..., 0])
target_affine = mytarget.affine
identity = np.eye(4)
affine_map = AffineMap(identity,
target_data.shape, target_affine,
anat_data.shape, anat_affine)
resampled = affine_map.transform(anat_data)
"""
regtools.overlay_slices(target_data, resampled, None, 0,
"target_data", "anat_data", figspath + "resampled_0.png")
regtools.overlay_slices(target_data, resampled, None, 1,
"target_data", "anat_data", figspath + "resampled_1.png")
regtools.overlay_slices(target_data, resampled, None, 2,
"target_data", "anat_data", figspath + "resampled_2.png")
"""
c_of_mass = transform_centers_of_mass(target_data, target_affine,
anat_data, anat_affine)
apply_niftis = []
apply_trks = []
if inputpathdir in applydirs:
applyfiles = [anat_path]
else:
applyfiles = []
for applydir in applydirs:
apply_niftis.extend(get_niftis(applydir, subject))
apply_trks.extend(get_trks(applydir, subject))
if "center_mass" in registration_types:
if apply_trks:
metric = CCMetric(3)
level_iters = [10, 10, 5]
sdr = SymmetricDiffeomorphicRegistration(metric, level_iters)
mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine,
c_of_mass.affine)
for apply_nifti in apply_niftis:
fname = os.path.basename(apply_nifti).split(".")[0]
fpath = outputpath + fname + "_centermass.nii"
applynii = nib.load(apply_nifti)
apply_data = applynii.get_data()
apply_affine = applynii.affine
apply_hdr = myanat.header
if len(np.shape(apply_data)) == 4:
transformed_all = c_of_mass.transform(apply_data,apply4D=True)
transformed = transformed_all[:, :, :, 0]
else:
transformed_all = c_of_mass.transform(apply_data)
transformed = transformed_all
save_nifti(fpath, transformed_all, apply_affine, hdr=apply_hdr)
if figspath is not None:
regtools.overlay_slices(target_data, transformed, None, 0,
"target_data", "Transformed", figspath + fname + "_centermass_1.png")
regtools.overlay_slices(target_data, transformed, None, 1,
"target_data", "Transformed", figspath + fname + "_centermass_2.png")
regtools.overlay_slices(target_data, transformed, None, 2,
"target_data", "Transformed", figspath + fname + "_centermass_3.png")
if verbose:
print("Saved the file at " + fpath)
#mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine,
# c_of_mass.affine)
#warped_moving = mapping.transform(anat_data)
for apply_trk in apply_trks:
fname = os.path.basename(apply_trk).split(".")[0]
fpath = outputpath + fname + "_centermass.trk"
sft = load_tractogram(apply_trk, 'same')
target_isocenter = np.diag(np.array([-vox_size, vox_size, vox_size, 1]))
origin_affine = affine_map.affine.copy()
origin_affine[0][3] = -origin_affine[0][3]
origin_affine[1][3] = -origin_affine[1][3]
origin_affine[2][3] = origin_affine[2][3] / vox_size
origin_affine[1][3] = origin_affine[1][3] / vox_size ** 2
# Apply the deformation and correct for the extents
mni_streamlines = deform_streamlines(
sft.streamlines, deform_field=mapping.get_forward_field(),
stream_to_current_grid=target_isocenter,
current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter,
ref_grid_to_world=np.eye(4))
if has_fury:
show_template_bundles(mni_streamlines, anat_data, show=False,
fname = figspath + fname + '_streamlines_centermass.png')
sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM)
save_tractogram(sft, fpath, bbox_valid_check=False)
if verbose:
print("Saved the file at " + fpath)
metric = MutualInformationMetric(params.nbins, params.sampling_prop)
if "AffineRegistration" in registration_types:
affreg = AffineRegistration(metric=metric,
level_iters=params.level_iters,
sigmas=params.sigmas,
factors=params.factors)
transform = TranslationTransform3D()
params0 = None
starting_affine = c_of_mass.affine
translation = affreg.optimize(target_data, anat_data, transform, params0,
target_affine, anat_affine,
starting_affine=starting_affine)
if apply_trks:
metric = CCMetric(3)
level_iters = [10, 10, 5]
sdr = SymmetricDiffeomorphicRegistration(metric, level_iters)
mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine,
translation.affine)
for apply_nifti in apply_niftis:
fname = os.path.basename(apply_nifti).split(".")[0]
fpath = outputpath + fname + "_affinereg.nii"
applynii = nib.load(apply_nifti)
apply_data = applynii.get_data()
apply_affine = applynii.affine
apply_hdr = myanat.header
if len(np.shape(apply_data)) == 4:
transformed_all = translation.transform(apply_data, apply4D=True)
transformed = transformed_all[:, :, :, 0]
else:
transformed_all = translation.transform(apply_data)
transformed = transformed_all
save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr)
if figspath is not None:
regtools.overlay_slices(target_data, transformed, None, 0,
"target_data", "Transformed", figspath + fname + "_affinereg_1.png")
regtools.overlay_slices(target_data, transformed, None, 1,
"target_data", "Transformed", figspath + fname + "_affinereg_2.png")
regtools.overlay_slices(target_data, transformed, None, 2,
"target_data", "Transformed", figspath + fname + "_affinereg_3.png")
if verbose:
print("Saved the file at " + fpath)
for apply_trk in apply_trks:
fname = os.path.basename(apply_trk).split(".")[0]
fpath = outputpath + fname + "_affinereg.trk"
sft = load_tractogram(apply_trk, 'same')
target_isocenter = np.diag(np.array([-vox_size, vox_size, vox_size, 1]))
origin_affine = affine_map.affine.copy()
origin_affine[0][3] = -origin_affine[0][3]
origin_affine[1][3] = -origin_affine[1][3]
origin_affine[2][3] = origin_affine[2][3] / vox_size
origin_affine[1][3] = origin_affine[1][3] / vox_size ** 2
# Apply the deformation and correct for the extents
mni_streamlines = deform_streamlines(
sft.streamlines, deform_field=mapping.get_forward_field(),
stream_to_current_grid=target_isocenter,
current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter,
ref_grid_to_world=np.eye(4))
if has_fury:
show_template_bundles(mni_streamlines, anat_data, show=False,
fname= figspath + fname + '_streamlines_affinereg.png')
sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM)
save_tractogram(sft, fpath, bbox_valid_check=False)
if verbose:
print("Saved the file at " + fpath)
if "RigidTransform3D" in registration_types:
transform = RigidTransform3D()
params0 = None
if 'translation' not in locals():
affreg = AffineRegistration(metric=metric,
level_iters=params.level_iters,
sigmas=params.sigmas,
factors=params.factors)
translation = affreg.optimize(target_data, anat_data, transform, params0,
target_affine, anat_affine,
starting_affine=c_of_mass.affine)
starting_affine = translation.affine
rigid = affreg.optimize(target_data, anat_data, transform, params0,
target_affine, anat_affine,
starting_affine=starting_affine)
transformed = rigid.transform(anat_data)
if apply_trks:
metric = CCMetric(3)
level_iters = [10, 10, 5]
sdr = SymmetricDiffeomorphicRegistration(metric, level_iters)
mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine,
rigid.affine)
for apply_nifti in apply_niftis:
fname = os.path.basename(apply_nifti).split(".")[0]
fpath = outputpath + fname + "_rigidtransf3d.nii"
applynii = nib.load(apply_nifti)
apply_data = applynii.get_data()
apply_affine = applynii.affine
apply_hdr = myanat.header
if len(np.shape(apply_data)) == 4:
transformed_all = rigid.transform(apply_data, apply4D=True)
transformed = transformed_all[:, :, :, 0]
else:
transformed_all = rigid.transform(apply_data)
transformed = transformed_all
save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr)
if figspath is not None:
regtools.overlay_slices(target_data, transformed, None, 0,
"target_data", "Transformed", figspath + fname + "_rigidtransf3d_1.png")
regtools.overlay_slices(target_data, transformed, None, 1,
"target_data", "Transformed", figspath + fname + "_rigidtransf3d_2.png")
regtools.overlay_slices(target_data, transformed, None, 2,
"target_data", "Transformed", figspath + fname + "_rigidtransf3d_3.png")
if verbose:
print("Saved the file at " + fpath)
for apply_trk in apply_trks:
fname = os.path.basename(apply_trk).split(".")[0]
fpath = outputpath + fname + "_rigidtransf3d.trk"
sft = load_tractogram(apply_trk, 'same')
target_isocenter = np.diag(np.array([-vox_size, vox_size, vox_size, 1]))
origin_affine = affine_map.affine.copy()
origin_affine[0][3] = -origin_affine[0][3]
origin_affine[1][3] = -origin_affine[1][3]
origin_affine[2][3] = origin_affine[2][3] / vox_size
origin_affine[1][3] = origin_affine[1][3] / vox_size ** 2
# Apply the deformation and correct for the extents
mni_streamlines = deform_streamlines(
sft.streamlines, deform_field=mapping.get_forward_field(),
stream_to_current_grid=target_isocenter,
current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter,
ref_grid_to_world=np.eye(4))
if has_fury:
show_template_bundles(mni_streamlines, anat_data, show=False,
fname= figspath + fname + '_rigidtransf3d.png')
sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM)
save_tractogram(sft, fpath, bbox_valid_check=False)
if verbose:
print("Saved the file at " + fpath)
if "AffineTransform3D" in registration_types:
transform = AffineTransform3D()
params0 = None
starting_affine = rigid.affine
affine = affreg.optimize(target_data, anat_data, transform, params0,
target_affine, anat_affine,
starting_affine=starting_affine)
transformed = affine.transform(anat_data)
if apply_trks:
metric = CCMetric(3)
level_iters = [10, 10, 5]
sdr = SymmetricDiffeomorphicRegistration(metric, level_iters)
mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine,
affine.affine)
for apply_nifti in apply_niftis:
fname = os.path.basename(apply_nifti).split(".")[0]
fpath = outputpath + fname + "_affinetransf3d.nii"
applynii = nib.load(apply_nifti)
apply_data = applynii.get_data()
apply_affine = applynii.affine
apply_hdr = myanat.header
if len(np.shape(apply_data)) == 4:
transformed_all = affine.transform(apply_data, apply4D=True)
transformed = transformed_all[:, :, :, 0]
else:
transformed_all = affine.transform(apply_data)
transformed = transformed_all
save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr)
if figspath is not None:
regtools.overlay_slices(target_data, transformed, None, 0,
"target_data", "Transformed", figspath + fname + "_affinetransf3d_1.png")
regtools.overlay_slices(target_data, transformed, None, 1,
"target_data", "Transformed", figspath + fname + "_affinetransf3d_2.png")
regtools.overlay_slices(target_data, transformed, None, 2,
"target_data", "Transformed", figspath + fname + "_affinetransf3d_3.png")
if verbose:
print("Saved the file at " + fpath)
for apply_trk in apply_trks:
fname = os.path.basename(apply_trk).split(".")[0]
fpath = outputpath + fname + "_affinetransf3d.trk"
sft = load_tractogram(apply_trk, 'same')
target_isocenter = np.diag(np.array([-vox_size, vox_size, vox_size, 1]))
origin_affine = affine_map.affine.copy()
origin_affine[0][3] = -origin_affine[0][3]
origin_affine[1][3] = -origin_affine[1][3]
origin_affine[2][3] = origin_affine[2][3] / vox_size
origin_affine[1][3] = origin_affine[1][3] / vox_size ** 2
# Apply the deformation and correct for the extents
mni_streamlines = deform_streamlines(
sft.streamlines, deform_field=mapping.get_forward_field(),
stream_to_current_grid=target_isocenter,
current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter,
ref_grid_to_world=np.eye(4))
if has_fury:
show_template_bundles(mni_streamlines, anat_data, show=False,
fname= figspath + fname + '_streamlines_affinetransf3d.png')
sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM)
save_tractogram(sft, fpath, bbox_valid_check=False)
if verbose:
print("Saved the file at " + fpath)