예제 #1
0
def run_betDWI(path_input, path_output):
    print('    - running BET with FSL...')
    finalFileName = os.path.join(
        path_output,
        utils.to_extract_filename(path_input) + d.id_bet + '_dwi_masked' +
        d.extension)
    binaryMaskFileName = os.path.join(
        path_output,
        utils.to_extract_filename(path_input) + d.id_bet + '_b0_masked_mask' +
        d.extension)
    b0MaskedFileName = os.path.join(
        path_output,
        utils.to_extract_filename(path_input) + d.id_bet + '_b0_masked' +
        d.extension)

    if not (os.path.exists(finalFileName)):

        fsl.bet(path_input, b0MaskedFileName, '-m -f .4')

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

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

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

    # return finalFileName, binaryMaskFileName, b0MaskedFileName
    print("Ejecutando")
    return finalFileName
예제 #2
0
def run_to_estimate_dti(path_input,
                        path_output,
                        fbval="",
                        fbvec="",
                        file_inMask=""):
    if fbval == "" or fbvec == "":
        folder_sujeto = path_output
        for l in os.listdir(folder_sujeto):
            if "TENSOR" in l and "bval" in l:
                fbval = os.path.join(folder_sujeto, l)
            if "TENSOR" in l and "bvec" in l:
                fbvec = os.path.join(folder_sujeto, l)

    if file_inMask == "":
        folder = os.path.dirname(path_input)
        for i in os.listdir(folder):
            if "masked_mask" in i:
                file_inMask = os.path.join(folder, i)

    #def to_estimate_dti(file_in, file_inMask, outPath, fbval, fbvec):
    print(d.separador + 'building DTI Model...')

    ref_name = utils.to_extract_filename(path_input)
    file_evecs = os.path.join(path_output, ref_name + d.id_evecs + d.extension)
    file_evals = os.path.join(path_output, ref_name + d.id_evals + d.extension)

    if (not (os.path.exists(file_evecs))) | (not (os.path.exists(file_evals))):
        try:
            os.remove(file_evecs)
            os.remove(file_evals)
        except:
            print("Unexpected error:", sys.exc_info()[0])

        img = nib.load(path_input)
        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), file_evecs)
        nib.save(
            nib.Nifti1Image(tensor_fitted.evals.astype(np.float32),
                            img.affine), file_evals)

    print(file_evecs)
    print(file_evals)
    print(path_input)
    return path_input
예제 #3
0
def run_eddy_correction(path_input,path_output,ref_bo):
    print('    - running Eddy Correction...')
    refNameOnly = utils.to_extract_filename(path_input)
    final_name=os.path.join(path_output,refNameOnly + d.id_eddy_correct + d.extension)

    if not os.path.exists(final_name):
        refName = utils.to_extract_filename_extention(path_input)
        path_temporal=os.path.join(path_output,"temp_eddy")
        os.mkdir(path_temporal)
        os.system('cp ' + path_input + ' ' + path_temporal)  # Copiamos archivo de difusion a la carpeta temporal
        fsl.eddy_correct(path_temporal +"/"+ refName, path_temporal +"/"+ refNameOnly + d.id_eddy_correct + '.nii', ref_bo)
        os.system('cp ' + os.path.join(path_temporal, refNameOnly + d.id_eddy_correct + d.extension) + ' ' + path_output)  # Copiamos archivo de difusion desde carpeta temporal
    #     shutil.rmtree(path_temporal)
    return final_name
예제 #4
0
def run_nonLocalMean(path_input,path_output):   
    print('    - running NonLocal Mean algoritm...')
    finalFileName = os.path.join(path_output, utils.to_extract_filename(path_input) + d.id_non_local_mean + d.extension)

    if not (os.path.exists(finalFileName)):
        img = nib.load(path_input)
        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
예제 #5
0
def run_reslicing(path_input, path_output, vox_sz=d.vox_sz):
    print('    - runnning Reslice...')
    finalFileName = os.path.join(
        path_output,
        utils.to_extract_filename(path_input) + d.id_reslice + d.extension)
    if not (os.path.exists(finalFileName)):
        img = nib.load(path_input)
        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
예제 #6
0
import numpy as np
from dipy.io import read_bvals_bvecs
from dipy.core.gradients import gradient_table

###################
folder_sujeto = path_output
for l in os.listdir(folder_sujeto):
    if "bval" in l:
        fbval = os.path.join(folder_sujeto, l)
    if "bvec" in l:
        fbvec = os.path.join(folder_sujeto, l)

