Exemple #1
0
def post_process(img: structure.BrainImage, segmentation: sitk.Image,
                 probability: sitk.Image, **kwargs) -> sitk.Image:
    """Post-processes a segmentation.

    Args:
        img (structure.BrainImage): The image.
        segmentation (sitk.Image): The segmentation (label image).
        probability (sitk.Image): The probabilities images (a vector image).

    Returns:
        sitk.Image: The post-processed image.
    """

    print('-' * 10, 'Post-processing', img.id_)

    # construct pipeline
    pipeline = fltr.FilterPipeline()
    if kwargs.get('crf_post', False):
        pipeline.add_filter(fltr_postp.DenseCRF())
        pipeline.set_param(
            fltr_postp.DenseCRFParams(img.images[structure.BrainImageTypes.T1],
                                      img.images[structure.BrainImageTypes.T2],
                                      probability), 0)

    return pipeline.execute(segmentation)
Exemple #2
0
def post_process(img: structure.BrainImage, segmentation: sitk.Image, probability: sitk.Image,
                 **kwargs) -> sitk.Image:
    """Post-processes a segmentation.

    Args:
        img (structure.BrainImage): The image.
        segmentation (sitk.Image): The segmentation (label image).
        probability (sitk.Image): The probabilities images (a vector image).

    Returns:
        sitk.Image: The post-processed image.
    """

    print('-' * 10, 'Post-processing', img.id_)

    # construct pipeline
    pipeline = fltr.FilterPipeline()
    if kwargs.get('simple_post', False):
        pipeline.add_filter(fltr_postp.ImagePostProcessing())
        pipeline.set_param(fltr_postp.ImagePostProcessingParam(probability,
                                                               variance=kwargs.get('variance', 1.0),
                                                               preserve_background=kwargs.get('preserve_background', False)), len(pipeline.filters) - 1)
    if kwargs.get('crf_post', False):
        pipeline.add_filter(fltr_postp.DenseCRF())
        pipeline.set_param(fltr_postp.DenseCRFParams(img.images[structure.BrainImageTypes.T1w],
                                                     img.images[structure.BrainImageTypes.T2w],
                                                     probability), len(pipeline.filters) - 1)

    return pipeline.execute(segmentation)
Exemple #3
0
def main(data_dir: str):
    # initialize filter pipeline with filters
    filters = [
        prep.GradientAnisotropicDiffusion(time_step=0.0625),
        prep.HistogramMatcher()
    ]
    histogram_matching_filter_idx = 1  # we need the index later to update the HistogramMatcher's parameters

    pipeline = flt.FilterPipeline(filters)

    # get subjects to evaluate
    subject_dirs = [
        subject for subject in glob.glob(os.path.join(data_dir, '*'))
        if os.path.isdir(subject)
        and os.path.basename(subject).startswith('Subject')
    ]

    for subject_dir in subject_dirs:
        subject_id = os.path.basename(subject_dir)
        print(f'Filtering {subject_id}...')

        # load the T1- and T2-weighted MR images
        t1_image = sitk.ReadImage(
            os.path.join(subject_dir, f'{subject_id}_T1.mha'))
        t2_image = sitk.ReadImage(
            os.path.join(subject_dir, f'{subject_id}_T2.mha'))

        # set the T2-weighted MR image as reference for the histogram matching
        pipeline.set_param(prep.HistogramMatcherParams(t2_image),
                           histogram_matching_filter_idx)

        # execute filtering pipeline on the T1-weighted image
        filtered_t1_image = pipeline.execute(t1_image)

        # plot filtering result
        slice_no_for_plot = t1_image.GetSize()[2] // 2
        fig, axs = plt.subplots(1, 2)
        axs[0].imshow(sitk.GetArrayFromImage(t1_image[:, :,
                                                      slice_no_for_plot]),
                      cmap='gray')
        axs[0].set_title('Original image')
        axs[1].imshow(sitk.GetArrayFromImage(
            filtered_t1_image[:, :, slice_no_for_plot]),
                      cmap='gray')
        axs[1].set_title('Filtered image')
        fig.suptitle(f'{subject_id}', fontsize=16)
        plt.show()
Exemple #4
0
def pre_process(id_: str, paths: dict, **kwargs) -> structure.BrainImage:
    """Loads and processes an image.

    The processing includes:

    - Registration
    - Pre-processing
    - Feature extraction

    Args:
        id_ (str): An image identifier.
        paths (dict): A dict, where the keys are an image identifier of type structure.BrainImageTypes
            and the values are paths to the images.

    Returns:
        (structure.BrainImage):
    """

    print('-' * 10, 'Processing', id_)

    # load image
    path = paths.pop(
        id_, '')  # the value with key id_ is the root directory of the image
    img = {img_key: sitk.ReadImage(path) for img_key, path in paths.items()}
    img = structure.BrainImage(id_, path, img)

    # construct T1 pipeline
    pipeline_t1 = fltr.FilterPipeline()
    if kwargs.get('zscore_pre', False):
        pipeline_t1.add_filter(fltr_prep.NormalizeZScore())
    if kwargs.get('registration_pre', False):
        pipeline_t1.add_filter(fltr_reg.MultiModalRegistration())
        pipeline_t1.set_param(fltr_reg.MultiModalRegistrationParams(atlas_t1),
                              1)

    # execute pipeline on T1 image
    img.images[structure.BrainImageTypes.T1] = pipeline_t1.execute(
        img.images[structure.BrainImageTypes.T1])

    # construct T2 pipeline
    pipeline_t2 = fltr.FilterPipeline()
    if kwargs.get('zscore_pre', False):
        pipeline_t2.add_filter(fltr_prep.NormalizeZScore())

    # execute pipeline on T2 image
    img.images[structure.BrainImageTypes.T2] = pipeline_t2.execute(
        img.images[structure.BrainImageTypes.T2])

    if kwargs.get('registration_pre', False):
        # get transformation
        transform = pipeline_t1.filters[1].transform

        # apply transformation of T1 image registration to T2 image
        image_t2 = img.images[structure.BrainImageTypes.T2]
        image_t2 = sitk.Resample(image_t2, atlas_t1, transform,
                                 sitk.sitkLinear, 0.0,
                                 image_t2.GetPixelIDValue())
        img.images[structure.BrainImageTypes.T2] = image_t2

        # apply transformation of T1 image registration to ground truth
        image_ground_truth = img.images[structure.BrainImageTypes.GroundTruth]
        image_ground_truth = sitk.Resample(
            image_ground_truth, atlas_t1, transform, sitk.sitkNearestNeighbor,
            0, image_ground_truth.GetPixelIDValue())
        img.images[structure.BrainImageTypes.GroundTruth] = image_ground_truth

        # update image properties to atlas image properties after registration
        img.image_properties = conversion.ImageProperties(atlas_t1)

    # extract the features
    feature_extractor = FeatureExtractor(img, **kwargs)
    img = feature_extractor.execute()

    img.feature_images = {}

    return img
Exemple #5
0
def pre_process(id_: str, paths: dict, **kwargs) -> structure.BrainImage:
    """Loads and processes an image.

    The processing includes:

    - Registration
    - Pre-processing
    - Feature extraction

    Args:
        id_ (str): An image identifier.
        paths (dict): A dict, where the keys are an image identifier of type structure.BrainImageTypes
            and the values are paths to the images.

    Returns:
        (structure.BrainImage):
    """

    print('-' * 10, 'Processing', id_)

    # load image
    path = paths.pop(
        id_, '')  # the value with key id_ is the root directory of the image
    path_to_transform = paths.pop(
        structure.BrainImageTypes.RegistrationTransform, '')
    img = {img_key: sitk.ReadImage(path) for img_key, path in paths.items()}
    transform = sitk.ReadTransform(path_to_transform)
    img = structure.BrainImage(id_, path, img, transform)

    # construct pipeline for brain mask registration
    # we need to perform this before the T1w and T2w pipeline because the registered mask is used for skull-stripping
    pipeline_brain_mask = fltr.FilterPipeline()
    if kwargs.get('registration_pre', False):
        pipeline_brain_mask.add_filter(fltr_prep.ImageRegistration())
        pipeline_brain_mask.set_param(
            fltr_prep.ImageRegistrationParameters(atlas_t1, img.transformation,
                                                  True),
            len(pipeline_brain_mask.filters) - 1)

    # execute pipeline on the brain mask image
    img.images[
        structure.BrainImageTypes.BrainMask] = pipeline_brain_mask.execute(
            img.images[structure.BrainImageTypes.BrainMask])

    # construct pipeline for T1w image pre-processing
    pipeline_t1 = fltr.FilterPipeline()
    if kwargs.get('registration_pre', False):
        pipeline_t1.add_filter(fltr_prep.ImageRegistration())
        pipeline_t1.set_param(
            fltr_prep.ImageRegistrationParameters(atlas_t1,
                                                  img.transformation),
            len(pipeline_t1.filters) - 1)
    if kwargs.get('skullstrip_pre', False):
        pipeline_t1.add_filter(fltr_prep.SkullStripping())
        pipeline_t1.set_param(
            fltr_prep.SkullStrippingParameters(
                img.images[structure.BrainImageTypes.BrainMask]),
            len(pipeline_t1.filters) - 1)
    if kwargs.get('normalization_pre', False):
        pipeline_t1.add_filter(fltr_prep.ImageNormalization())

    # execute pipeline on the T1w image
    img.images[structure.BrainImageTypes.T1w] = pipeline_t1.execute(
        img.images[structure.BrainImageTypes.T1w])

    # construct pipeline for T2w image pre-processing
    pipeline_t2 = fltr.FilterPipeline()
    if kwargs.get('registration_pre', False):
        pipeline_t2.add_filter(fltr_prep.ImageRegistration())
        pipeline_t2.set_param(
            fltr_prep.ImageRegistrationParameters(atlas_t2,
                                                  img.transformation),
            len(pipeline_t2.filters) - 1)
    if kwargs.get('skullstrip_pre', False):
        pipeline_t2.add_filter(fltr_prep.SkullStripping())
        pipeline_t2.set_param(
            fltr_prep.SkullStrippingParameters(
                img.images[structure.BrainImageTypes.BrainMask]),
            len(pipeline_t2.filters) - 1)
    if kwargs.get('normalization_pre', False):
        pipeline_t2.add_filter(fltr_prep.ImageNormalization())

    # execute pipeline on the T2w image
    img.images[structure.BrainImageTypes.T2w] = pipeline_t2.execute(
        img.images[structure.BrainImageTypes.T2w])

    # construct pipeline for ground truth image pre-processing
    pipeline_gt = fltr.FilterPipeline()
    if kwargs.get('registration_pre', False):
        pipeline_gt.add_filter(fltr_prep.ImageRegistration())
        pipeline_gt.set_param(
            fltr_prep.ImageRegistrationParameters(atlas_t1, img.transformation,
                                                  True),
            len(pipeline_gt.filters) - 1)

    # execute pipeline on the ground truth image
    img.images[structure.BrainImageTypes.GroundTruth] = pipeline_gt.execute(
        img.images[structure.BrainImageTypes.GroundTruth])

    # update image properties to atlas image properties after registration
    img.image_properties = conversion.ImageProperties(
        img.images[structure.BrainImageTypes.T1w])

    # extract the features
    feature_extractor = FeatureExtractor(img, **kwargs)

    img = feature_extractor.execute()

    img.feature_images = {
    }  # we free up memory because we only need the img.feature_matrix
    # for training of the classifier

    return img