コード例 #1
0
ファイル: lr.py プロジェクト: submagr/pyLAR
def run(config, software, im_fns, check=True):
    """Low-rank decomposition."""
    log = logging.getLogger(__name__)
    # Checks that all variables are set correctly
    if check:
        check_requirements(config, software)
    # Initialize variables
    selection = config.selection
    result_dir = config.result_dir
    sigma = config.sigma
    reference_im_fn = config.reference_im_fn
    num_of_data = len(selection)
    # Pre-processing: registration and histogram matching
    s = time.time()
    if config.registration == 'affine':
        log.info('Affine registration')
        pyLAR.affineRegistrationStep(software.EXE_BRAINSFit, im_fns,
                                     result_dir, selection, reference_im_fn)
    elif config.registration == 'rigid':
        log.info('Rigid registration')
        pyLAR.rigidRegistrationStep(software.EXE_BRAINSFit, im_fns, result_dir,
                                    selection, reference_im_fn)
    elif config.registration == 'none':
        pass
    else:
        raise Exception('Unknown registration')
    if config.histogram_matching:
        pyLAR.histogramMatchingStep(selection, result_dir)

    e = time.time()
    l = e - s
    log.info('Preprocessing - total running time:  %f mins' % (l / 60.0))

    # Loading images and blurring them if option selected.
    s = time.time()
    im_ref = sitk.ReadImage(reference_im_fn)
    im_ref_array = sitk.GetArrayFromImage(im_ref)
    z_dim, x_dim, y_dim = im_ref_array.shape
    vector_length = z_dim * x_dim * y_dim
    del im_ref, im_ref_array
    Y = np.zeros((vector_length, num_of_data))
    for i in range(num_of_data):
        if config.registration == 'none':
            im_file = im_fns[selection[i]]
        else:
            im_file = os.path.join(result_dir, 'L0_Iter0_' + str(i) + '.nrrd')
        log.info("Input File: " + im_file)
        inIm = sitk.ReadImage(im_file)
        tmp = sitk.GetArrayFromImage(inIm)
        if sigma > 0:  # blurring
            log.info("Blurring: " + str(sigma))
            outIm = pyLAR.GaussianBlur(inIm, None, sigma)
            tmp = sitk.GetArrayFromImage(outIm)
        Y[:, i] = tmp.reshape(-1)
        del tmp
    # Low-Rank and sparse decomposition
    low_rank, sparse, n_iter, rank, sparsity, sum_sparse = pyLAR.rpca(
        Y, config.lamda)
    lr_fn = pyLAR.saveImagesFromDM(low_rank,
                                   os.path.join(result_dir, 'L' + '_LowRank_'),
                                   reference_im_fn)
    sp_fn = pyLAR.saveImagesFromDM(sparse,
                                   os.path.join(result_dir, 'L' + '_Sparse_'),
                                   reference_im_fn)
    pyLAR.writeTxtFromList(os.path.join(result_dir, 'list_outputs.txt'),
                           lr_fn + sp_fn)
    e = time.time()
    l = e - s
    log.info("Rank: " + str(rank))
    log.info("Sparsity: " + str(sparsity))
    log.info('Processing - total running time:  %f mins' % (l / 60.0))
    return sparsity, sum_sparse
コード例 #2
0
ファイル: nglra.py プロジェクト: KitwareMedical/pyLAR
def _runIteration(vector_length, level, currentIter, config, im_fns, sigma, gridSize, maxDisp, software):
    """Iterative unbiased low-rank atlas creation from a selection of images"""
    log = logging.getLogger(__name__)
    result_dir = config.result_dir
    selection = config.selection
    reference_im_fn = config.reference_im_fn
    use_healthy_atlas = config.use_healthy_atlas
    registration_type = config.registration_type
    lamda = config.lamda
    listOutputImages = []
    if registration_type == 'BSpline' or registration_type == 'Demons':
        EXE_BRAINSResample = software.EXE_BRAINSResample
        EXE_InvertDeformationField = software.EXE_InvertDeformationField
        if registration_type == 'BSpline':
            EXE_BRAINSFit = software.EXE_BRAINSFit
            EXE_BSplineToDeformationField = software.EXE_BSplineToDeformationField
        elif registration_type == 'Demons':
            EXE_BRAINSDemonWarp = software.EXE_BRAINSDemonWarp
    elif registration_type == 'ANTS':
        EXE_antsRegistration = software.EXE_antsRegistration
        EXE_WarpImageMultiTransform = software.EXE_WarpImageMultiTransform
        ants_params = config.ants_params
    # Prepares data matrix for low-rank decomposition
    num_of_data = len(selection)
    Y = np.zeros((vector_length, num_of_data))
    iter_prefix = 'L' + str(level) + '_Iter'
    iter_path = os.path.join(result_dir, iter_prefix)
    current_path_iter = iter_path + str(currentIter)
    prev_path_iter = iter_path + str(currentIter-1)
    for i in range(num_of_data):
        im_file = prev_path_iter + '_' + str(i) + '.nrrd'
        inIm = sitk.ReadImage(im_file)
        tmp = sitk.GetArrayFromImage(inIm)
        if sigma > 0:  # blurring
            log.info("Blurring: " + str(sigma))
            outIm = pyLAR.GaussianBlur(inIm, None, sigma)
            tmp = sitk.GetArrayFromImage(outIm)
        Y[:, i] = tmp.reshape(-1)
        del tmp

    # Low-rank and sparse decomposition
    low_rank, sparse, n_iter, rank, sparsity, sum_sparse = pyLAR.rpca(Y, lamda)
    lr = pyLAR.saveImagesFromDM(low_rank, current_path_iter + '_LowRank_', reference_im_fn)
    sp = pyLAR.saveImagesFromDM(sparse, current_path_iter + '_Sparse_', reference_im_fn)
    listOutputImages = lr + sp
    # Visualize and inspect
    try:
        import matplotlib.pyplot as plt
        fig = plt.figure(figsize=(15, 5))
        slice_prefix = 'L' + str(level) + '_' + str(currentIter)
        pyLAR.showSlice(Y, slice_prefix + ' Input', plt.cm.gray, 0, reference_im_fn)
        pyLAR.showSlice(low_rank, slice_prefix + ' low rank', plt.cm.gray, 1, reference_im_fn)
        pyLAR.showSlice(np.abs(sparse), slice_prefix + ' sparse', plt.cm.gray, 2, reference_im_fn)
        plt.savefig(current_path_iter + '.png')
        fig.clf()
        plt.close(fig)
    except ImportError:
        pass

    del low_rank, sparse, Y

    # Unbiased low-rank atlas building (ULAB)
    if not use_healthy_atlas:
        EXE_AverageImages = software.EXE_AverageImages
        # Average the low-rank images to produce the Atlas
        atlasIm = current_path_iter + '_atlas.nrrd'
        listOfImages = []
        num_of_data = len(selection)
        for i in range(num_of_data):
            lrIm = current_path_iter + '_LowRank_' + str(i) + '.nrrd'
            listOfImages.append(lrIm)
        pyLAR.AverageImages(EXE_AverageImages, listOfImages, atlasIm)

        im = sitk.ReadImage(atlasIm)
        im_array = sitk.GetArrayFromImage(im)
        z_dim, x_dim, y_dim = im_array.shape
        try:
            import matplotlib.pyplot as plt
            plt.figure()
            implot = plt.imshow(np.flipud(im_array[z_dim / 2, :, :]), plt.cm.gray)
            plt.title(iter_prefix + str(currentIter) + ' atlas')
            plt.savefig(current_path_iter + '.png')
        except ImportError:
            pass
        reference_im_fn = atlasIm
    listOutputImages += [reference_im_fn]
    for i in range(num_of_data):
        # Warps the low-rank image back to the initial state (the non-greedy way)
        invWarpedlowRankIm = ''
        if currentIter == 1:
            invWarpedlowRankIm = current_path_iter + '_LowRank_' + str(i) + '.nrrd'
        else:
            lowRankIm = current_path_iter + '_LowRank_' + str(i) + '.nrrd'
            invWarpedlowRankIm = current_path_iter + '_InvWarped_LowRank_' + str(i) + '.nrrd'
            if registration_type == 'BSpline' or registration_type == 'Demons':
                previousIterDVF = prev_path_iter + '_DVF_' + str(i) + '.nrrd'
                inverseDVF = prev_path_iter + '_INV_DVF_' + str(i) + '.nrrd'
                pyLAR.genInverseDVF(EXE_InvertDeformationField, previousIterDVF, inverseDVF, True)
                pyLAR.updateInputImageWithDVF(EXE_BRAINSResample, lowRankIm, reference_im_fn,
                                              inverseDVF, invWarpedlowRankIm, True)
            if registration_type == 'ANTS':
                previousIterTransformPrefix = prev_path_iter + '_' + str(i) + '_'
                pyLAR.ANTSWarpImage(EXE_WarpImageMultiTransform, lowRankIm, invWarpedlowRankIm, reference_im_fn,
                                    previousIterTransformPrefix, True, True)

        # Registers each inversely-warped low-rank image to the Atlas image
        outputIm = current_path_iter + '_Deformed_LowRank' + str(i) + '.nrrd'
        # .tfm for BSpline only
        outputTransform = current_path_iter + '_Transform_' + str(i) + '.tfm'
        outputDVF = current_path_iter + '_DVF_' + str(i) + '.nrrd'

        movingIm = invWarpedlowRankIm
        fixedIm = reference_im_fn

        initial_prefix = 'L' + str(level) + '_Iter0_'
        initialInputImage = os.path.join(result_dir, initial_prefix + str(i) + '.nrrd')
        newInputImage = current_path_iter + '_' + str(i) + '.nrrd'

        if registration_type == 'BSpline':
            pyLAR.BSplineReg_BRAINSFit(EXE_BRAINSFit, fixedIm, movingIm, outputIm, outputTransform,
                                              gridSize, maxDisp, EXECUTE=True)
            pyLAR.ConvertTransform(EXE_BSplineToDeformationField, reference_im_fn,
                                                outputTransform, outputDVF, EXECUTE=True)
            pyLAR.updateInputImageWithDVF(EXE_BRAINSResample, initialInputImage, reference_im_fn,
                                                       outputDVF, newInputImage, EXECUTE=True)
        elif registration_type == 'Demons':
            pyLAR.DemonsReg(EXE_BRAINSDemonWarp, fixedIm, movingIm, outputIm, outputDVF, EXECUTE=True)
            pyLAR.updateInputImageWithDVF(EXE_BRAINSResample, initialInputImage, reference_im_fn,
                                                       outputDVF, newInputImage, EXECUTE=True)
        elif registration_type == 'ANTS':
            # Generates a warp(DVF) file and an affine file
            outputTransformPrefix = current_path_iter + '_' + str(i) + '_'
            # if currentIter > 1:
            # initialTransform = os.path.join(result_dir, iter_prefix + str(currentIter-1) + '_' + str(i) + '_0Warp.nii.gz')
            # else:
            pyLAR.ANTS(EXE_antsRegistration, fixedIm, movingIm, outputTransformPrefix, ants_params, EXECUTE=True)
            # Generates the warped input image with the specified file name
            pyLAR.ANTSWarpImage(EXE_WarpImageMultiTransform, initialInputImage, newInputImage,
                                             reference_im_fn, outputTransformPrefix, EXECUTE=True)
        else:
            raise('Unrecognized registration type:', registration_type)
        listOutputImages += [newInputImage]
    return sparsity, sum_sparse, listOutputImages
コード例 #3
0
ファイル: lr.py プロジェクト: KitwareMedical/pyLAR
def run(config, software, im_fns, check=True):
    """Low-rank decomposition."""
    log = logging.getLogger(__name__)
    # Checks that all variables are set correctly
    if check:
        check_requirements(config, software)
    # Initialize variables
    selection = config.selection
    result_dir = config.result_dir
    sigma = config.sigma
    reference_im_fn = config.reference_im_fn
    num_of_data = len(selection)
    # Pre-processing: registration and histogram matching
    s = time.time()
    if config.registration == 'affine':
        log.info('Affine registration')
        pyLAR.affineRegistrationStep(software.EXE_BRAINSFit, im_fns, result_dir, selection, reference_im_fn)
    elif config.registration == 'rigid':
        log.info('Rigid registration')
        pyLAR.rigidRegistrationStep(software.EXE_BRAINSFit, im_fns, result_dir, selection, reference_im_fn)
    elif config.registration == 'none':
        pass
    else:
        raise Exception('Unknown registration')
    if config.histogram_matching:
        pyLAR.histogramMatchingStep(selection, result_dir)

    e = time.time()
    l = e - s
    log.info('Preprocessing - total running time:  %f mins' % (l / 60.0))

    # Loading images and blurring them if option selected.
    s = time.time()
    im_ref = sitk.ReadImage(reference_im_fn)
    im_ref_array = sitk.GetArrayFromImage(im_ref)
    z_dim, x_dim, y_dim = im_ref_array.shape
    vector_length = z_dim * x_dim * y_dim
    del im_ref, im_ref_array
    Y = np.zeros((vector_length, num_of_data))
    for i in range(num_of_data):
        if config.registration == 'none':
            im_file = im_fns[selection[i]]
        else:
            im_file = os.path.join(result_dir, 'L0_Iter0_' + str(i) + '.nrrd')
        log.info("Input File: " + im_file)
        inIm = sitk.ReadImage(im_file)
        tmp = sitk.GetArrayFromImage(inIm)
        if sigma > 0:  # blurring
            log.info("Blurring: " + str(sigma))
            outIm = pyLAR.GaussianBlur(inIm, None, sigma)
            tmp = sitk.GetArrayFromImage(outIm)
        Y[:, i] = tmp.reshape(-1)
        del tmp
    # Low-Rank and sparse decomposition
    low_rank, sparse, n_iter, rank, sparsity, sum_sparse = pyLAR.rpca(Y, config.lamda)
    lr_fn = pyLAR.saveImagesFromDM(low_rank, os.path.join(result_dir, 'L' + '_LowRank_'), reference_im_fn)
    sp_fn = pyLAR.saveImagesFromDM(sparse, os.path.join(result_dir, 'L' + '_Sparse_'), reference_im_fn)
    pyLAR.writeTxtFromList(os.path.join(result_dir,'list_outputs.txt'),lr_fn+sp_fn)
    e = time.time()
    l = e - s
    log.info("Rank: " + str(rank))
    log.info("Sparsity: " + str(sparsity))
    log.info('Processing - total running time:  %f mins' % (l / 60.0))
    return sparsity, sum_sparse
コード例 #4
0
ファイル: nglra.py プロジェクト: submagr/pyLAR
def _runIteration(vector_length, level, currentIter, config, im_fns, sigma,
                  gridSize, maxDisp, software):
    """Iterative unbiased low-rank atlas creation from a selection of images"""
    log = logging.getLogger(__name__)
    result_dir = config.result_dir
    selection = config.selection
    reference_im_fn = config.reference_im_fn
    use_healthy_atlas = config.use_healthy_atlas
    registration_type = config.registration_type
    lamda = config.lamda
    listOutputImages = []
    if registration_type == 'BSpline' or registration_type == 'Demons':
        EXE_BRAINSResample = software.EXE_BRAINSResample
        EXE_InvertDeformationField = software.EXE_InvertDeformationField
        if registration_type == 'BSpline':
            EXE_BRAINSFit = software.EXE_BRAINSFit
            EXE_BSplineToDeformationField = software.EXE_BSplineToDeformationField
        elif registration_type == 'Demons':
            EXE_BRAINSDemonWarp = software.EXE_BRAINSDemonWarp
    elif registration_type == 'ANTS':
        EXE_antsRegistration = software.EXE_antsRegistration
        EXE_WarpImageMultiTransform = software.EXE_WarpImageMultiTransform
        ants_params = config.ants_params
    # Prepares data matrix for low-rank decomposition
    num_of_data = len(selection)
    Y = np.zeros((vector_length, num_of_data))
    iter_prefix = 'L' + str(level) + '_Iter'
    iter_path = os.path.join(result_dir, iter_prefix)
    current_path_iter = iter_path + str(currentIter)
    prev_path_iter = iter_path + str(currentIter - 1)
    for i in range(num_of_data):
        im_file = prev_path_iter + '_' + str(i) + '.nrrd'
        inIm = sitk.ReadImage(im_file)
        tmp = sitk.GetArrayFromImage(inIm)
        if sigma > 0:  # blurring
            log.info("Blurring: " + str(sigma))
            outIm = pyLAR.GaussianBlur(inIm, None, sigma)
            tmp = sitk.GetArrayFromImage(outIm)
        Y[:, i] = tmp.reshape(-1)
        del tmp

    # Low-rank and sparse decomposition
    low_rank, sparse, n_iter, rank, sparsity, sum_sparse = pyLAR.rpca(Y, lamda)
    lr = pyLAR.saveImagesFromDM(low_rank, current_path_iter + '_LowRank_',
                                reference_im_fn)
    sp = pyLAR.saveImagesFromDM(sparse, current_path_iter + '_Sparse_',
                                reference_im_fn)
    listOutputImages = lr + sp
    # Visualize and inspect
    try:
        import matplotlib.pyplot as plt
        fig = plt.figure(figsize=(15, 5))
        slice_prefix = 'L' + str(level) + '_' + str(currentIter)
        pyLAR.showSlice(Y, slice_prefix + ' Input', plt.cm.gray, 0,
                        reference_im_fn)
        pyLAR.showSlice(low_rank, slice_prefix + ' low rank', plt.cm.gray, 1,
                        reference_im_fn)
        pyLAR.showSlice(np.abs(sparse), slice_prefix + ' sparse', plt.cm.gray,
                        2, reference_im_fn)
        plt.savefig(current_path_iter + '.png')
        fig.clf()
        plt.close(fig)
    except ImportError:
        pass

    del low_rank, sparse, Y

    # Unbiased low-rank atlas building (ULAB)
    if not use_healthy_atlas:
        EXE_AverageImages = software.EXE_AverageImages
        # Average the low-rank images to produce the Atlas
        atlasIm = current_path_iter + '_atlas.nrrd'
        listOfImages = []
        num_of_data = len(selection)
        for i in range(num_of_data):
            lrIm = current_path_iter + '_LowRank_' + str(i) + '.nrrd'
            listOfImages.append(lrIm)
        pyLAR.AverageImages(EXE_AverageImages, listOfImages, atlasIm)

        im = sitk.ReadImage(atlasIm)
        im_array = sitk.GetArrayFromImage(im)
        z_dim, x_dim, y_dim = im_array.shape
        try:
            import matplotlib.pyplot as plt
            plt.figure()
            implot = plt.imshow(np.flipud(im_array[z_dim / 2, :, :]),
                                plt.cm.gray)
            plt.title(iter_prefix + str(currentIter) + ' atlas')
            plt.savefig(current_path_iter + '.png')
        except ImportError:
            pass
        reference_im_fn = atlasIm
    listOutputImages += [reference_im_fn]
    for i in range(num_of_data):
        # Warps the low-rank image back to the initial state (the non-greedy way)
        invWarpedlowRankIm = ''
        if currentIter == 1:
            invWarpedlowRankIm = current_path_iter + '_LowRank_' + str(
                i) + '.nrrd'
        else:
            lowRankIm = current_path_iter + '_LowRank_' + str(i) + '.nrrd'
            invWarpedlowRankIm = current_path_iter + '_InvWarped_LowRank_' + str(
                i) + '.nrrd'
            if registration_type == 'BSpline' or registration_type == 'Demons':
                previousIterDVF = prev_path_iter + '_DVF_' + str(i) + '.nrrd'
                inverseDVF = prev_path_iter + '_INV_DVF_' + str(i) + '.nrrd'
                pyLAR.genInverseDVF(EXE_InvertDeformationField,
                                    previousIterDVF, inverseDVF, True)
                pyLAR.updateInputImageWithDVF(EXE_BRAINSResample, lowRankIm,
                                              reference_im_fn, inverseDVF,
                                              invWarpedlowRankIm, True)
            if registration_type == 'ANTS':
                previousIterTransformPrefix = prev_path_iter + '_' + str(
                    i) + '_'
                pyLAR.ANTSWarpImage(EXE_WarpImageMultiTransform, lowRankIm,
                                    invWarpedlowRankIm, reference_im_fn,
                                    previousIterTransformPrefix, True, True)

        # Registers each inversely-warped low-rank image to the Atlas image
        outputIm = current_path_iter + '_Deformed_LowRank' + str(i) + '.nrrd'
        # .tfm for BSpline only
        outputTransform = current_path_iter + '_Transform_' + str(i) + '.tfm'
        outputDVF = current_path_iter + '_DVF_' + str(i) + '.nrrd'

        movingIm = invWarpedlowRankIm
        fixedIm = reference_im_fn

        initial_prefix = 'L' + str(level) + '_Iter0_'
        initialInputImage = os.path.join(result_dir,
                                         initial_prefix + str(i) + '.nrrd')
        newInputImage = current_path_iter + '_' + str(i) + '.nrrd'

        if registration_type == 'BSpline':
            pyLAR.BSplineReg_BRAINSFit(EXE_BRAINSFit,
                                       fixedIm,
                                       movingIm,
                                       outputIm,
                                       outputTransform,
                                       gridSize,
                                       maxDisp,
                                       EXECUTE=True)
            pyLAR.ConvertTransform(EXE_BSplineToDeformationField,
                                   reference_im_fn,
                                   outputTransform,
                                   outputDVF,
                                   EXECUTE=True)
            pyLAR.updateInputImageWithDVF(EXE_BRAINSResample,
                                          initialInputImage,
                                          reference_im_fn,
                                          outputDVF,
                                          newInputImage,
                                          EXECUTE=True)
        elif registration_type == 'Demons':
            pyLAR.DemonsReg(EXE_BRAINSDemonWarp,
                            fixedIm,
                            movingIm,
                            outputIm,
                            outputDVF,
                            EXECUTE=True)
            pyLAR.updateInputImageWithDVF(EXE_BRAINSResample,
                                          initialInputImage,
                                          reference_im_fn,
                                          outputDVF,
                                          newInputImage,
                                          EXECUTE=True)
        elif registration_type == 'ANTS':
            # Generates a warp(DVF) file and an affine file
            outputTransformPrefix = current_path_iter + '_' + str(i) + '_'
            # if currentIter > 1:
            # initialTransform = os.path.join(result_dir, iter_prefix + str(currentIter-1) + '_' + str(i) + '_0Warp.nii.gz')
            # else:
            pyLAR.ANTS(EXE_antsRegistration,
                       fixedIm,
                       movingIm,
                       outputTransformPrefix,
                       ants_params,
                       EXECUTE=True)
            # Generates the warped input image with the specified file name
            pyLAR.ANTSWarpImage(EXE_WarpImageMultiTransform,
                                initialInputImage,
                                newInputImage,
                                reference_im_fn,
                                outputTransformPrefix,
                                EXECUTE=True)
        else:
            raise ('Unrecognized registration type:', registration_type)
        listOutputImages += [newInputImage]
    return sparsity, sum_sparse, listOutputImages