Beispiel #1
0
def eddy_correction(file_in, outPath, ref_bo):
    """
    Prueba documental.

    In:

    file_in: akakakakka
    outPath: kakakasjdjdlllf kklkd
    ref_bo. kskskdejien skkd  dllkd

    Out:

    """

    print('    - running Eddy Correction...')
    refNameOnly = utils.to_extract_filename(file_in)

    if not (os.path.exists(outPath + utils.to_extract_filename(file_in) +
                           d.id_eddy_correct + d.extension)):
        refName = utils.to_extract_filename_extention(file_in)

        os.system('cp ' + file_in + ' ' + d.path_temporal
                  )  # Copiamos archivo de difusion a la carpeta temporal
        fsl.eddy_correct(
            d.path_temporal + refName,
            d.path_temporal + refNameOnly + d.id_eddy_correct + '.nii', ref_bo)
        os.system(
            'cp ' + d.path_temporal + refNameOnly + d.id_eddy_correct +
            d.extension + ' ' +
            outPath)  # Copiamos archivo de difusion desde carpeta temporal

    return outPath + refNameOnly + d.id_eddy_correct + d.extension
Beispiel #2
0
def medianOtsu(file_in, outPath, median_radius=4, num_pass=4):
    print('    - running Median Otsu algoritm...')

    finalFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_median_otsu + '_maskedVolume' + d.extension
    binaryMaskFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_median_otsu + '_binaryMask' + d.extension
    b0MaskedFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_median_otsu + '_b0Masked' + d.extension

    if not (os.path.exists(finalFileName)):
        img = nib.load(file_in)
        data = img.get_data()
        maskedvolume, mask = median_otsu(data, median_radius, num_pass)

        nib.save(nib.Nifti1Image(maskedvolume.astype(np.float32), img.affine),
                 finalFileName)
        nib.save(nib.Nifti1Image(mask.astype(np.float32), img.affine),
                 binaryMaskFileName)
        nib.save(
            nib.Nifti1Image(
                maskedvolume[:, :, :, d.default_b0_ref].astype(np.float32),
                img.affine), b0MaskedFileName)

    return finalFileName, binaryMaskFileName
Beispiel #3
0
def registration_to(path_moving, path_static, path_output):
    moving_img = nib.load(path_moving)
    moving_data = moving_img.get_data()
    moving_affine = moving_img.affine

    img_static = nib.load(path_static)
    static_data = img_static.get_data()
    static_affine = img_static.affine

    affine, starting_affine = tools.affine_registration(
        moving_data,
        static_data,
        moving_grid2world=moving_affine,
        static_grid2world=static_affine)

    warped_moving, mapping = tools.syn_registration(
        moving_data,
        static_data,
        moving_grid2world=moving_affine,
        static_grid2world=static_affine,
        # step_length=0.1,
        # sigma_diff=2.0,
        metric='CC',
        dim=3,
        level_iters=[5, 5, 3],
        # dim=3, level_iters = [10, 10, 5],
        # prealign=affine.affine)
        prealign=starting_affine)

    ref_name = utils.to_extract_filename(path_moving)

    nib.save(nib.Nifti1Image(warped_moving.astype(np.float32), static_affine),
             path_output + ref_name + '_BET_normalized.nii')

    return warped_moving, static_affine, mapping
Beispiel #4
0
def to_estimate_dti(file_in, file_inMask, outPath, fbval, fbvec):
    print(d.separador + 'building DTI Model...')

    ref_name = utils.to_extract_filename(file_in)

    if (
            not (os.path.exists(outPath + ref_name + d.id_evecs + d.extension))
    ) | (not (os.path.exists(outPath + ref_name + d.id_evals + d.extension))):
        try:
            os.remove(outPath + ref_name + d.id_evecs + d.extension)
            os.remove(outPath + ref_name + d.id_evals + d.extension)
        except:
            print("Unexpected error:", sys.exc_info()[0])

        img = nib.load(file_in)
        data = img.get_data()
        mask = nib.load(file_inMask)
        mask = mask.get_data()

        bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
        gtab = gradient_table(bvals, bvecs)

        tensor_model = dti.TensorModel(gtab)
        tensor_fitted = tensor_model.fit(data, mask)

        nib.save(
            nib.Nifti1Image(tensor_fitted.evecs.astype(np.float32),
                            img.affine),
            outPath + ref_name + d.id_evecs + d.extension)
        nib.save(
            nib.Nifti1Image(tensor_fitted.evals.astype(np.float32),
                            img.affine),
            outPath + ref_name + d.id_evals + d.extension)

    return outPath + ref_name + d.id_evecs + d.extension, outPath + ref_name + d.id_evals + d.extension
Beispiel #5
0
def to_register_dwi_to_mni(path_in, path_out, path_bvec, path_bval):
    ref_name = utils.to_extract_filename(path_in)

    # if not os.path.exists(path_out + ref_name + '_normalized' + d.extension):

    img_DWI = nib.load(path_in)
    data_DWI = img_DWI.get_data()
    affine_DWI = img_DWI.affine

    bvals, bvecs = read_bvals_bvecs(path_bval, path_bvec)
    gtab = gradient_table(bvals, bvecs)

    b0 = data_DWI[..., gtab.b0s_mask]

    mean_b0 = np.mean(b0, -1)

    mni_t2 = nib.load(d.standard_t2)
    mni_t2_data = mni_t2.get_data()
    MNI_T2_affine = mni_t2.affine

    directionWarped = np.zeros((mni_t2_data.shape[0], mni_t2_data.shape[1],
                                mni_t2_data.shape[2], data_DWI.shape[-1]))
    rangos = range(data_DWI.shape[-1])

    affine, starting_affine = tools.affine_registration(
        mean_b0,
        mni_t2_data,
        moving_grid2world=affine_DWI,
        static_grid2world=MNI_T2_affine)

    warped_moving, mapping = tools.syn_registration(
        mean_b0,
        mni_t2_data,
        moving_grid2world=affine_DWI,
        static_grid2world=MNI_T2_affine,
        # step_length=0.1,
        # sigma_diff=2.0,
        metric='CC',
        dim=3,
        level_iters=[10, 10, 5],
        # prealign=affine.affine)
        prealign=starting_affine)

    for gradientDirection in rangos:
        # print(gradientDirection)
        directionWarped[:, :, :, gradientDirection] = mapping.transform(
            data_DWI[:, :, :, gradientDirection].astype(int),
            interpolation='nearest')

    nib.save(nib.Nifti1Image(directionWarped, MNI_T2_affine),
             path_out + ref_name + '_normalized' + d.extension)

    return path_out + ref_name + '_normalized' + d.extension, mapping
Beispiel #6
0
def betDWI(file_in, outPath):
    print('    - running BET with FSL...')

    finalFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_bet + '_dwi_masked' + d.extension
    binaryMaskFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_bet + '_b0_masked_mask' + d.extension
    b0MaskedFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_bet + '_b0_masked' + d.extension

    if not (os.path.exists(b0MaskedFileName)):
        fsl.bet(file_in, b0MaskedFileName, '-m -f .4')

        imgMask = nib.load(binaryMaskFileName)
        dataMask = imgMask.get_data()

        img = nib.load(file_in)
        data = img.get_data()

        data[dataMask == 0] = 0
        nib.save(nib.Nifti1Image(data.astype(np.float32), img.affine),
                 finalFileName)

    return finalFileName, binaryMaskFileName, b0MaskedFileName
Beispiel #7
0
def reslicing(file_in, outPath, vox_sz):
    print('    - runnning Reslice...')

    finalFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_reslice + d.extension
    if not (os.path.exists(finalFileName)):
        img = nib.load(file_in)
        data = img.get_data()
        affine = img.affine

        old_vox_sz = img.header.get_zooms()[:3]

        new_vox_sz = (vox_sz, vox_sz, vox_sz)

        # Si el tamano del voxel es isotropico, no es necesario hacer el reslice

        data, affine = reslice(data, affine, old_vox_sz, new_vox_sz)

        nib.save(nib.Nifti1Image(data, affine), finalFileName)
    return finalFileName
Beispiel #8
0
def registration_atlas_to(path_atlas, path_output, affine, mapping):
    img_atlas = nib.load(path_atlas)
    atlas_data = img_atlas.get_data()

    indexs = np.unique(atlas_data)

    ref_name = utils.to_extract_filename(path_atlas)
    list_path_roi = []

    for index in indexs:
        roi = (atlas_data == index)
        # warped_roi = mapping.transform_inverse(roi.astype(int)*255, interpolation='nearest')
        warped_roi = mapping.transform_inverse(
            ndim.binary_dilation(roi).astype(int), interpolation='nearest')

        warped_roi = ndim.binary_dilation(warped_roi)
        warped_roi = ndim.binary_erosion(warped_roi)

        bin_warped_roi = np.ceil(warped_roi)

        filled_warped_roi = ndim.binary_fill_holes(
            bin_warped_roi.astype(int)).astype(int)

        nib.save(nib.Nifti1Image(filled_warped_roi.astype(np.float32), affine),
                 path_output + ref_name + '_ROI_' + str(index) + d.extension)

        list_path_roi.append(path_output + ref_name + '_ROI_' + str(index) +
                             d.extension)
        # print("ROI # " + str(index) + " for " + ref_name + " Atlas, has been saved")

        if not ('registered_atlas' in locals()):
            registered_atlas = np.zeros(filled_warped_roi.shape)

        registered_atlas[filled_warped_roi != 0] = index

    nib.save(nib.Nifti1Image(registered_atlas.astype(np.float32), affine),
             path_output + ref_name + '_registered_' + d.extension)

    return list_path_roi
Beispiel #9
0
def nonLocalMean(file_in, outPath):
    print('    - running NonLocal Mean algoritm...')

    finalFileName = outPath + utils.to_extract_filename(
        file_in) + d.id_non_local_mean + d.extension

    if not (os.path.exists(finalFileName)):
        img = nib.load(file_in)
        data = img.get_data()

        newData = np.zeros(data.shape)
        gradientDirections = data.shape[-1]

        for index in range(gradientDirections):
            print(index)
            sigma = estimate_sigma(data[:, :, :, index], N=8)
            newData[:, :, :, index] = nlmeans(data[:, :, :, index],
                                              sigma=sigma)

        nib.save(nib.Nifti1Image(newData.astype(np.float32), img.affine),
                 finalFileName)
    return finalFileName
Beispiel #10
0
def registerAffine_atlas(pathAtlas, pathStandard, outPath, tempPath,
                         affineSubject, Subject):
    atlas = nib.load(pathAtlas)
    atlas_data = atlas.get_data()

    indexs = np.unique(atlas_data)

    refNameOnly = utils.to_extract_filename(pathAtlas)

    file_outSubject, omatSubject = fsl.flirt(
        pathStandard, tempPath + 'Aux_FLIRT' + d.extension, Subject,
        tempPath + 'Aux_FLIRT_omat.mat')
    fsl.hex_to_dec(omatSubject, omatSubject + '.mat2')
    omatSubject = omatSubject + '.mat2'

    for index in indexs:
        roi = (atlas_data == index)
        nib.save(nib.Nifti1Image(roi.astype(np.float32), affineSubject),
                 tempPath + refNameOnly + '_ROI_' + str(index) + d.extension)

        fsl.flirt_xfm(
            tempPath + refNameOnly + '_ROI_' + str(index) + d.extension,
            outPath + refNameOnly + '_ROI_' + str(index) + '_FLIRT' +
            d.extension, Subject, omatSubject)
Beispiel #11
0
def to_estimate_dti_maps(path_dwi_input, path_output, file_tensor_fitevecs,
                         file_tensor_fitevals):
    ref_name_only = utils.to_extract_filename(file_tensor_fitevecs)
    ref_name_only = ref_name_only[:-9]

    list_maps = []

    img_tensorFitevecs = nib.load(file_tensor_fitevecs)
    img_tensorFitevals = nib.load(file_tensor_fitevals)

    evecs = img_tensorFitevecs.get_data()
    evals = img_tensorFitevals.get_data()

    affine = img_tensorFitevecs.affine

    print(d.separador + d.separador + 'computing of FA map')
    FA = fractional_anisotropy(evals)
    FA[np.isnan(FA)] = 0
    nib.save(nib.Nifti1Image(FA.astype(np.float32), affine),
             path_output + ref_name_only + '_FA' + d.extension)

    list_maps.append(path_output + ref_name_only + '_FA' + d.extension)

    print(d.separador + d.separador + 'computing of Color FA map')
    FA2 = np.clip(FA, 0, 1)
    RGB = color_fa(FA2, evecs)
    nib.save(nib.Nifti1Image(np.array(255 * RGB, 'uint8'), affine),
             path_output + ref_name_only + '_FA_RGB' + d.extension)

    print(d.separador + d.separador + 'computing of MD map')
    MD = dti.mean_diffusivity(evals)
    nib.save(nib.Nifti1Image(MD.astype(np.float32), affine),
             path_output + ref_name_only + '_MD' + d.extension)

    list_maps.append(path_output + ref_name_only + '_MD' + d.extension)

    print(d.separador + d.separador + 'computing of AD map')
    AD = dti.axial_diffusivity(evals)
    nib.save(nib.Nifti1Image(AD.astype(np.float32), affine),
             path_output + ref_name_only + '_AD' + d.extension)

    list_maps.append(path_output + ref_name_only + '_AD' + d.extension)

    print(d.separador + d.separador + 'computing of RD map')
    RD = dti.radial_diffusivity(evals)
    nib.save(nib.Nifti1Image(RD.astype(np.float32), affine),
             path_output + ref_name_only + '_RD' + d.extension)

    list_maps.append(path_output + ref_name_only + '_RD' + d.extension)

    sphere = get_sphere('symmetric724')
    peak_indices = quantize_evecs(evecs, sphere.vertices)

    eu = EuDX(FA.astype('f8'),
              peak_indices,
              seeds=300000,
              odf_vertices=sphere.vertices,
              a_low=0.15)
    tensor_streamlines = [streamline for streamline in eu]

    hdr = nib.trackvis.empty_header()
    hdr['voxel_size'] = nib.load(path_dwi_input).get_header().get_zooms()[:3]
    hdr['voxel_order'] = 'LAS'
    hdr['dim'] = FA.shape

    tensor_streamlines_trk = ((sl, None, None) for sl in tensor_streamlines)

    nib.trackvis.write(path_output + ref_name_only + '_tractography_EuDx.trk',
                       tensor_streamlines_trk,
                       hdr,
                       points_space='voxel')

    return list_maps