#################

# def to_register_dwi_to_mni(path_in, path_out, path_bvec, path_bval):
ref_name = utils.to_extract_filename(path_input)

finalname = os.path.join(path_output, ref_name + '_normalized' + d.extension)

if not os.path.exists(finalname):

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

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

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

    mean_b0 = np.mean(b0, -1)
예제 #7
0
import shutil

path_input = sys.argv[1]
path_output = sys.argv[2]
"""
Prueba documental.
In:
file_in: akakakakka
outPath: kakakasjdjdlllf kklkd
ref_bo. kskskdejien skkd  dllkd
Out:
"""
ref_bo = '0'
print('    - running Eddy Correction...')

refNameOnly = utils.to_extract_filename(path_input)
final_name = os.path.join(path_output,
                          refNameOnly + d.id_eddy_correct + d.extension)

if not os.path.exists(final_name):
    refName = utils.to_extract_filename_extention(path_input)
    path_temporal = os.path.join(path_output, "temp_eddy")
    os.mkdir(path_temporal)
    os.system(
        'cp ' + path_input + ' ' +
        path_temporal)  # Copiamos archivo de difusion a la carpeta temporal
    fsl.eddy_correct(
        path_temporal + "/" + refName,
        path_temporal + "/" + refNameOnly + d.id_eddy_correct + '.nii', ref_bo)
    os.system(
        'cp ' + os.path.join(path_temporal, refNameOnly + d.id_eddy_correct +
예제 #8
0
def run_to_estimate_dti_maps(path_input,
                             path_output,
                             file_tensor_fitevals="",
                             file_tensor_fitevecs="",
                             fbval="",
                             fbvec=""):
    folder = os.path.dirname(path_input)
    if fbval == "" or fbvec == "":
        folder_sujeto = path_output
        for l in os.listdir(folder_sujeto):
            if "TENSOR" in l and "bval" in l:
                fbval = os.path.join(folder_sujeto, l)
            if "TENSOR" in l and "bvec" in l:
                fbvec = os.path.join(folder_sujeto, l)

    if file_tensor_fitevals == "" or file_tensor_fitevecs == "":

        for i in os.listdir(folder):
            if "DTIEvals" in i:
                file_tensor_fitevals = os.path.join(folder, i)

        for i in os.listdir(folder):
            if "DTIEvecs" in i:
                file_tensor_fitevecs = os.path.join(folder, i)

    if not os.path.exists(os.path.join(folder, "list_maps.txt")):

        # 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),
            os.path.join(path_output, ref_name_only + '_FA' + d.extension))

        list_maps.append(
            os.path.join(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),
            os.path.join(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),
            os.path.join(path_output, ref_name_only + '_MD' + d.extension))

        list_maps.append(
            os.path.join(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),
            os.path.join(path_output, ref_name_only + '_AD' + d.extension))

        list_maps.append(
            os.path.join(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),
            os.path.join(path_output, ref_name_only + '_RD' + d.extension))

        list_maps.append(
            os.path.join(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_input).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(os.path.join(
            path_output, ref_name_only + '_tractography_EuDx.trk'),
                           tensor_streamlines_trk,
                           hdr,
                           points_space='voxel')

        print(list_maps)
        with open(os.path.join(path_output, "list_maps.txt"), "w") as f:
            for s in list_maps:
                f.write(str(s) + "\n")

    return path_input
예제 #9
0
sys.path+=[os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/"]


path_input = sys.argv[1]
path_output = sys.argv[2]

from tareas.dependencias import utils
from tareas.dependencias import definitions as d
from dipy.segment.mask import median_otsu
import nibabel as nib
import numpy as np
median_radius = 4
num_pass = 4
# print('    - running Median Otsu algoritm...')

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

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

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

# return finalFileName, binaryMaskFileName
print(finalFileName)
예제 #10
0
path_input = sys.argv[1]
path_output = sys.argv[2]

from tareas.dependencias import utils
from tareas.dependencias import definitions as d
import nibabel as nib
import numpy as np
from dipy.denoise.noise_estimate import estimate_sigma
from dipy.denoise.nlmeans import nlmeans

print('    - running NonLocal Mean algoritm...')

finalFileName = os.path.join(
    path_output,
    utils.to_extract_filename(path_input) + d.id_non_local_mean + d.extension)

if not (os.path.exists(finalFileName)):
    img = nib.load(path_input)
    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)
예제 #11
0

path_input = sys.argv[1]
path_output = sys.argv[2]


from tareas.dependencias import utils
from tareas.dependencias import definitions as d
from tareas.dependencias import fsl_wrapper as fsl
import nibabel as nib
import numpy as np
print('    - running BET with FSL...')



finalFileName = os.path.join(path_output,utils.to_extract_filename(path_input) + d.id_bet + '_dwi_masked' + d.extension)
binaryMaskFileName = os.path.join(path_output,utils.to_extract_filename(path_input) + d.id_bet + '_b0_masked_mask' + d.extension)
b0MaskedFileName = os.path.join(path_output,utils.to_extract_filename(path_input) + d.id_bet + '_b0_masked' + d.extension)

if not (os.path.exists(finalFileName)):

    fsl.bet(path_input, b0MaskedFileName, '-m -f .4')

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

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

    data[dataMask == 0] = 0
    nib.save(nib.Nifti1Image(data.astype(np.float32), img.affine), finalFileName)
예제 #12
0
    if "DTIEvecs" in i:
        file_tensor_fitevecs = os.path.join(folder, i)

folder_sujeto = path_output
for l in os.listdir(folder_sujeto):
    if "bval" in l:
        fbval = os.path.join(folder_sujeto, l)
    if "bvec" in l:
        fbvec = os.path.join(folder_sujeto, l)

#################

if not os.path.exists(os.path.join(folder, "list_maps.txt")):

    # 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
예제 #13
0
def run_to_register_dwi_to_mni(path_input,path_output,fbval="",fbvec=""):
    
    if fbval == "" or fbvec == "":
        folder_sujeto=path_output
        for l in os.listdir(folder_sujeto):
            if "TENSOR" in l and "bval" in l:
                fbval=os.path.join(folder_sujeto,l)
            if "TENSOR" in l and "bvec" in l:
                fbvec=os.path.join(folder_sujeto,l)

    # def to_register_dwi_to_mni(path_in, path_out, path_bvec, path_bval):
    ref_name = utils.to_extract_filename(path_input)

    finalname=os.path.join(path_output,ref_name + '_normalized' + d.extension)

    if not os.path.exists(finalname ):

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

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

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

        mean_b0 = np.mean(b0, -1)

        try:
            mni_t2 = nib.load(d.standard_t2)
        except:
            mni_t2 = nib.load(d.standard_t1)
        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]),dtype=np.float32)
        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)
        print("terminado affine registration")
        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)
        print("terminado syn registration")
        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), finalname)

        affine = nib.load(finalname).affine

        list_path_atlas_1 = utils.registration_atlas_to(d.aan_atlas, path_output, affine, mapping)
        with open(os.path.join(path_output,"list_path_atlas_1.txt"), "w") as f:
            for s in list_path_atlas_1:
                f.write(str(s) +"\n")
        list_path_atlas_2 = utils.registration_atlas_to(d.morel_atlas, path_output, affine, mapping)
        with open(os.path.join(path_output,"list_path_atlas_2.txt"), "w") as f:
            for s in list_path_atlas_2:
                f.write(str(s) +"\n")
        list_path_atlas_3 = utils.registration_atlas_to(d.hypothalamus_atlas, path_output, affine, mapping)
        with open(os.path.join(path_output,"list_path_atlas_3.txt"), "w") as f:
            for s in list_path_atlas_3:
                f.write(str(s) +"\n")
        list_path_atlas_4 = utils.registration_atlas_to(d.harvard_oxford_cort_atlas, path_output, affine, mapping)
        with open(os.path.join(path_output,"list_path_atlas_4.txt"), "w") as f:
            for s in list_path_atlas_4:
                f.write(str(s) +"\n")


    print(finalname)
    return path_input
예제 #14
0
sys.path += [os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"]

from tareas.dependencias import utils
from tareas.dependencias import definitions as d
import nibabel as nib
from dipy.align.reslice import reslice

path_input = sys.argv[1]
path_output = sys.argv[2]

vox_sz = d.vox_sz
print('    - runnning Reslice...')

finalFileName = os.path.join(
    path_output,
    utils.to_extract_filename(path_input) + d.id_reslice + d.extension)
if not (os.path.exists(finalFileName)):
    img = nib.load(path_input)
    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)
print(finalFileName)