/
tracking.py
476 lines (283 loc) · 9.97 KB
/
tracking.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# coding: utf-8
# # Ferret DWI tractography
# In[1]:
get_ipython().magic(u'pylab')
# ## Imports & Plotting function
# In[2]:
from __future__ import division, print_function, absolute_import
import numpy as np
import nibabel as nib
from dipy.reconst.peaks import peaks_from_model, PeaksAndMetrics
from dipy.core.sphere import Sphere
from dipy.data import get_sphere
from dipy.io.gradients import read_bvals_bvecs
from dipy.core.gradients import gradient_table
from dipy.tracking import utils
from common import load_nifti, save_trk, save_peaks, load_peaks, save_trk_old_style
from dipy.viz import actor, window, fvtk
#from ipdb import set_trace
def show_results(streamlines, vol, affine, world_coords=True, opacity=0.6):
from dipy.viz import actor, window, widget
shape = data.shape
if not world_coords:
from dipy.tracking.streamline import transform_streamlines
streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))
ren = window.Renderer()
if streamlines is not None:
stream_actor = actor.line(streamlines)
if not world_coords:
image_actor = actor.slicer(vol, affine=np.eye(4))
else:
image_actor = actor.slicer(vol, affine)
slicer_opacity = opacity #.6
image_actor.opacity(slicer_opacity)
if streamlines is not None:
ren.add(stream_actor)
ren.add(image_actor)
show_m = window.ShowManager(ren, size=(1200, 900))
show_m.initialize()
def change_slice(obj, event):
z = int(np.round(obj.get_value()))
image_actor.display_extent(0, shape[0] - 1,
0, shape[1] - 1, z, z)
slider = widget.slider(show_m.iren, show_m.ren,
callback=change_slice,
min_value=0,
max_value=shape[2] - 1,
value=shape[2] / 2,
label="Move slice",
right_normalized_pos=(.98, 0.6),
size=(120, 0), label_format="%0.lf",
color=(1., 1., 1.),
selected_color=(0.86, 0.33, 1.))
global size
size = ren.GetSize()
def win_callback(obj, event):
global size
if size != obj.GetSize():
slider.place(ren)
size = obj.GetSize()
show_m.initialize()
show_m.add_window_callback(win_callback)
show_m.render()
show_m.start()
# ren.zoom(1.5)
# ren.reset_clipping_range()
# window.record(ren, out_path='bundles_and_a_slice.png', size=(1200, 900),
# reset_camera=False)
del show_m
# ### Simple viewers
# In[3]:
def simple_viewer(streamlines, vol, affine):
renderer = window.Renderer()
renderer.add(actor.line(streamlines))
renderer.add(actor.slicer(vol, affine))
window.show(renderer)
# In[4]:
def show_gradients(gtab):
renderer = window.Renderer()
renderer.add(fvtk.point(gtab.gradients, (1,0,0), point_radius=100))
renderer.add(fvtk.point(-gtab.gradients, (1,0,0), point_radius=100))
window.show(renderer)
# ## Tracking set of functions
# The following set of code allows to do the tracktography of Diffusion Weighted Images.
#
# The inputs necessary are:
# * a nifti file of the raw data
# * its associated bvals and bvecs
# * (optional) a mask in nifti
#
# Output:
# * FA, evecs & rgb nifti files
# * .trk file containing the streamlines
# * (annexes) image (png) of the tensor using elipsoids
#
# Parameters:
# * own mask or masking based on the DWI data (median_otsu)
# * type of model used. Here TensorModel (DTI). Can also be ConstrainedSphericalDeconvModel (CSD) or others
# * type of fiting of the model. Here (by default) Weighted Least Square (WLS). Can be Ordinary Least Square (OLS) or others
# * seed density. To increase the number of streamlines
# * threshold of the streamline length filter
# ### Input file paths and loading
# In[31]:
dname = '/Volumes/Samsung_T1/dti/Dipy/P32_F16/'
fdwi = dname + '2dseq.src.gz.nii.gz' #nii from 2dseq in dsi_studio
data, affine = load_nifti(fdwi)
fbval = dname + 'bvals' #from dsi_studio
fbvec = dname + 'bvecs'
bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
gtab = gradient_table(bvals, bvecs, b0_threshold=50)
fmask = None #dname + 'mask_extern.nii' #None if wish to get an automated mask from dwi data
# In[65]:
#checks for gtab
#show_gradients(gtab)
np.sum(gtab.b0s_mask)
print(gtab.info)
plot(np.sort(gtab.bvals))
# ### Hand-made mask or autogenerated mask from the DWI data
# In[32]:
if fmask is None:
from dipy.segment.mask import median_otsu
b0_mask, mask = median_otsu(data) # TODO: check parameters to improve the mask
else:
mask, mask_affine = load_nifti(fmask)
mask = np.squeeze(mask) #fix mask dimensions
# ### DTI Model computation and fitting (further for CSD--not tested)
# In[33]:
# compute DTI model
from dipy.reconst.dti import TensorModel
tenmodel = TensorModel(gtab)#, fit_method='OLS') #, min_signal=5000)
# In[34]:
# fit the dti model
tenfit = tenmodel.fit(data, mask=mask)
# ### DWI indicators computation and saving in nifti files (FA, first eigen vector, rgb tensor)
# In[35]:
# save fa
ffa = dname + 'tensor_fa.nii.gz'
fa_img = nib.Nifti1Image(tenfit.fa.astype(np.float32), affine)
nib.save(fa_img, ffa)
# In[10]:
# save first eigen vector
evecs_img = nib.Nifti1Image(tenfit.evecs.astype(np.float32), affine)
nib.save(evecs_img, dname+'tensor_evecs.nii.gz')
# In[32]:
# compute and save rgb
from dipy.reconst.dti import color_fa
RGB = color_fa(tenfit.fa, tenfit.evecs)
nib.save(nib.Nifti1Image(np.array(255 * RGB, 'uint8'), affine), dname+'tensor_rgb.nii.gz')
# In[ ]:
# In[36]:
sh_order = 8 #TODO: check what that does
if data.shape[-1] < 15:
raise ValueError('You need at least 15 unique DWI volumes to '
'compute fiber ODFs. You currently have: {0}'
' DWI volumes.'.format(data.shape[-1]))
elif data.shape[-1] < 30:
sh_order = 6
# In[37]:
# compute the response equation ?
from dipy.reconst.csdeconv import auto_response
response, ratio = auto_response(gtab, data)
response = list(response)
# In[35]:
# for CSD
#from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
#model = ConstrainedSphericalDeconvModel(gtab, response,
#sh_order=sh_order)
# In[ ]:
# In[38]:
peaks_sphere = get_sphere('symmetric362')
#TODO: check what that does
peaks_csd = peaks_from_model(model=tenmodel,
data=data,
sphere=peaks_sphere,
relative_peak_threshold=.5, #.5
min_separation_angle=25,
mask=mask,
return_sh=True,
sh_order=sh_order,
normalize_peaks=True,
parallel=False)
# In[39]:
peaks_csd.affine = affine
fpeaks = dname + 'peaks.npz'
save_peaks(fpeaks, peaks_csd)
# In[40]:
from dipy.io.trackvis import save_trk
from dipy.tracking import utils
from dipy.tracking.local import (ThresholdTissueClassifier,
LocalTracking)
stopping_thr = 0.25 #0.25
pam = load_peaks(fpeaks)
#ffa = dname + 'tensor_fa_nomask.nii.gz'
fa, fa_affine = load_nifti(ffa)
classifier = ThresholdTissueClassifier(fa,
stopping_thr)
# In[41]:
# seeds
seed_density = 1
seed_mask = fa > 0.4 #0.4 #TODO: check this parameter
seeds = utils.seeds_from_mask(
seed_mask,
density=seed_density,
affine=affine)
# In[ ]:
# In[42]:
#TODO: check what that does
#if use_sh:
# detmax_dg = \
# DeterministicMaximumDirectionGetter.from_shcoeff(
# pam.shm_coeff,
# max_angle=30.,
# sphere=pam.sphere)
#
# streamlines = \
# LocalTracking(detmax_dg, classifier, seeds, affine,
# step_size=.5)
#
#else:
# tractography, if affine then in world coordinates
streamlines = LocalTracking(pam, classifier,
seeds, affine=affine, step_size=.5)
# Compute streamlines and store as a list.
streamlines = list(streamlines)
#ftractogram = dname + 'tractogram.trk'
#save .trk
#save_trk_old_style(ftractogram, streamlines, affine, fa.shape)
#render
show_results(streamlines, fa, fa_affine)
# In[18]:
# threshold on streamline length
from dipy.tracking.utils import length
lengths = list(length(streamlines))
new_streamlines = [ s for s, l in zip(streamlines, lengths) if l > 2. ] #3.5
# In[19]:
# info length streamlines
print(len(streamlines))
print(len(new_streamlines))
print(max(length(streamlines)))
print(min(length(streamlines)))
print(max(length(new_streamlines)))
print(min(length(new_streamlines)))
# In[20]:
# show new tracto
new_streamlines = list(new_streamlines)
new_lengths = list(length(new_streamlines))
fnew_tractogram = dname + 'filteredtractogram.trk'
save_trk_old_style(fnew_tractogram, new_streamlines, affine, fa.shape)
show_results(new_streamlines, fa, fa_affine, opacity=0.6)
# In[161]:
# In[43]:
import matplotlib.pyplot as plt
fig_hist, ax = plt.subplots(1)
ax.hist(lengths, color='burlywood')
ax.set_xlabel('Length')
ax.set_ylabel('Count')
plt.show()
plt.legend()
#plt.savefig('length_histogram.png')
# In[ ]:
# ## Annexes
# In[ ]:
# In[30]:
print('Computing tensor ellipsoids in a part of the splenium of the CC')
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')
from dipy.viz import fvtk
ren = fvtk.ren()
evals = tenfit.evals[13:43, 44:74, 28:29]
evecs = tenfit.evecs[13:43, 44:74, 28:29]
# In[31]:
cfa = RGB[13:43, 44:74, 28:29]
cfa /= cfa.max()
fvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere))
print('Saving illustration as tensor_ellipsoids.png')
fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600))
# In[ ]:
# In[27]:
# first endpoint of the first streamline
streamlines[0][0]
# In[28]:
# other endpoint of the first streamline
streamlines[0][-1]
# In[ ]: