コード例 #1
0
ファイル: tracking_method.py プロジェクト: geyunxiang/mmdps
def probal(Threshold=.2,
           data_list=None,
           seed='.',
           one_node=False,
           two_node=False):
    time0 = time.time()
    print("begin loading data, time:", time.time() - time0)

    data = data_list['DWI']
    affine = data_list['affine']
    img = data_list['img']
    labels = data_list['labels']
    gtab = data_list['gtab']
    head_mask = data_list['head_mask']

    if type(seed) != str:
        seed_mask = seed
    else:
        seed_mask = (labels == 2) * (head_mask == 1)

    white_matter = (labels == 2) * (head_mask == 1)
    seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

    print("begin reconstruction, time:", time.time() - time0)
    response, ratio = auto_response_ssst(gtab, data, roi_radii=10, fa_thr=0.7)
    csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
    csd_fit = csd_model.fit(data, mask=white_matter)

    csa_model = CsaOdfModel(gtab, sh_order=6)
    gfa = csa_model.fit(data, mask=white_matter).gfa
    stopping_criterion = ThresholdStoppingCriterion(gfa, Threshold)

    print("begin tracking, time:", time.time() - time0)
    fod = csd_fit.odf(small_sphere)
    pmf = fod.clip(min=0)
    prob_dg = ProbabilisticDirectionGetter.from_pmf(pmf,
                                                    max_angle=30.,
                                                    sphere=small_sphere)
    streamline_generator = LocalTracking(prob_dg,
                                         stopping_criterion,
                                         seeds,
                                         affine,
                                         step_size=.5)
    streamlines = Streamlines(streamline_generator)

    sft = StatefulTractogram(streamlines, img, Space.RASMM)

    if one_node or two_node:
        sft.to_vox()
        streamlines = reduct_seed_ROI(sft.streamlines, seed_mask, one_node,
                                      two_node)
        sft = StatefulTractogram(streamlines, img, Space.VOX)
        sft._vox_to_rasmm()

    print("begin saving, time:", time.time() - time0)

    output = 'tractogram_probabilistic.trk'
    save_trk(sft, output)

    print("finished, time:", time.time() - time0)
コード例 #2
0
def csa_mod_est(gtab, data, wm_in_dwi):
    from dipy.reconst.shm import CsaOdfModel
    print('Fitting CSA model...')
    wm_in_dwi_mask = nib.load(wm_in_dwi).get_fdata().astype('bool')
    model = CsaOdfModel(gtab, sh_order=6)
    mod = model.fit(data, wm_in_dwi_mask)
    return mod.shm_coeff
コード例 #3
0
def csa_mod_est(gtab, data, B0_mask):
    '''
    Estimate a Constant Solid Angle (CSA) model from dwi data.

    Parameters
    ----------
    gtab : Obj
        DiPy object storing diffusion gradient information
    data : array
        4D numpy array of diffusion image data.
    B0_mask : str
        File path to B0 brain mask.

    Returns
    -------
    csa_mod : obj
        Spherical harmonics coefficients of the CSA-estimated reconstruction model.
    '''
    from dipy.reconst.shm import CsaOdfModel
    print('Fitting CSA model...')
    model = CsaOdfModel(gtab, sh_order=6)
    csa_mod = model.fit(data,
                        nib.load(B0_mask).get_fdata().astype('bool')).shm_coeff
    del model
    return csa_mod
コード例 #4
0
ファイル: estimation.py プロジェクト: neurolibre/PyNets
def csa_mod_est(gtab, data, B0_mask, sh_order=8):
    '''
    Estimate a Constant Solid Angle (CSA) model from dwi data.

    Parameters
    ----------
    gtab : Obj
        DiPy object storing diffusion gradient information
    data : array
        4D numpy array of diffusion image data.
    B0_mask : str
        File path to B0 brain mask.
    sh_order : int
        The order of the SH model. Default is 8.

    Returns
    -------
    csa_mod : ndarray
        Coefficients of the csa reconstruction.
    model : obj
        Fitted csa model.

    References
    ----------
    .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging
      with Solid Angle Consideration.

    '''
    from dipy.reconst.shm import CsaOdfModel
    print('Fitting CSA model...')
    model = CsaOdfModel(gtab, sh_order=sh_order)
    B0_mask_data = np.asarray(nib.load(B0_mask).dataobj).astype('bool')
    csa_mod = model.fit(data, B0_mask_data).shm_coeff
    del B0_mask_data
    return csa_mod, model
コード例 #5
0
def reconst_f(output_dir, b_sph=None):
    params_file = os.path.join(output_dir, 'params.pickle')
    data_file = os.path.join(output_dir, 'data.pickle')

    baseparams = pickle.load(open(params_file, 'rb'))
    data = pickle.load(open(data_file, 'rb'))
    gtab = data.gtab
    S_data = data.raw[data.slice]

    S_data_list = [S_data]
    if hasattr(data, 'ground_truth'):
        S_data_list.append(data.ground_truth[data.slice])

    l_labels = np.sum(gtab.bvals > 0)
    imagedims = S_data.shape[:-1]
    b_vecs = gtab.bvecs[gtab.bvals > 0,...]
    if b_sph is None:
        b_sph = load_sphere(vecs=b_vecs.T)
    qball_sphere = dipy.core.sphere.Sphere(xyz=b_vecs)
    basemodel = CsaOdfModel(gtab, **baseparams['base'])
    fs = []
    for S in S_data_list:
        f = basemodel.fit(S).odf(qball_sphere)
        f = np.clip(f, 0, np.max(f, -1)[..., None])
        f = np.array(f.reshape(-1, l_labels).T, order='C')
        normalize_odf(f, b_sph.b)
        fs.append(f)
    return tuple(fs)
コード例 #6
0
ファイル: tracking_method.py プロジェクト: geyunxiang/mmdps
def PFT_tracking(name=None, data_path=None, output_path='.', Threshold=.20):

    time0 = time.time()
    print("begin loading data, time:", time.time() - time0)
    data, affine, img, labels, gtab, head_mask = get_data(name, data_path)

    seed_mask = (labels == 2) * (head_mask == 1)
    white_matter = (labels == 2) * (head_mask == 1)
    seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

    print('begin reconstruction, time:', time.time() - time0)

    response, ratio = auto_response_ssst(gtab, data, roi_radii=10, fa_thr=0.7)
    csd_model = ConstrainedSphericalDeconvModel(gtab, response)
    csd_fit = csd_model.fit(data, mask=white_matter)

    csa_model = CsaOdfModel(gtab, sh_order=6)
    gfa = csa_model.fit(data, mask=white_matter).gfa

    stopping_criterion = ThresholdStoppingCriterion(gfa, Threshold)

    dg = ProbabilisticDirectionGetter.from_shcoeff(csd_fit.shm_coeff,
                                                   max_angle=20.,
                                                   sphere=default_sphere)

    #seed_mask = (labels == 2)
    #seed_mask[pve_wm_data < 0.5] = 0
    seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

    #voxel_size = np.average(voxel_size[1:4])
    step_size = 0.2

    #cmc_criterion = CmcStoppingCriterion.from_pve(pve_wm_data,
    #                                              pve_gm_data,
    #                                             pve_csf_data,
    #                                             step_size=step_size,
    #                                              average_voxel_size=voxel_size)

    # Particle Filtering Tractography
    pft_streamline_generator = ParticleFilteringTracking(
        dg,
        stopping_criterion,
        seeds,
        affine,
        max_cross=1,
        step_size=step_size,
        maxlen=1000,
        pft_back_tracking_dist=2,
        pft_front_tracking_dist=1,
        particle_count=15,
        return_all=False)
    streamlines = Streamlines(pft_streamline_generator)
    sft = StatefulTractogram(streamlines, img, Space.RASMM)
    output = output_path + '/tractogram_pft_' + name + '.trk'
コード例 #7
0
def test_torch_gfa(datas_dwi, gtabs):
    rtol = 1e-04
    atol = 1e-08

    idx = 0
    data_dwi = datas_dwi[idx][100:140, 100:140, 28:29]
    gtab = gtabs[idx]

    csamodel = CsaOdfModel(gtab, 4)
    csamodel = csamodel.fit(data_dwi)
    data_sh = csamodel.shm_coeff
    true_gfa = csamodel.gfa

    torch_gfa = metrics.torch_gfa(torch.FloatTensor(data_sh)).numpy()

    assert np.isclose(true_gfa, torch_gfa, rtol=rtol, atol=atol).all()
コード例 #8
0
ファイル: tracking_method.py プロジェクト: geyunxiang/mmdps
def ClosestPeak(name=None, data_path=None, output_path='.', Threshold=.20):

    time0 = time.time()
    print("begin loading data, time:", time.time() - time0)
    data, affine, img, labels, gtab, head_mask = get_data(name, data_path)

    seed_mask = (labels == 2) * (head_mask == 1)
    white_matter = (labels == 2) * (head_mask == 1)
    seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

    print("begin reconstruction, time:", time.time() - time0)
    response, ratio = auto_response_ssst(gtab, data, roi_radii=10, fa_thr=0.7)
    csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
    #csd_fit = csd_model.fit(data, mask=white_matter)
    #pmf = csd_fit.odf(small_sphere).clip(min=0)
    peak_dg = BootDirectionGetter.from_data(data,
                                            csd_model,
                                            max_angle=30.,
                                            sphere=small_sphere)

    csa_model = CsaOdfModel(gtab, sh_order=6)
    gfa = csa_model.fit(data, mask=white_matter).gfa
    stopping_criterion = ThresholdStoppingCriterion(gfa, Threshold)

    #from dipy.data import small_sphere

    print("begin tracking, time:", time.time() - time0)
    #detmax_dg = DeterministicMaximumDirectionGetter.from_shcoeff(
    #    csd_fit.shm_coeff, max_angle=30., sphere=default_sphere)
    streamline_generator = LocalTracking(peak_dg,
                                         stopping_criterion,
                                         seeds,
                                         affine,
                                         step_size=.5)
    streamlines = Streamlines(streamline_generator)
    sft = StatefulTractogram(streamlines, img, Space.RASMM)

    print("begin saving, time:", time.time() - time0)

    output = output_path + '/tractogram_ClosestPeak_' + name + '.trk'
    save_trk(sft, output)

    print("finished, time:", time.time() - time0)
コード例 #9
0
ファイル: utils.py プロジェクト: JanMigon/Diffusion-mri
def calculate_odf(gtab, data, sh_order=4):
    csamodel = CsaOdfModel(gtab, sh_order)

    data_small = data[30:65, 40:75, 39:40]
    csa_odf = csamodel.fit(data_small).odf(default_sphere)
    csa_odf = np.clip(csa_odf, 0, np.max(csa_odf, -1)[..., None])
    odf_spheres = actor.odf_slicer(csa_odf,
                                   sphere=default_sphere,
                                   scale=0.9,
                                   norm=False,
                                   colormap='plasma')

    ren = window.Scene()
    ren.add(odf_spheres)

    print('Saving illustration as csa_odfs_{}.png'.format(data.shape[-1] - 1))
    window.record(ren,
                  out_path='results/csa_odfs_{}.png'.format(data.shape[-1] -
                                                            1),
                  size=(600, 600))
    return csa_odf
コード例 #10
0
ファイル: estimation.py プロジェクト: dPys/PyNets
def csa_mod_est(gtab, data, B0_mask, sh_order=8):
    """
    Estimate a Constant Solid Angle (CSA) model from dwi data.

    Parameters
    ----------
    gtab : Obj
        DiPy object storing diffusion gradient information
    data : array
        4D numpy array of diffusion image data.
    B0_mask : str
        File path to B0 brain mask.
    sh_order : int
        The order of the SH model. Default is 8.

    Returns
    -------
    csa_mod : ndarray
        Coefficients of the csa reconstruction.
    model : obj
        Fitted csa model.

    References
    ----------
    .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging
      with Solid Angle Consideration.

    """
    from dipy.reconst.shm import CsaOdfModel

    print("Reconstructing using CSA...")
    model = CsaOdfModel(gtab, sh_order=sh_order)
    csa_mod = model.fit(
        data,
        np.nan_to_num(np.asarray(
            nib.load(B0_mask).dataobj)).astype("bool")).shm_coeff
    # Clip any negative values
    csa_mod = np.clip(csa_mod, 0, np.max(csa_mod, -1)[..., None])
    return csa_mod.astype("float32"), model
コード例 #11
0
ファイル: estimation.py プロジェクト: Mozihua/PyNets
def csa_mod_est(gtab, data, wm_in_dwi):
    '''
    Estimate a Constant Solid Angle (CSA) model from dwi data.

    Parameters
    ----------
    gtab : Obj
        DiPy object storing diffusion gradient information
    data : array
        4D numpy array of diffusion image data.
    wm_in_dwi : str
        File path to white-matter tissue segmentation Nifti1Image.

    Returns
    -------
    csa_mod : obj
        Spherical harmonics coefficients of the CSA-estimated reconstruction model.
    '''
    from dipy.reconst.shm import CsaOdfModel
    print('Fitting CSA model...')
    wm_in_dwi_mask = nib.load(wm_in_dwi).get_fdata().astype('bool')
    model = CsaOdfModel(gtab, sh_order=6)
    csa_mod = model.fit(data, wm_in_dwi_mask).shm_coeff
    return csa_mod
コード例 #12
0
ファイル: reconst_csa.py プロジェクト: bevlin510/dipy
ODF. peak_values shows the maxima values of the ODF and peak_indices gives us
their position on the discrete sphere that was used to do the reconstruction of
the ODF. In order to obtain the full ODF return_odf should be True. Before
enabling this option make sure that you have enough memory.

Finally lets try to visualize the orientation distribution functions of a small
rectangular area around the middle of our datasets.
"""

i,j,k,w = np.array(data.shape) / 2
data_small  = data[i-5:i+5, j-5:j+5, k-2:k+2]
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')

from dipy.viz import fvtk
r = fvtk.ren()
fvtk.add(r, fvtk.sphere_funcs(csamodel.fit(data_small).odf(sphere),
							  sphere, colormap='jet'))
print('Saving illustration as csa_odfs.png')
fvtk.record(r, n_frames=1, out_path='csa_odfs.png', size=(600, 600))

"""
.. figure:: csa_odfs.png
   :align: center

   **Constant Solid Angle ODFs**.

.. include:: ../links_names.inc

"""
コード例 #13
0
seed_mask = labels == 2
white_matter = (labels == 1) | (labels == 2)
seeds = utils.seeds_from_mask(seed_mask, density=1, affine=affine)

csd_model = ConstrainedSphericalDeconvModel(gtab, None, sh_order=6)
csd_fit = csd_model.fit(data, mask=white_matter)

"""
We use the GFA of the CSA model to build a tissue classifier.
"""

from dipy.reconst.shm import CsaOdfModel

csa_model = CsaOdfModel(gtab, sh_order=6)
gfa = csa_model.fit(data, mask=white_matter).gfa
classifier = ThresholdTissueClassifier(gfa, .25)

"""
The fiber orientation distribution (FOD) of the CSD model estimates the
distribution of small fiber bundles within each voxel. We can use this
distribution for probabilistic fiber tracking. One way to do this is to
represent the FOD using a discrete sphere. This discrete FOD can be used by the
Probabilistic Direction Getter as a PMF for sampling tracking directions. We
need to clip the FOD to use it as a PMF because the latter cannot have negative
values. (Ideally the FOD should be strictly positive, but because of noise
and/or model failures sometimes it can have negative values).
"""

from dipy.direction import ProbabilisticDirectionGetter
from dipy.data import small_sphere
コード例 #14
0
ファイル: HumanBrain.py プロジェクト: Davidnh8/HumanBrain_v2
def Analyze(img_d_path, img_s_path, gtab):

    # For fiber tracking, 3 things are needed
    # 1. Method for getting directions
    # 2. Method for identifying different tissue types
    # 3. seeds to begin tracking from

    print_info = False
    if print_info:
        print(
            "============================  Diffusion  ============================"
        )
        print(img_d)
        print(
            "============================ Structural ============================="
        )
        print(img_s)
        print("Labels:", np.unique(img_s.get_data()).astype('int'))

    # Load images
    img_d = nib.load(img_d_path)
    img_s = nib.load(img_s_path)

    # Resize the label (img_s)
    # 0. create an empty array the shape of diffusion image, without
    #    the 4th dimension
    # 1. Convert structural voxel coordinates into ref space (affine)
    # 2. Convert diffusion voxel coordinates into ref space (affine)
    # 3 For each diffusion ref coordinate,
    #   find the closest structural ref coordinate
    # 4. find its corresponding label, then input it to the empty array

    print_info_2 = True
    if print_info_2:
        #print(img_d.get_data().shape[])
        print(img_d.affine)
        print(img_s.affine)
        print(img_s._dataobj._shape)
        print(img_d._dataobj._shape)

    img_d_shape_3D = [j for i, j in enumerate(img_d.dataobj._shape) if i < 3]
    img_s_shape_3D = img_s.dataobj._shape

    #raise ValueError(" ")

    img_d_affine = img_d.affine
    img_s_affine = img_s.affine

    img_s_data = img_s.get_data()
    img_d_data = img_d.get_data()

    Vox_coord_s_i = np.arange(img_s_shape_3D[0])
    Vox_coord_s_j = np.arange(img_s_shape_3D[1])
    Vox_coord_s_k = np.arange(img_s_shape_3D[2])
    Ref_coord_s_i = Vox_coord_s_i * img_s_affine[0, 0] + img_s_affine[0, 3]
    Ref_coord_s_j = Vox_coord_s_j * img_s_affine[1, 1] + img_s_affine[1, 3]
    Ref_coord_s_k = Vox_coord_s_k * img_s_affine[2, 2] + img_s_affine[2, 3]
    #print(Ref_coord_s_j)

    reduced_size_label = np.zeros(img_d_shape_3D)

    for i in range(img_d_shape_3D[0]):
        for j in range(img_d_shape_3D[1]):
            for k in range(img_d_shape_3D[2]):
                # convert to reference coordinate
                ref_coord_i = i * img_d_affine[0, 0] + img_d_affine[0, 3]
                ref_coord_j = j * img_d_affine[1, 1] + img_d_affine[1, 3]
                ref_coord_k = k * img_d_affine[2, 2] + img_d_affine[2, 3]

                min_i_ind = bisect.bisect_left(np.sort(Ref_coord_s_i),
                                               ref_coord_i)
                min_j_ind = bisect.bisect_left(Ref_coord_s_j, ref_coord_j)
                min_k_ind = bisect.bisect_left(Ref_coord_s_k, ref_coord_k)
                #print(min_i_ind,min_j_ind,min_k_ind)
                #print(img_s_data[260-1-min_i_ind][311-1-min_j_ind][260-1-min_k_ind])
                #reduced_size_label[i][j][k]=img_s_data[260-1-min_i_ind][311-1-min_j_ind][260-1-min_k_ind]
                reduced_size_label[i][j][k] = img_s_data[260 - 1 - min_i_ind,
                                                         min_j_ind, min_k_ind]
    print("Label image reduction successful")

    # Divide Brainstem
    #msk_Midbrain
    yy, xx, zz = np.meshgrid(np.arange(174), np.arange(145), np.arange(145))

    pon_midbrain_msk = yy > (-115 / 78) * zz + 115
    midbrain_msk = zz > 48

    BS_msk = reduced_size_label == 16
    reduced_size_label_BS_seg = np.copy(reduced_size_label)
    reduced_size_label_BS_seg[BS_msk * pon_midbrain_msk] = 90
    reduced_size_label_BS_seg[BS_msk * midbrain_msk] = 120

    plt.figure(figsize=[11, 8.5])
    msk = reduced_size_label > 200
    temp_reduced_size_label = np.copy(reduced_size_label_BS_seg)
    temp_reduced_size_label[msk] = 0
    plt.imshow(temp_reduced_size_label[72, :, :], origin='lower')

    msk = reduced_size_label == 16
    temp_reduced_size_label = np.copy(reduced_size_label)
    temp_reduced_size_label[~msk] = 0
    plt.figure(figsize=[11, 8.5])
    plt.imshow(temp_reduced_size_label[72, :, :], origin='lower')

    #print("image display complete")
    #input1=raw_input("stopping")
    T1_path = "C:\\Users\\gham\\Desktop\\Human Brain\\Data\\102109\\102109_3T_Diffusion_preproc\\102109\\T1w\\"
    T1_file = "T1w_acpc_dc_restore_1.25.nii.gz"
    T1 = nib.load(T1_path + T1_file)
    T1_data = T1.get_data()
    plt.figure(figsize=[11, 8.5])
    plt.imshow(T1_data[72, :, :], origin='lower')
    plt.show()

    # implement the modified label
    reduced_size_label = reduced_size_label_BS_seg
    #raise ValueError("========== Stop =============")

    #White matter mask
    left_cerebral_wm = reduced_size_label == 2
    right_cerebral_wm = reduced_size_label == 41
    cerebral_wm = left_cerebral_wm + right_cerebral_wm
    left_cerebellum_wm = reduced_size_label == 7
    right_cerebellum_wm = reduced_size_label == 46
    cerebellum_wm = left_cerebellum_wm + right_cerebellum_wm

    CC = np.zeros(reduced_size_label.shape)
    for i in [251, 252, 253, 254, 255]:
        CC += reduced_size_label == i

    left_cortex = np.zeros(reduced_size_label.shape)
    for i in np.arange(1000, 1036):
        left_cortex += reduced_size_label == i
    right_cortex = np.zeros(reduced_size_label.shape)
    for i in np.arange(2000, 2036):
        right_cortex += reduced_size_label == i

    extra = np.zeros(reduced_size_label.shape)
    for i in [
            4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 90, 120, 17, 18, 24, 26, 28,
            30, 31, 43, 44, 46, 47, 49, 50, 51, 52, 53, 54, 58, 60, 62, 63, 77,
            80, 85
    ]:
        extra += reduced_size_label == i
    #for i in np.arange(1001,1035):
    #    extra+=reduced_size_label==i

    wm = cerebral_wm + cerebellum_wm + CC + extra + left_cortex + right_cortex

    #seed_mask1=np.zeros(reduced_size_label.shape)
    #for i in [16]:
    #    seed_mask1+=reduced_size_label==i
    #seed_mask2=np.zeros(reduced_size_label.shape)

    #seed_mask=seed_mask1+seed_mask2

    #seed_mask=(reduced_size_label==16)+(reduced_size_label==2)+(reduced_size_label==41)
    #seeds = utils.seeds_from_mask(seed_mask, density=1, affine=img_d_affine)
    seeds = utils.seeds_from_mask(wm, density=1, affine=img_d_affine)

    # Constrained Spherical Deconvolution
    #reference: https://www.imagilys.com/constrained-spherical-deconvolution-CSD-tractography/
    csd_model = ConstrainedSphericalDeconvModel(gtab, None, sh_order=6)
    csd_fit = csd_model.fit(img_d_data, mask=wm)

    print("CSD model complete")

    # reconstruction
    from dipy.reconst.shm import CsaOdfModel

    csa_model = CsaOdfModel(gtab, sh_order=6)
    gfa = csa_model.fit(img_d_data, mask=wm).gfa
    classifier = ThresholdTissueClassifier(gfa, .25)
    # =============================================================================
    #     import dipy.reconst.dti as dti
    #     from dipy.reconst.dti import fractional_anisotropy
    #     tensor_model = dti.TensorModel(gtab)
    #     tenfit=tensor_model.fit(img_d_data,mask=wm) #COMPUTATIONALL INTENSE
    #     FA=fractional_anisotropy(tenfit.evals)
    #     classifier=ThresholdTissueClassifier(FA,.1) # 0.2 enough?
    # =============================================================================

    print("Classifier complete")

    # Probabilistic direction getter
    from dipy.direction import ProbabilisticDirectionGetter
    from dipy.data import small_sphere
    from dipy.io.streamline import save_trk

    fod = csd_fit.odf(small_sphere)
    pmf = fod.clip(min=0)
    prob_dg = ProbabilisticDirectionGetter.from_pmf(pmf,
                                                    max_angle=75.,
                                                    sphere=small_sphere)
    streamlines_generator = LocalTracking(prob_dg,
                                          classifier,
                                          seeds,
                                          img_d_affine,
                                          step_size=.5)
    save_trk("probabilistic_small_sphere.trk", streamlines_generator,
             img_d_affine, reduced_size_label.shape)

    astreamlines = np.array(list(streamlines_generator))
    endpoints = np.array(
        [st[0::len(st) - 1] for st in astreamlines if len(st) > 1])

    print(endpoints)
    with open('endpoints-shorder=6-maxangle=75-gfa=0.25-BSdiv-v3.pkl',
              'wb') as f:
        pickle.dump(endpoints, f)
    with open("reduced_label-shorder=6-maxangle=75-gfa=0.25-BSdiv-v3.pkl",
              "wb") as g:
        pickle.dump(reduced_size_label, g)
コード例 #15
0
ファイル: reconst_csa.py プロジェクト: tomas-psorn/dipy
enabling this option, make sure that you have enough memory.

Let's visualize the ODFs of a small rectangular area in an axial slice of the
splenium of the corpus callosum (CC).
"""

data_small = maskdata[13:43, 44:74, 28:29]

from dipy.viz import window, actor

# Enables/disables interactive visualization
interactive = False

ren = window.Renderer()

csaodfs = csamodel.fit(data_small).odf(default_sphere)
"""
It is common with CSA ODFs to produce negative values, we can remove those
using ``np.clip``
"""

csaodfs = np.clip(csaodfs, 0, np.max(csaodfs, -1)[..., None])
csa_odfs_actor = actor.odf_slicer(csaodfs,
                                  sphere=default_sphere,
                                  colormap='plasma',
                                  scale=0.4)
csa_odfs_actor.display(z=0)

ren.add(csa_odfs_actor)
print('Saving illustration as csa_odfs.png')
window.record(ren, n_frames=1, out_path='csa_odfs.png', size=(600, 600))
コード例 #16
0
def tracking(image,
             bvecs,
             bvals,
             wm,
             seeds,
             fibers,
             prune_length=3,
             rseed=42,
             plot=False,
             proba=False,
             verbose=False):
    # Pipelines transcribed from:
    #   https://dipy.org/documentation/1.1.1./examples_built/tracking_introduction_eudx/#example-tracking-introduction-eudx
    #   https://dipy.org/documentation/1.1.1./examples_built/tracking_probabilistic/

    # Load Images
    dwi_loaded = nib.load(image)
    dwi_data = dwi_loaded.get_fdata()

    wm_loaded = nib.load(wm)
    wm_data = wm_loaded.get_fdata()

    seeds_loaded = nib.load(seeds)
    seeds_data = seeds_loaded.get_fdata()
    seeds = utils.seeds_from_mask(seeds_data, dwi_loaded.affine, density=2)

    # Load B-values & B-vectors
    # NB. Use aligned b-vecs if providing eddy-aligned data
    bvals, bvecs = read_bvals_bvecs(bvals, bvecs)
    gtab = gradient_table(bvals, bvecs)
    csa_model = CsaOdfModel(gtab, sh_order=6)

    # Set stopping criterion
    gfa = csa_model.fit(dwi_data, mask=wm_data).gfa
    stop_criterion = ThresholdStoppingCriterion(gfa, .25)

    if proba:
        # Establish ODF model
        response, ratio = auto_response(gtab,
                                        dwi_data,
                                        roi_radius=10,
                                        fa_thr=0.7)
        csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
        csd_fit = csd_model.fit(dwi_data, mask=wm_data)

        # Create Probabilisitic direction getter
        fod = csd_fit.odf(default_sphere)
        pmf = fod.clip(min=0)
        prob_dg = ProbabilisticDirectionGetter.from_pmf(pmf,
                                                        max_angle=30.,
                                                        sphere=default_sphere)
        # Use the probabilisitic direction getter as the dg
        dg = prob_dg

    else:
        # Establish ODF model
        csa_peaks = peaks_from_model(csa_model,
                                     dwi_data,
                                     default_sphere,
                                     relative_peak_threshold=0.8,
                                     min_separation_angle=45,
                                     mask=wm_data)

        # Use the CSA peaks as the dg
        dg = csa_peaks

    # Create generator and perform tracing
    s_generator = LocalTracking(dg,
                                stop_criterion,
                                seeds,
                                dwi_loaded.affine,
                                0.5,
                                random_seed=rseed)
    streamlines = Streamlines(s_generator)

    # Prune streamlines
    streamlines = ArraySequence(
        [strline for strline in streamlines if len(strline) > prune_length])
    sft = StatefulTractogram(streamlines, dwi_loaded, Space.RASMM)

    # Save streamlines
    save_trk(sft, fibers + ".trk")

    # Visualize fibers
    if plot and has_fury:
        from dipy.viz import window, actor, colormap as cmap

        # Create the 3D display.
        r = window.Renderer()
        r.add(actor.line(streamlines, cmap.line_colors(streamlines)))
        window.record(r, out_path=fibers + '.png', size=(800, 800))
コード例 #17
0
ファイル: reconst_csa.py プロジェクト: DALILA2015/dipy
the ODF. In order to obtain the full ODF, return_odf should be True. Before
enabling this option, make sure that you have enough memory.

Let's visualize the ODFs of a small rectangular area in an axial slice of the
splenium of the corpus callosum (CC).
"""

data_small = maskdata[13:43, 44:74, 28:29]

from dipy.data import get_sphere
sphere = get_sphere('symmetric724')

from dipy.viz import fvtk
r = fvtk.ren()

csaodfs = csamodel.fit(data_small).odf(sphere)

"""
It is common with CSA ODFs to produce negative values, we can remove those using ``np.clip``
"""

csaodfs = np.clip(csaodfs, 0, np.max(csaodfs, -1)[..., None])

fvtk.add(r, fvtk.sphere_funcs(csaodfs, sphere, colormap='jet'))
print('Saving illustration as csa_odfs.png')
fvtk.record(r, n_frames=1, out_path='csa_odfs.png', size=(600, 600))

"""
.. figure:: csa_odfs.png
   :align: center
コード例 #18
0
ファイル: csa_odf_example_gfa_sh.py プロジェクト: mdesco/dipy
fetch_stanford_hardi()
img, gtab = read_stanford_hardi()


data = img.get_data()
affine = img.get_affine()
print('data.shape (%d, %d, %d, %d)' % data.shape)


mask = data[..., 0] > 50

mask_small  = mask[20:50,55:85, 38:40]
data_small  = data[20:50,55:85, 38:40]

csamodel = CsaOdfModel(gtab, 4, smooth=0.006)
csa_fit = csamodel.fit(data_small)

sphere = get_sphere('symmetric724')
csa_odf = csa_fit.odf(sphere)
gfa_csa = gfa(csa_odf)

odfs = csa_odf.clip(0)
gfa_csa_wo_zeros = gfa(odfs)

csa_mm = minmax_normalize(odfs) 
gfa_csa_mm = gfa(csa_mm)

qballmodel = QballModel(gtab, 6, smooth=0.006)
qball_fit = qballmodel.fit(data_small)
qball_odf = qball_fit.odf(sphere)
gfa_qball = gfa(qball_odf)
コード例 #19
0
def solve_shm(data):
    csamodel = CsaOdfModel(data['gtab'], 4)
    u = csamodel.fit(data['S']).odf(data['sph'])
    return np.clip(u, 0, np.max(u, -1)[..., None])
コード例 #20
0
ファイル: tracking_method.py プロジェクト: geyunxiang/mmdps
def determine(name=None,
              data_path=None,
              output_path='.',
              Threshold=.20,
              data_list=None,
              seed='.',
              minus_ROI_mask='.',
              one_node=False,
              two_node=False):

    time0 = time.time()
    print("begin loading data, time:", time.time() - time0)

    if data_list == None:
        data, affine, img, labels, gtab, head_mask = get_data(name, data_path)
    else:
        data = data_list['DWI']
        affine = data_list['affine']
        img = data_list['img']
        labels = data_list['labels']
        gtab = data_list['gtab']
        head_mask = data_list['head_mask']

    print(type(seed))

    if type(seed) != str:
        seed_mask = seed
    else:
        seed_mask = (labels == 2) * (head_mask == 1)

    white_matter = (labels == 2) * (head_mask == 1)
    seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

    print("begin reconstruction, time:", time.time() - time0)
    response, ratio = auto_response_ssst(gtab, data, roi_radii=10, fa_thr=0.7)
    csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
    csd_fit = csd_model.fit(data, mask=white_matter)

    csa_model = CsaOdfModel(gtab, sh_order=6)
    gfa = csa_model.fit(data, mask=white_matter).gfa
    stopping_criterion = ThresholdStoppingCriterion(gfa, Threshold)

    #from dipy.data import small_sphere

    print("begin tracking, time:", time.time() - time0)
    detmax_dg = DeterministicMaximumDirectionGetter.from_shcoeff(
        csd_fit.shm_coeff, max_angle=30., sphere=default_sphere)
    streamline_generator = LocalTracking(detmax_dg,
                                         stopping_criterion,
                                         seeds,
                                         affine,
                                         step_size=.5)
    streamlines = Streamlines(streamline_generator)
    sft = StatefulTractogram(streamlines, img, Space.RASMM)

    if one_node or two_node:
        sft.to_vox()
        streamlines = reduct_seed_ROI(sft.streamlines, seed_mask, one_node,
                                      two_node)

        if type(minus_ROI_mask) != str:

            streamlines = minus_ROI(streamlines=streamlines,
                                    ROI=minus_ROI_mask)

        sft = StatefulTractogram(streamlines, img, Space.VOX)
        sft._vox_to_rasmm()

    print("begin saving, time:", time.time() - time0)

    output = output_path + '/tractogram_deterministic_' + name + '.trk'
    save_trk(sft, output)

    print("finished, time:", time.time() - time0)
コード例 #21
0
ファイル: reconst_csa.py プロジェクト: klchan13/dipy
the ODF. In order to obtain the full ODF, return_odf should be True. Before
enabling this option, make sure that you have enough memory.

Let's visualize the ODFs of a small rectangular area in an axial slice of the
splenium of the corpus callosum (CC).
"""

data_small = maskdata[13:43, 44:74, 28:29]

from dipy.data import get_sphere
sphere = get_sphere('symmetric724')

from dipy.viz import fvtk
r = fvtk.ren()

csaodfs = csamodel.fit(data_small).odf(sphere)

"""
It is common with CSA ODFs to produce negative values, we can remove those using ``np.clip``
"""

csaodfs = np.clip(csaodfs, 0, np.max(csaodfs, -1)[..., None])

fvtk.add(r, fvtk.sphere_funcs(csaodfs, sphere, colormap='jet'))
print('Saving illustration as csa_odfs.png')
fvtk.record(r, n_frames=1, out_path='csa_odfs.png', size=(600, 600))

"""
.. figure:: csa_odfs.png
   :align: center
コード例 #22
0
seed_mask = (labels == 2)
white_matter = (labels == 1) | (labels == 2)
seeds = utils.seeds_from_mask(seed_mask, affine, density=1)

response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6)
csd_fit = csd_model.fit(data, mask=white_matter)
"""
We use the GFA of the CSA model to build a stopping criterion.
"""

from dipy.reconst.shm import CsaOdfModel

csa_model = CsaOdfModel(gtab, sh_order=6)
gfa = csa_model.fit(data, mask=white_matter).gfa
stopping_criterion = ThresholdStoppingCriterion(gfa, .25)
"""
The Fiber Orientation Distribution (FOD) of the CSD model estimates the
distribution of small fiber bundles within each voxel. We can use this
distribution for probabilistic fiber tracking. One way to do this is to
represent the FOD using a discrete sphere. This discrete FOD can be used by the
``ProbabilisticDirectionGetter`` as a PMF for sampling tracking directions. We
need to clip the FOD to use it as a PMF because the latter cannot have negative
values. Ideally, the FOD should be strictly positive, but because of noise
and/or model failures sometimes it can have negative values.
"""

from dipy.direction import ProbabilisticDirectionGetter
from dipy.data import small_sphere
from dipy.io.stateful_tractogram import Space, StatefulTractogram
コード例 #23
0
ファイル: shm_models_examples.py プロジェクト: mdesco/dipy
fetch_stanford_hardi()
img, gtab = read_stanford_hardi()

vizu = 1

data = img.get_data()
affine = img.get_affine()
print('data.shape (%d, %d, %d, %d)' % data.shape)

#mrconvert dwi.nii -coord 3 0 - | threshold - - | median3D - - | median3D - mask.nii 
#mask = data[..., 0] > 50

order = 4
csamodel = CsaOdfModel(gtab, order, smooth=0.006)
print 'Computing the CSA odf...'
csafit  = csamodel.fit(data) 
coeff   = csafit._shm_coef

# dipy-dev compatible
#GFA = csafit.gfa
#nib.save(nib.Nifti1Image(GFA.astype('float32'), affine), 'gfa_csa.nii.gz')    
nib.save(nib.Nifti1Image(coeff.astype('float32'), affine), 'csa_odf_sh.nii.gz')


sphere = get_sphere('symmetric724')
odfs = sh_to_sf(coeff[20:50,55:85, 38:39], sphere, order)
if vizu :
    from dipy.viz import fvtk
    r = fvtk.ren()
    fvtk.add(r, fvtk.sphere_funcs(odfs, sphere, colormap='jet'))
    fvtk.show(r)