Exemple #1
0
def view(image):
    have_imglyb = False
    try:
        import imglyb
        have_imglyb = True
    except ImportError:
        pass
    have_vtk = False
    try:
        import vtk
        have_vtk = True
    except ImportError:
        pass
    viewer = Viewer()
    if is_arraylike(image):
        arr = np.asarray(image)
        image_from_array = itk.GetImageViewFromArray(arr)
        viewer.image = image_from_array
    elif have_vtk and isinstance(image, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())
        array.shape = tuple(image.GetDimensions())[::-1]
        image_from_array = itk.GetImageViewFromArray(array)
        image_from_array.SetSpacing(image.GetSpacing())
        image_from_array.SetOrigin(image.GetOrigin())
        viewer.image = image_from_array
    elif have_imglyb and isinstance(image,
            imglyb.util.ReferenceGuardingRandomAccessibleInterval):
        image_array = imglyb.to_numpy(image)
        image_from_array = itk.GetImageViewFromArray(image_array)

    else:
        # an itk.Image
        viewer.image = itk.output(image)
    return viewer
def to_itk_image(other_image_datatype):
    if is_arraylike(other_image_datatype):
        array = np.asarray(other_image_datatype)
        case_use_view = array.flags['OWNDATA']
        if have_dask and isinstance(other_image_datatype,
                                    dask.array.core.Array):
            case_use_view = False
        if case_use_view:
            image_from_array = itk.GetImageViewFromArray(array)
        else:
            image_from_array = itk.GetImageFromArray(array)
        return image_from_array
    elif have_vtk and isinstance(other_image_datatype, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(
            other_image_datatype.GetPointData().GetScalars())
        array.shape = tuple(other_image_datatype.GetDimensions())[::-1]
        image_from_array = itk.GetImageViewFromArray(array)
        image_from_array.SetSpacing(other_image_datatype.GetSpacing())
        image_from_array.SetOrigin(other_image_datatype.GetOrigin())
        return image_from_array
    elif have_imglyb and isinstance(
            other_image_datatype,
            imglyb.util.ReferenceGuardingRandomAccessibleInterval):
        array = imglyb.to_numpy(other_image_datatype)
        image_from_array = itk.GetImageViewFromArray(array)
        return image_from_array

    return None
def view(image):
    viewer = Viewer()
    if isinstance(image, np.ndarray):
        image_from_array = itk.GetImageViewFromArray(image)
        viewer.image = image_from_array
    elif HAVE_VTK and isinstance(image, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(
            image.GetPointData().GetScalars())
        array.shape = tuple(image.GetDimensions())[::-1]
        image_from_array = itk.GetImageViewFromArray(array)
        image_from_array.SetSpacing(image.GetSpacing())
        image_from_array.SetOrigin(image.GetOrigin())
        viewer.image = image_from_array
    else:
        viewer.image = image
    return viewer
Exemple #4
0
    def itk_ws(self, NEED_WL, res_type):
        Dimension = 3

        #dist_itk = create_itk_img(self.dist.shape, Dimension, itk.US)
        #markers_itk = create_itk_img(self.dist.shape, Dimension, itk.US)
        dist_itk = itk.GetImageViewFromArray(self.dist)
        markers_itk = itk.GetImageViewFromArray(self.markers)

        #np_view = itk.GetArrayViewFromImage(dist_itk)
        #np_mar = itk.GetArrayViewFromImage(markers_itk)
        #np_view[:] = self.dist
        #np_mar[:] = self.markers

        labelImage, res = decorator(Image_3D._itk_ws,
                                    res_type)(self, NEED_WL, dist_itk,
                                              markers_itk)
        if labelImage is not None:
            self.labels[:] = itk.GetArrayViewFromImage(labelImage)
        return res
Exemple #5
0
def dataset_to_itk_image(dataset):

    import itk

    itk_image = itk.GetImageViewFromArray(dataset.active_scalars)

    if dataset.spacing is not None:
        itk_image.SetSpacing(dataset.spacing)

    return itk_image
Exemple #6
0
    def validate(self, obj, value):
        if is_arraylike(value):
            array = np.asarray(value)
            self._source_object = array
            if array.flags['OWNDATA']:
                image_from_array = itk.GetImageViewFromArray(array)
            else:
                image_from_array = itk.GetImageFromArray(array)
            return image_from_array
        elif have_vtk and isinstance(value, vtk.vtkImageData):
            from vtk.util import numpy_support as vtk_numpy_support
            array = vtk_numpy_support.vtk_to_numpy(
                value.GetPointData().GetScalars())
            array.shape = tuple(value.GetDimensions())[::-1]
            self._source_object = array
            image_from_array = itk.GetImageViewFromArray(array)
            image_from_array.SetSpacing(value.GetSpacing())
            image_from_array.SetOrigin(value.GetOrigin())
            return image_from_array
        elif have_imglyb and isinstance(
                value, imglyb.util.ReferenceGuardingRandomAccessibleInterval):
            array = imglyb.to_numpy(value)
            self._source_object = array
            image_from_array = itk.GetImageViewFromArray(array)
            return image_from_array

        try:
            # an itk.Image or a filter that produces an Image
            # return itk.output(value)
            # Working around traitlets / ipywidgets update mechanism to
            # force an update. While the result of __eq__ can indicate it is
            # the same object, the actual contents may have changed, as
            # indicated by image.GetMTime()
            value = itk.output(value)
            self._source_object = value
            grafted = value.__New_orig__()
            grafted.Graft(value)
            return grafted
        except:
            self.error(obj, value)
Exemple #7
0
import numpy as np

image = itk.imread(filename)
arr = itk.array_from_image(image)
arr.fill(1)
assert np.any(arr != itk.array_from_image(image))
arr = itk.array_from_image(image)
arr.fill(1)
assert np.any(arr != itk.array_from_image(image))
view = itk.GetArrayViewFromImage(image)
view.fill(1)
assert np.all(view == itk.array_from_image(image))
image = itk.image_from_array(arr)
image.FillBuffer(2)
assert np.any(arr != itk.array_from_image(image))
image = itk.GetImageViewFromArray(arr)
image.FillBuffer(2)
assert np.all(arr == itk.array_from_image(image))
image = itk.image_from_array(arr, is_vector=True)
assert image.GetImageDimension() == 2
image = itk.GetImageViewFromArray(arr, is_vector=True)
assert image.GetImageDimension() == 2
arr = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.uint8)
assert arr.shape[0] == 2
assert arr.shape[1] == 3
assert arr[1, 1] == 5
image = itk.image_from_array(arr)
arrKeepAxes = itk.array_from_image(image, keep_axes=True)
assert arrKeepAxes.shape[0] == 3
assert arrKeepAxes.shape[1] == 2
assert arrKeepAxes[1, 1] == 4
Exemple #8
0
def connected_components(dataset, background_value=0, progress_callback=None):
    try:
        import numpy as np
        import itk
    except Exception as exc:
        print("Could not import necessary module(s)")
        print(exc)

    if np.issubdtype(dataset.active_scalars.dtype, np.floating):
        raise Exception(
            "Connected Components works only on images with integral types.")

    # Add a try/except around the ITK portion. ITK exceptions are
    # passed up to the Python layer, so we can at least report what
    # went wrong with the script, e.g,, unsupported image type.
    try:
        # Get the ITK image. The input is assumed to have an integral type.
        # Take care of casting to an unsigned short image so we can store up
        # to 65,535 connected components (the number of connected components
        # is limited to the maximum representable number in the voxel type
        # of the input image in the ConnectedComponentsFilter).
        array = dataset.active_scalars.astype(np.uint16)
        itk_image = itk.GetImageViewFromArray(array)
        itk_image.SetSpacing(dataset.spacing)
        itk_image_type = type(itk_image)

        # ConnectedComponentImageFilter
        connected_filter = itk.ConnectedComponentImageFilter[
            itk_image_type, itk_image_type].New()
        connected_filter.SetBackgroundValue(background_value)
        connected_filter.SetInput(itk_image)

        if progress_callback is not None:

            def connected_progress_func():
                progress = connected_filter.GetProgress()
                abort = progress_callback(progress * 0.5)
                connected_filter.SetAbortGenerateData(abort)

            connected_observer = itk.PyCommand.New()
            connected_observer.SetCommandCallable(connected_progress_func)
            connected_filter.AddObserver(itk.ProgressEvent(),
                                         connected_observer)

        # Relabel filter. This will compress the label numbers to a
        # continugous range between 1 and n where n is the number of
        # labels. It will also sort the components from largest to
        # smallest, where the largest component has label 1, the
        # second largest has label 2, and so on...
        relabel_filter = itk.RelabelComponentImageFilter[itk_image_type,
                                                         itk_image_type].New()
        relabel_filter.SetInput(connected_filter.GetOutput())
        relabel_filter.SortByObjectSizeOn()

        if progress_callback is not None:

            def relabel_progress_func():
                progress = relabel_filter.GetProgress()
                abort = progress_callback(progress * 0.5 + 0.5)
                relabel_filter.SetAbortGenerateData(abort)

            relabel_observer = itk.PyCommand.New()
            relabel_observer.SetCommandCallable(relabel_progress_func)
            relabel_filter.AddObserver(itk.ProgressEvent(), relabel_observer)

        try:
            relabel_filter.Update()
        except RuntimeError:
            return

        itk_image_data = relabel_filter.GetOutput()
        label_buffer = itk.PyBuffer[itk_image_type].GetArrayFromImage(
            itk_image_data)

        # Flip the labels so that the largest component has the highest label
        # value, e.g., the labeling ordering by size goes from [1, 2, ... N] to
        # [N, N-1, N-2, ..., 1]. Note that zero is the background value, so we
        # do not want to change it.
        import numpy as np
        minimum = 1  # Minimum label is always 1, background is 0
        maximum = np.max(label_buffer)

        # Try more memory-efficient approach
        gt_zero = label_buffer > 0
        label_buffer[gt_zero] = minimum - label_buffer[gt_zero] + maximum

        # Transpose the data to Fortran indexing
        dataset.active_scalars = label_buffer.transpose([2, 1, 0])

    except Exception as exc:
        print("Problem encountered while running ConnectedComponents")
        raise exc
def main(main_args):
    print("<b>>>> Running " + os.path.basename(sys.argv[0]) + "</b>\n")
    sys.stdout.flush()

    ### Inputs
    T1 = main_args.t1
    T2 = main_args.t2
    T2_exists = True
    if (T2 == ""):
        T2_exists = False

    T1_split = os.path.splitext(os.path.basename(T1))
    if (T1_split[1] == 'gz'):
        T1_base = os.path.splitext(T1_split[0])
    else:
        T1_base = T1_split[0]

    if (T2_exists):
        T2_split = os.path.splitext(os.path.basename(T2))
        if (T2_split[1] == 'gz'):
            T2_base = os.path.splitext(T2_split[0])
        else:
            T2_base = T2_split[0]

    ### Executables
    python = main_args.python3
    ImageMath = main_args.ImageMath
    ImageStat = main_args.ImageStat
    ABC = main_args.ABC

    ### Masks
    CSFLabel = int(main_args.CSFLabel)

    ### Output path
    OUT_PATH = main_args.output

    ### Scripts
    scripts_prefix = os.path.join(OUT_PATH, "PythonScripts")

    if (main_args.registration == "true"):
        rigid_align_script = os.path.join(scripts_prefix,
                                          "rigid_align_script.py")
        print_main_info("Running " + rigid_align_script)

        OUT_RR = os.path.join(OUT_PATH, 'RigidRegistration')
        call([python, rigid_align_script, '--output', OUT_RR])
        T1_REGISTERED = os.path.join(OUT_RR, "".join([T1_base, "_stx.nrrd"]))
        if (T2_exists):
            T2_REGISTERED = os.path.join(OUT_RR,
                                         "".join([T2_base, "_stx.nrrd"]))

        print_main_info("Finished running " + rigid_align_script)

    else:
        T1_REGISTERED = T1
        if (T2_exists):
            T2_REGISTERED = T2

    OUT_SS = os.path.join(OUT_PATH, 'SkullStripping')
    if not os.path.exists(OUT_SS):
        os.makedirs(OUT_SS)

    if (main_args.skullStripping == "true"):
        make_mask_script = os.path.join(scripts_prefix, "make_mask_script.py")
        print_main_info("Running " + make_mask_script)

        BRAIN_MASK = os.path.join(OUT_SS,
                                  "".join([T1_base, "_FinalBrainMask.nrrd"]))
        if not (os.path.isfile(BRAIN_MASK)):
            if (T2_exists):
                call([
                    python, make_mask_script, '--t1', T1_REGISTERED, '--t2',
                    T2_REGISTERED, '--at_dir', '--at_list', '--output', OUT_SS
                ])
            else:
                call([
                    python, make_mask_script, '--t1', T1_REGISTERED, '--t2',
                    '', '--at_dir', '--at_list', '--output', OUT_SS
                ])
        else:
            print('Brainmask already exists')
        print_main_info("Finished running " + make_mask_script)
    else:
        BRAIN_MASK = main_args.brainMask

    print_main_info("Stripping the skull")

    T1_STRIPPED = os.path.join(OUT_SS, "".join([T1_base, "_stripped.nrrd"]))
    args = [
        ImageMath, T1_REGISTERED, '-outfile', T1_STRIPPED, '-mask', BRAIN_MASK
    ]
    call_and_print(args)

    if (T2_exists):
        T2_STRIPPED = os.path.join(OUT_SS, "".join([T2_base,
                                                    "_stripped.nrrd"]))
        args = [
            ImageMath, T2_REGISTERED, '-outfile', T2_STRIPPED, '-mask',
            BRAIN_MASK
        ]
        call_and_print(args)

    if (main_args.segmentation == "true"):
        tissue_seg_script = os.path.join(scripts_prefix,
                                         "tissue_seg_script.py")
        print_main_info("Running " + tissue_seg_script)

        OUT_TS = os.path.join(OUT_PATH, 'TissueSegAtlas')
        OUT_ABC = os.path.join(OUT_PATH, 'ABC_Segmentation')
        Segmentation = os.path.join(
            OUT_ABC, "".join([T1_base, "_stripped_labels_EMS.nrrd"]))
        print(Segmentation)
        if not (os.path.isfile(Segmentation)):
            print(Segmentation + ' doesnt exist')
            if (T2_exists):
                call([
                    python, tissue_seg_script, '--t1', T1_STRIPPED, '--t2',
                    T2_STRIPPED, '--at_dir', '--output', OUT_TS
                ])
            else:
                call([
                    python, tissue_seg_script, '--t1', T1_STRIPPED, '--t2', '',
                    '--at_dir', '--output', OUT_TS
                ])
        else:
            print('Segmentation already exists')
        print_main_info("Finished running tissue_seg_script.py")

    else:
        Segmentation = main_args.tissueSeg

    if (main_args.removeVentricles == "true"):
        vent_mask_script = os.path.join(scripts_prefix, "vent_mask_script.py")
        print_main_info("Running " + vent_mask_script)
        OUT_VR = os.path.join(OUT_PATH, 'VentricleMasking')
        call([
            python, vent_mask_script, '--t1', T1_STRIPPED,
            '--subjectTissueSeg', Segmentation, '--output', OUT_VR
        ])
        Segmentation = os.path.join(
            OUT_VR, "".join([T1_base, "_stripped_EMS_withoutVent.nrrd"]))
        print_main_info("Finished running " + vent_mask_script)

    BRAIN_MASK_base = os.path.splitext(os.path.basename(BRAIN_MASK))[0]
    Segmentation_base = os.path.splitext(os.path.basename(Segmentation))[0]

    ######### Stripping the skull from segmentation ######
    MID_TEMP00 = os.path.join(OUT_PATH, "".join([T1_base, "_MID00.nrrd"]))
    args = [
        ImageMath, Segmentation, '-outfile', MID_TEMP00, '-mask', BRAIN_MASK
    ]
    call_and_print(args)

    ######### Cutting below AC-PC line #######
    ### Coronal mask creation
    print_main_info("Cutting below AC-PC line")

    if (main_args.cerebellumMask == ""):
        ACPC_unit = main_args.ACPCunit
        if (ACPC_unit == "index"):
            ACPC_val = int(main_args.ACPCval)
        else:
            ACPC_mm = float(main_args.ACPCval)
            im = itk.imread(T1_REGISTERED)
            index_coord = im.TransformPhysicalPointToContinuousIndex(
                [ACPC_mm, 0, 0])
            ACPC_val = round(index_coord[0])

        Coronal_Mask = "coronal_mask_" + str(ACPC_val) + ".nrrd"
        if not (os.path.isfile(Coronal_Mask)):
            im = itk.imread(T1_REGISTERED)
            np_copy = itk.GetArrayFromImage(im)
            if ((ACPC_val >= np_copy.shape[0]) | (ACPC_val <= 0)):
                eprint("ACPC index out of range (" + str(ACPC_val) +
                       "), using default coronal mask (slice 70)")
                sys.stderr.flush()
                ACPC_val = 70

            print_main_info('Creating coronal mask')
            np_copy[ACPC_val - 1:np_copy.shape[0] - 1, :, :] = 1
            np_copy[0:ACPC_val - 1, :, :] = 0
            itk_np_copy = itk.GetImageViewFromArray(np_copy)
            itk_np_copy.SetOrigin(im.GetOrigin())
            itk_np_copy.SetSpacing(im.GetSpacing())
            itk_np_copy.SetDirection(im.GetDirection())
            itk.imwrite(itk_np_copy, Coronal_Mask)
            print_main_info('Coronal mask created')
        else:
            print_main_info('Loading ' + Coronal_Mask)

    else:
        Coronal_Mask = main_args.cerebellumMask

    ### Mask multiplication
    MID_TEMP01 = os.path.join(OUT_PATH,
                              "".join([Segmentation_base, "_MID01.nrrd"]))
    MID_TEMP02 = os.path.join(OUT_PATH,
                              "".join([Segmentation_base, "_MID02.nrrd"]))
    MID_TEMP03 = os.path.join(OUT_PATH,
                              "".join([Segmentation_base, "_MID03.nrrd"]))

    args = [
        ImageMath, MID_TEMP00, '-outfile', MID_TEMP01, '-mask', Coronal_Mask
    ]
    call_and_print(args)

    args = [
        ImageMath, MID_TEMP01, '-outfile', MID_TEMP02, '-extractLabel', '3'
    ]
    call_and_print(args)

    args = [ImageMath, MID_TEMP02, '-outfile', MID_TEMP03, '-conComp', '1']
    call_and_print(args)

    Erosion_Mask = BRAIN_MASK_base + '_Erosion.nrrd'
    Erosion_Mask00 = BRAIN_MASK_base + '_Erosion00.nrrd'
    Erosion_Mask01 = BRAIN_MASK_base + '_Erosion01.nrrd'
    Erosion_Mask01_inv = BRAIN_MASK_base + '_Erosion01_inv.nrrd'
    args = [ImageMath, BRAIN_MASK, '-erode', '1,1', '-outfile', Erosion_Mask00]
    call_and_print(args)

    args = [
        ImageMath, Erosion_Mask00, '-erode', '1,1', '-outfile', Erosion_Mask01
    ]
    call_and_print(args)

    for i in range(0, 14):
        args = [
            ImageMath, Erosion_Mask01, '-erode', '1,1', '-outfile',
            Erosion_Mask01
        ]
        call_and_print(args)

    args = [
        ImageMath, Erosion_Mask01, '-threshold', '0,0', '-outfile',
        Erosion_Mask01_inv
    ]
    call_and_print(args)

    FINAL_CSF_SEG = Segmentation_base + "_FINAL_Partial_CSF.nrrd"

    args = [
        ImageMath, MID_TEMP03, '-mask', Erosion_Mask01_inv, '-outfile',
        FINAL_CSF_SEG
    ]
    call_and_print(args)
    args = [
        ImageMath, FINAL_CSF_SEG, '-mask', Coronal_Mask, '-outfile',
        FINAL_CSF_SEG
    ]
    call_and_print(args)
    args = [
        ImageMath, FINAL_CSF_SEG, '-mask', MID_TEMP02, '-outfile',
        FINAL_CSF_SEG
    ]
    call_and_print(args)

    ## add script erase quad....
    Erosion = FINAL_CSF_SEG[:-5] + "_Ero.nrrd"
    Erosion_MASKING = Erosion[:-5] + "_Masking.nrrd"
    args = [ImageMath, FINAL_CSF_SEG, '-erode', '1,1', '-outfile', Erosion]
    call_and_print(args)

    args = [
        ImageMath, Erosion_Mask01, '-erode', '1,1', '-outfile', Erosion_Mask
    ]
    call_and_print(args)
    for i in range(0, 5):
        args = [
            ImageMath, Erosion_Mask, '-erode', '1,1', '-outfile', Erosion_Mask
        ]
        call_and_print(args)

    args = [
        ImageMath, Erosion, '-mask', Erosion_Mask, '-outfile', Erosion_MASKING
    ]
    call_and_print(args)

    Erosion_MASKING_conComp = Erosion_MASKING[:-5] + "_conComp.nrrd"
    args = [
        ImageMath, Erosion_MASKING, '-conComp', '1', '-outfile',
        Erosion_MASKING_conComp
    ]
    call_and_print(args)

    Dilation_comComp = Erosion_MASKING_conComp[:-5] + "_dil.nrrd"
    args = [
        ImageMath, Erosion_MASKING_conComp, '-dilate', '1,1', '-outfile',
        Dilation_comComp
    ]
    call_and_print(args)

    for k in range(0, 13):
        args = [
            ImageMath, Dilation_comComp, '-dilate', '1,1', '-outfile',
            Dilation_comComp
        ]
        call_and_print(args)

    FINAL_RESULT = FINAL_CSF_SEG[:-5] + "_QCistern.nrrd"

    args = [
        ImageMath, Dilation_comComp, '-threshold', '0,0', '-outfile',
        Dilation_comComp
    ]
    call_and_print(args)
    args = [
        ImageMath, FINAL_CSF_SEG, '-mask', Dilation_comComp, '-outfile',
        FINAL_RESULT
    ]
    call_and_print(args)

    if (main_args.computeCSFDensity == "true"):
        LH_INNER_SURF = main_args.LHInnerSurf
        RH_INNER_SURF = main_args.RHInnerSurf
        OUT_CCD = os.path.join(OUT_PATH, 'CSF_Density')
        args = [
            'computecsfdensity', '-l', LH_INNER_SURF, '-r', RH_INNER_SURF,
            '-s', Segmentation, '-c', FINAL_OUTERCSF, '-o', OUT_CCD, '-p',
            Segmentation_base
        ]
        call_and_print(args)

    print_main_info("Auto_EACSF finished")

    sys.exit(0)
def MotionCorrect(fixedImageFile,movingImageFile):

    PixelType = itk.ctype('float')
    
    fixedImage = itk.GetImageViewFromArray(fixedImageFile)
    movingImage = itk.GetImageViewFromArray(movingImageFile)
#    fixedImage = itk.imread(fixedImageFile, PixelType)
#    movingImage = itk.imread(movingImageFile, PixelType)

    Dimension = fixedImage.GetImageDimension()
    FixedImageType = itk.Image[PixelType, Dimension]
    MovingImageType = itk.Image[PixelType, Dimension]
    
    TransformType = itk.TranslationTransform[itk.D, Dimension]
    initialTransform = TransformType.New()
    
    optimizer = itk.RegularStepGradientDescentOptimizerv4.New(
            LearningRate=4,
            MinimumStepLength=0.001,
            RelaxationFactor=0.5,
            NumberOfIterations=200)
    
    metric = itk.MeanSquaresImageToImageMetricv4[
        FixedImageType, MovingImageType].New()
    
    registration = itk.ImageRegistrationMethodv4.New(FixedImage=fixedImage,
            MovingImage=movingImage,
            Metric=metric,
            Optimizer=optimizer,
            InitialTransform=initialTransform)
    
    movingInitialTransform = TransformType.New()
    initialParameters = movingInitialTransform.GetParameters()
    initialParameters[0] = 0
    initialParameters[1] = 0
    movingInitialTransform.SetParameters(initialParameters)
    registration.SetMovingInitialTransform(movingInitialTransform)
    
    identityTransform = TransformType.New()
    identityTransform.SetIdentity()
    registration.SetFixedInitialTransform(identityTransform)
    
    registration.SetNumberOfLevels(1)
    registration.SetSmoothingSigmasPerLevel([0])
    registration.SetShrinkFactorsPerLevel([1])
    
    registration.Update()
    
#    transform = registration.GetTransform()
#    finalParameters = transform.GetParameters()
#    translationAlongX = finalParameters.GetElement(0)
#    translationAlongY = finalParameters.GetElement(1)
#    
#    numberOfIterations = optimizer.GetCurrentIteration()
#    
#    bestValue = optimizer.GetValue()
    
#    print("Result = ")
#    print(" Translation X = " + str(translationAlongX))
#    print(" Translation Y = " + str(translationAlongY))
#    print(" Iterations    = " + str(numberOfIterations))
#    print(" Metric value  = " + str(bestValue))
    
    CompositeTransformType = itk.CompositeTransform[itk.D, Dimension]
    outputCompositeTransform = CompositeTransformType.New()
    outputCompositeTransform.AddTransform(movingInitialTransform)
    outputCompositeTransform.AddTransform(registration.GetModifiableTransform())
    
    resampler = itk.ResampleImageFilter.New(Input=movingImage,
            Transform=outputCompositeTransform,
            UseReferenceImage=True,
            ReferenceImage=fixedImage)
    resampler.SetDefaultPixelValue(100)
    
    OutputImageType = itk.Image[PixelType, Dimension]
    
    caster = itk.CastImageFilter[FixedImageType,
            OutputImageType].New(Input=resampler)
    
    outputImageFile = itk.GetArrayFromImage(caster)
#    writer = itk.ImageFileWriter.New(Input=caster, FileName=outputImageFile)
#    writer.SetFileName(outputImageFile)
#    writer.Update()
    return outputImageFile
Exemple #11
0
# BridgeNumPy
try:
    # Images
    import numpy
    image = itk.imread(fileName)
    arr = itk.GetArrayFromImage(image)
    arr.fill(1)
    assert numpy.any(arr != itk.GetArrayFromImage(image))
    view = itk.GetArrayViewFromImage(image)
    view.fill(1)
    assert numpy.all(view == itk.GetArrayFromImage(image))
    image = itk.GetImageFromArray(arr)
    image.FillBuffer(2)
    assert numpy.any(arr != itk.GetArrayFromImage(image))
    image = itk.GetImageViewFromArray(arr)
    image.FillBuffer(2)
    assert numpy.all(arr == itk.GetArrayFromImage(image))
    # VNL Vectors
    v1 = itk.vnl_vector.D(2)
    v1.fill(1)
    v_np = itk.GetArrayFromVnlVector(v1)
    assert v1.get(0) == v_np[0]
    v_np[0] = 0
    assert v1.get(0) != v_np[0]
    view = itk.GetArrayViewFromVnlVector(v1)
    assert v1.get(0) == view[0]
    view[0] = 0
    assert v1.get(0) == view[0]
    # VNL Matrices
    m1 = itk.vnl_matrix.D(2, 2)
Exemple #12
0
def reorient(img, new_orientation=ITK_COORDINATE_ORIENTATION_LPI, new_dir = standard_dir):

    # this function is implemented using ITK since SimpleITK has not implemented the filter "OrientImageFilter" yet
    # the ITK orientation system is from this blog post: https://itk.org/pipermail/insight-users/2017-May/054606.html
    # comparison ITK - simpleITK filters: https://itk.org/SimpleITKDoxygen/html/Filter_Coverage.html
    # see also: https://github.com/fedorov/lidc-idri-conversion/blob/master/seg/seg_converter.py

    # change image name
    img_sitk = img

    # get characteristics of simpleITK image
    size_in_sitk      = img_sitk.GetSize()
    spacing_in_sitk   = img_sitk.GetSpacing()
    origin_in_sitk    = img_sitk.GetOrigin()
    direction_in_sitk = img_sitk.GetDirection()

    # allocate ITK image (type and size)
    Dimension   = 3
    PixelType   = itk.F
    ImageTypeIn = itk.Image[PixelType, Dimension]
    img_itk = ImageTypeIn.New()
    sizeIn_itk = itk.Size[Dimension]()
    for i in range (0,Dimension):
        sizeIn_itk[i] = size_in_sitk[i]
    region = itk.ImageRegion[Dimension]()
    region.SetSize(sizeIn_itk)
    img_itk.SetRegions(region)
    img_itk.Allocate()

    # pass image from simpleITK to numpy
    img_py  = sitk.GetArrayFromImage(img_sitk)

    # pass image from numpy to ITK
    img_itk = itk.GetImageViewFromArray(img_py)

    # pass characteristics from simpleITK image to ITK image (except size, assigned in allocation)
    spacing_in_itk = itk.Vector[itk.F, Dimension]()
    for i in range (0,Dimension):
        spacing_in_itk[i] = spacing_in_sitk[i]
    img_itk.SetSpacing(spacing_in_itk)

    origin_in_itk  = itk.Point[itk.F, Dimension]()
    for i in range (0,Dimension):
        origin_in_itk[i]  = origin_in_sitk[i]
    img_itk.SetOrigin(origin_in_itk)

    # old way of assigning direction (until ITK 4.13)
#     direction_in_itk = itk.Matrix[itk.F,3,3]()
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(0,0,direction_in_sitk[0]) # r,c,value
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(0,1,direction_in_sitk[1])
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(0,2,direction_in_sitk[2])
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(1,0,direction_in_sitk[3]) # r,c,value
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(1,1,direction_in_sitk[4])
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(1,2,direction_in_sitk[5])
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(2,0,direction_in_sitk[6]) # r,c,value
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(2,1,direction_in_sitk[7])
#     direction_in_itk = img_itk.GetDirection().GetVnlMatrix().set(2,2,direction_in_sitk[8])

    direction_in_itk = np.eye(3)
    direction_in_itk[0][0] = direction_in_sitk[0]
    direction_in_itk[0][1] = direction_in_sitk[1]
    direction_in_itk[0][2] = direction_in_sitk[2]
    direction_in_itk[1][0] = direction_in_sitk[3]
    direction_in_itk[1][1] = direction_in_sitk[4]
    direction_in_itk[1][2] = direction_in_sitk[5]
    direction_in_itk[2][0] = direction_in_sitk[6]
    direction_in_itk[2][1] = direction_in_sitk[7]
    direction_in_itk[2][2] = direction_in_sitk[8]
    img_itk.SetDirection(itk.matrix_from_array(direction_in_itk))

    # make sure image is float for the orientation filter (GetImageViewFromArray sets it to unsigned char)
    ImageTypeIn_afterPy = type(img_itk)
    ImageTypeOut        = itk.Image[itk.F, 3]
    CastFilterType      = itk.CastImageFilter[ImageTypeIn_afterPy, ImageTypeOut]
    castFilter          = CastFilterType.New()
    castFilter.SetInput(img_itk)
    castFilter.Update()
    img_itk             = castFilter.GetOutput()

    # change orientation to RAI
    OrientType = itk.OrientImageFilter[ImageTypeOut,ImageTypeOut]
    filter     = OrientType.New()
    filter.UseImageDirectionOn()
    filter.SetDesiredCoordinateOrientation(new_orientation)
    filter.SetInput(img_itk)
    filter.Update()
    img_itk    = filter.GetOutput()

    # get characteristics of ITK image
    spacing_out_itk   = img_itk.GetSpacing()
    origin_out_itk    = img_itk.GetOrigin()

    # pass image from itk to numpy
    img_py = itk.GetArrayViewFromImage(img_itk)

    # pass image from numpy to simpleitk
    img = sitk.GetImageFromArray(img_py)

    # pass characteristics from ITK image to simpleITK image (except size, implicitely passed)
    spacing = []
    for i in range (0, Dimension):
        spacing.append(spacing_out_itk[i])
    img.SetSpacing(spacing)

    origin = []
    for i in range (0, Dimension):
        origin.append(origin_out_itk[i])
        
    img.SetOrigin(origin)
    img.SetDirection(new_dir)

    return img
Exemple #13
0
print("Processing Pixel...")

z = 0
y = 0
x = 0
for z in range(OutputArray.shape[0]):
    for y in range(OutputArray.shape[1]):
        for x in range(OutputArray.shape[2]):
            if (OutputArray[z][y][x] != 0):
                if (MaskArray[z][y][x] == 0):
                    OutputArray[z][y][x] = 0
                else:
                    OutputArray[z][y][x] = 1

final = itk.GetImageViewFromArray(OutputArray)
final.SetOrigin(reader4mm.GetOutput().GetOrigin())
final.SetSpacing(reader4mm.GetOutput().GetSpacing())
final.SetDirection(reader4mm.GetOutput().GetDirection())

WriterType = itk.ImageFileWriter[LabeledImageType]
writer = WriterType.New()
writer.SetFileName(path + "/mask.mha")
writer.SetInput(final)
try:
    writer.Update()
except Exception as error:
    print("EXIT FAILURE")
    print(error)
    sys.exit(1)
Exemple #14
0
# Read input image
itk_image = itk.imread(input_filename)

#run filters on itkImage

#view only of itkImage, data is not copied
np_view = itk.GetArrayViewFromImage(itk_image)

#copy of itkImage, data is copied
np_copy = itk.GetArrayFromImage(itk_image)

#do numpy stuff

#convert back to itk, view only, data is not copied
itk_np_view = itk.GetImageViewFromArray(np_copy)

#convert back to itk, data is not copied
itk_np_copy = itk.GetImageFromArray(np_copy)

# Save result
itk.imwrite(itk_np_view, output_filename)

# Vnl matrix[View] from array
arr = np.zeros([3, 3], np.uint8)
matrix_view = itk.GetVnlMatrixViewFromArray(arr)
matrix = itk.GetVnlMatrixFromArray(arr)

# Array[View] from Vnl matrix
arr_view = itk.GetArrayViewFromVnlMatrix(matrix)
arr = itk.GetArrayFromVnlMatrix(matrix)
Exemple #15
0
def main(main_args):
    print(os.path.basename(sys.argv[0])+"\n")
    ### Inputs
    T1 = main_args.t1
    T2 = main_args.t2
    BRAIN_MASK = main_args.brainMask
    T2_exists = True
    if (T2 == ""):
        T2_exists = False

    T1_base = os.path.splitext(os.path.splitext(os.path.basename(T1))[0])[0]

    if (T2_exists):
        T2_base = os.path.splitext(os.path.splitext(T2)[0])[0]

    SEGMENTATION = main_args.tissueSeg

    ### Executables
    python = main_args.python3
    ImageMath = main_args.ImageMath
    ImageStat = main_args.ImageStat
    ABC = main_args.ABC

    ### Masks
    CSFLabel = int(main_args.CSFLabel)

    ### Output path
    OUT_PATH = main_args.output

    ### Scripts
    scripts_prefix = os.path.join(OUT_PATH, "PythonScripts")


    current_suffix = ""

    registration_suffix = "_stx"
    if (main_args.registration):
        rigid_align_script = os.path.join(scripts_prefix, "rigid_align.py")
        print("Running " + rigid_align_script)
        call_and_print([python, rigid_align_script])

    if (main_args.skullStripping):
        make_mask_script = os.path.join(scripts_prefix, "make_mask.py")
        print("Running " + make_mask_script)
        call_and_print([python, make_mask_script])

    skull_strip_script = os.path.join(scripts_prefix, "skull_strip.py")
    print("Running " + skull_strip_script)
    call_and_print([python, skull_strip_script])

    if (main_args.segmentation):
        tissue_seg_script = os.path.join(scripts_prefix, "tissue_seg.py")
        print("Running " + tissue_seg_script)
        call_and_print([python, tissue_seg_script])
        abc_seg = find_file(".*_labels_EMS.nrrd", os.path.join(OUT_PATH, "ABC_Segmentation"))
        if(abc_seg is not None):
            SEGMENTATION = abc_seg


    if (main_args.removeVentricles):
        vent_mask_script = os.path.join(scripts_prefix, "vent_mask.py")
        print("Running " + vent_mask_script)
        call_and_print([python, vent_mask_script])
        
        ventricleMasking_seg = find_file(".*_withoutVent.nrrd", os.path.join(OUT_PATH, "VentricleMasking"))
        if(ventricleMasking_seg is not None):
            SEGMENTATION = ventricleMasking_seg
        print("Finished running "+ vent_mask_script)

    OUT_FM = os.path.join(OUT_PATH, 'FinalMasking')
    if not os.path.exists(OUT_FM):
        os.makedirs(OUT_FM)

    if(not os.path.exists(BRAIN_MASK)):
        BRAIN_MASK = find_file(".*_FinalBrainMask.nrrd", os.path.join(OUT_PATH, "SkullStripping"))
        # BRAIN_MASK = os.path.join(OUT_PATH, 'FinalMasking', os.path.splitext(os.path.basename(SEGMENTATION))[0] + "_brainMask.nrrd")
        # args=[ImageMath, SEGMENTATION, '-outfile', BRAIN_MASK, '-threshold', "1,999999"]
        # call_and_print(args)

    BRAIN_MASK_base = os.path.splitext(os.path.basename(BRAIN_MASK))[0]
    Segmentation_base = os.path.splitext(os.path.basename(SEGMENTATION))[0]

    ######### Stripping the skull from segmentation ######
    MID_TEMP00 = os.path.join(OUT_FM, "".join([T1_base,"_MID00.nrrd"]))
    args=[ImageMath, SEGMENTATION, '-outfile', MID_TEMP00, '-mask', BRAIN_MASK]
    call_and_print(args)

    ######### Cutting below AC-PC line #######
    ### Coronal mask creation
    print("Cutting below AC-PC line")

    T1_REGISTERED = T1
    if main_args.registration:
        T1_REGISTERED = os.path.join(OUT_PATH, "RigidRegistration", T1_base + "_stx.nrrd")
        T1_base = os.path.splitext(os.path.splitext(os.path.basename(T1_REGISTERED))[0])[0]

    
    T1_STRIPPED = find_file(T1_base + "_stripped.nrrd", os.path.join(OUT_PATH, "SkullStripping"))
    if(T1_STRIPPED is not None):
        T1_REGISTERED = T1_STRIPPED
        T1_base = os.path.splitext(os.path.splitext(os.path.basename(T1_REGISTERED))[0])[0]

    if (main_args.cerebellumMask == ""):
        ACPC_unit=main_args.ACPCunit
        if(ACPC_unit == "index"):
            ACPC_val=int(main_args.ACPCval)
        else:
            ACPC_mm=float(main_args.ACPCval)
            im=itk.imread(T1_REGISTERED)
            index_coord=im.TransformPhysicalPointToContinuousIndex([ACPC_mm,0,0])
            ACPC_val=round(index_coord[0])

        Coronal_Mask = os.path.join(OUT_FM,"coronal_mask_"+str(ACPC_val)+".nrrd")
        if not (os.path.isfile(Coronal_Mask)):
            im=itk.imread(T1_REGISTERED)
            np_copy=itk.GetArrayFromImage(im)
            if ((ACPC_val >= np_copy.shape[0]) | (ACPC_val <= 0)):
                eprint("ACPC index out of range ("+str(ACPC_val)+"), using default coronal mask (slice 70)")
                sys.stderr.flush()
                ACPC_val = 70;

            print('Creating coronal mask')
            np_copy[ACPC_val-1:np_copy.shape[0]-1,:,:]=1
            np_copy[0:ACPC_val-1,:,:]=0
            itk_np_copy=itk.GetImageViewFromArray(np_copy)
            itk_np_copy.SetOrigin(im.GetOrigin())
            itk_np_copy.SetSpacing(im.GetSpacing())
            itk_np_copy.SetDirection(im.GetDirection())
            itk.imwrite(itk_np_copy,Coronal_Mask)
            print('Coronal mask created')
        else:
            print('Loading ' + Coronal_Mask)

    else:
        Coronal_Mask = main_args.cerebellumMask

    ### Mask multiplication
    MID_TEMP01 = os.path.join(OUT_FM,"".join([Segmentation_base,"_MID01.nrrd"]))
    MID_TEMP02 = os.path.join(OUT_FM,"".join([Segmentation_base,"_MID02.nrrd"]))
    MID_TEMP03 = os.path.join(OUT_FM,"".join([Segmentation_base,"_MID03.nrrd"]))

    args=[ImageMath, MID_TEMP00, '-outfile', MID_TEMP01, '-mask', Coronal_Mask]
    call_and_print(args)

    args=[ImageMath, MID_TEMP01, '-outfile', MID_TEMP02, '-extractLabel', '3']
    call_and_print(args)

    args=[ImageMath, MID_TEMP02, '-outfile', MID_TEMP03, '-conComp','1']
    call_and_print(args)

    Erosion_Mask = os.path.join(OUT_FM,BRAIN_MASK_base + '_Erosion.nrrd')
    Erosion_Mask00 = os.path.join(OUT_FM,BRAIN_MASK_base + '_Erosion00.nrrd')
    Erosion_Mask01 = os.path.join(OUT_FM,BRAIN_MASK_base + '_Erosion01.nrrd')
    Erosion_Mask01_inv = os.path.join(OUT_FM,BRAIN_MASK_base + '_Erosion01_inv.nrrd')
    args = [ImageMath, BRAIN_MASK, '-erode', '1,1', '-outfile', Erosion_Mask00]
    call_and_print(args)

    args = [ImageMath, Erosion_Mask00, '-erode', '1,1', '-outfile', Erosion_Mask01]
    call_and_print(args)

    for i in range(0,14):
        args = [ImageMath, Erosion_Mask01,  '-erode', '1,1', '-outfile', Erosion_Mask01]
        call_and_print(args)

    args = [ImageMath, Erosion_Mask01, '-threshold', '0,0', '-outfile', Erosion_Mask01_inv]
    call_and_print(args)


    FINAL_CSF_SEG = os.path.join(OUT_FM, Segmentation_base + "_Partial_CSF.nrrd")

    args = [ImageMath, MID_TEMP03, '-mask', Erosion_Mask01_inv, '-outfile', FINAL_CSF_SEG]
    call_and_print(args)

    ## add script erase quad....
    Erosion = os.path.join(OUT_FM, Segmentation_base + "Partial_Ero.nrrd")
    Erosion_MASKING = os.path.join(OUT_FM,Segmentation_base + "Partial_Masking.nrrd")
    args = [ImageMath, FINAL_CSF_SEG,  '-erode', '1,1', '-outfile', Erosion]
    call_and_print(args)

    args = [ImageMath, Erosion_Mask01,  '-erode', '1,1', '-outfile', Erosion_Mask]
    call_and_print(args)
    for i in range(0,5):
        args = [ImageMath, Erosion_Mask,  '-erode', '1,1', '-outfile', Erosion_Mask]
        call_and_print(args)

    args = [ImageMath, Erosion, '-mask', Erosion_Mask, '-outfile', Erosion_MASKING]
    call_and_print(args)


    Erosion_MASKING_conComp = os.path.join(OUT_FM, Segmentation_base + "Partial_conComp.nrrd")
    args = [ImageMath, Erosion_MASKING, '-conComp', '1', '-outfile', Erosion_MASKING_conComp]
    call_and_print(args)


    Dilation_comComp = os.path.join(OUT_FM, Segmentation_base + "Partial_conComp_dil.nrrd")
    args = [ImageMath, Erosion_MASKING_conComp,  '-dilate', '1,1', '-outfile', Dilation_comComp]
    call_and_print(args)

    for k in range(0,13):
        args = [ImageMath, Dilation_comComp,  '-dilate', '1,1', '-outfile', Dilation_comComp]
        call_and_print(args)

    FINAL_RESULT = os.path.join(OUT_PATH, Segmentation_base + "_FINAL_QCistern.nrrd")

    args = [ImageMath, Dilation_comComp, '-threshold', '0,0', '-outfile', Dilation_comComp]
    call_and_print(args)
    args = [ImageMath, FINAL_CSF_SEG, '-mask', Dilation_comComp, '-outfile', FINAL_RESULT]
    call_and_print(args)

    args = [ImageStat, FINAL_RESULT, '-label', FINAL_RESULT, '-volumeSummary']
    call_and_print(args)

    if (main_args.computeCSFDensity == "true"):
        LH_INNER_SURF = main_args.LHInnerSurf
        RH_INNER_SURF = main_args.RHInnerSurf
        OUT_CCD=os.path.join(OUT_PATH,'CSF_Density')
        args = ['computecsfdensity', '-l', LH_INNER_SURF, '-r', RH_INNER_SURF, '-s', Segmentation, '-c', FINAL_OUTERCSF, '-o', OUT_CCD, '-p', Segmentation_base]
        call_and_print(args)

    print("Auto_EACSF finished")

    sys.exit(0);
Exemple #16
0
def main(main_args):
    print("<b>>>> Running "+os.path.basename(sys.argv[0])+"</b>\n")
    sys.stdout.flush()

    ### Inputs
    T1 = main_args.t1
    T2 = main_args.t2
    T2_exists=True
    if (T2 == ""):
        T2_exists=False

    T1_split=os.path.splitext(os.path.basename(T1))
    if (T1_split[1] == 'gz'):
        T1_base=os.path.splitext(T1_split[0])
    else:
        T1_base=T1_split[0]

    if (T2_exists):
        T2_split=os.path.splitext(os.path.basename(T2))
        if (T2_split[1] == 'gz'):
            T2_base=os.path.splitext(T2_split[0])
        else:
            T2_base=T2_split[0]

    ### Data directory
    DATADIR = main_args.dataDir

    ### Coronal mask settings
    ACPC_unit=main_args.ACPCunit
    if(ACPC_unit == "index"):
        ACPC_val=int(main_args.ACPCval)
    else:
        ACPC_mm=float(main_args.ACPCval)
        im=itk.imread(T1)
        index_coord=im.TransformPhysicalPointToContinuousIndex([ACPC_mm,0,0])
        ACPC_val=round(index_coord[0])

    if(ACPC_val == 70):
        Coronal_Mask = os.path.join(DATADIR,"masks","coronal_mask_70.nrrd")
    else:
        im=itk.imread(T1)
        np_copy=itk.GetArrayFromImage(im)
        if ((ACPC_val >= np_copy.shape[0]) | (ACPC_val <= 0)):
            eprint("ACPC index out of range ("+str(ACPC_val)+"), using default coronal mask (slice 70)")
            sys.stderr.flush()
            Coronal_Mask = os.path.join(DATADIR,"masks","coronal_mask_70.nrrd")
        else:
            np_copy[ACPC_val-1:np_copy.shape[0]-1,:,:]=np.iinfo(np_copy.dtype).max
            np_copy[0:ACPC_val-1,:,:]=0
            itk_np_copy=itk.GetImageViewFromArray(np_copy)
            itk_outfile_name="coronal_mask_"+str(ACPC_val)
            itk.imwrite(itk_np_copy,itk_outfile_name)
            Coronal_Mask = itk_outfile_name

    ### Executables
    python=main_args.python3
    ImageMath=main_args.ImageMath
    ImageStat=main_args.ImageStat
    ABC=main_args.ABC

    ### Masks
    BRAIN_MASK = main_args.brainMask

    if (main_args.useDfCerMask == "true"):
        PRE_CEREBELLUM_MASK = "/work/alemaout/sources/Projects/auto_EACSF-Project/auto_EACSF/data/CVS_MASK_RAI_Dilate.nrrd"
    else:
        PRE_CEREBELLUM_MASK = main_args.cerebellumMask
    Segmentation = main_args.tissueSeg
    if (Segmentation == "") :
        CSFLabel=3
    else:
        CSFLabel=int(main_args.CSFLabel)

    ### Output path
    OUT_PATH = main_args.output

    ### Scripts
    scripts_prefix="PythonScripts/"

    if (main_args.performReg == "true"):
       rigid_align="rigid_align_script.py"
       print_main_info("Running "+rigid_align)
       sys.stdout.flush()
       OUT_RR=os.path.join(OUT_PATH,'RigidRegistration')
       call([python, scripts_prefix+rigid_align,'--output',OUT_RR])
       T1 = os.path.join(OUT_RR, "".join([T1_base,"_stx.nrrd"]))
       if (T2_exists):
           T2=os.path.join(OUT_RR, "".join([T2_base,"_stx.nrrd"]))

       print_main_info("Finished running "+rigid_align)
       sys.stdout.flush()

    if (main_args.performSS == "true"):
       make_mask="make_mask_script.py"
       print_main_info("Running "+make_mask)
       sys.stdout.flush()
       OUT_SS=os.path.join(OUT_PATH,'SkullStripping')
       call([python, scripts_prefix+make_mask, '--t1', T1, '--t2', T2, '--at_dir', '--at_list', '--output',OUT_SS])
       BRAIN_MASK = os.path.join(OUT_SS, "".join([T1_base,"_FinalBrainMask.nrrd"]))
       print_main_info("Finished running "+make_mask)
       sys.stdout.flush()


    if (main_args.performTSeg == "true"):
       tissue_seg="tissue_seg_script.py"
       print_main_info("Running tissue_seg_script.py")
       sys.stdout.flush()
       OUT_TS=os.path.join(OUT_PATH,'TissueSegAtlas')
       OUT_ABC=os.path.join(OUT_PATH,'ABC_Segmentation')
       call([python, scripts_prefix+tissue_seg, '--t1', T1, '--t2', T2,'--at_dir', '--output', OUT_TS])
       print_main_info("Finished running tissue_seg_script.py")
       Segmentation = os.path.join(OUT_ABC, "".join([T1_base,"_labels_EMS.nrrd"]))
       sys.stdout.flush()

    vent_mask="vent_mask_script.py"
    print_main_info("Running "+vent_mask)
    sys.stdout.flush()
    OUT_VR=os.path.join(OUT_PATH,'VentricleMasking')
    call([python, scripts_prefix+vent_mask, '--t1', T1, '--tissueSeg', Segmentation, '--atlas', '--output',OUT_VR])
    Segmentation = os.path.join(OUT_VR, "".join([T1_base,"_EMS_withoutVent.nrrd"]))
    print_main_info("Finished running "+vent_mask)
    sys.stdout.flush()

    BRAIN_MASK_dir = os.path.dirname(BRAIN_MASK)
    BRAIN_MASK_base = os.path.splitext(os.path.basename(BRAIN_MASK))[0]
    PRE_CEREBELLUM_MASK_dir = os.path.dirname(PRE_CEREBELLUM_MASK)
    PRE_CEREBELLUM_MASK_base = os.path.splitext(os.path.basename(PRE_CEREBELLUM_MASK))[0]
    Segmentation_dir = os.path.dirname(Segmentation)
    Segmentation_base = os.path.splitext(os.path.basename(Segmentation))[0]

    ######### Stripping the skull ######
    print_main_info("Stripping the skull")
    MID_TEMP00 = os.path.join(OUT_PATH, "".join([T1_base,"_MID00.nrrd"]))
    args=[ImageMath, Segmentation, '-outfile', MID_TEMP00, '-mul', BRAIN_MASK]
    call_and_print(args)

    ######### Cutting below AC-PC line #######
    print_main_info("Cutting below AC-PC line")
    MID_TEMP01 = os.path.join(OUT_PATH,"".join([Segmentation_base,"_MID01.nrrd"]))
    MID_TEMP02 = os.path.join(OUT_PATH,"".join([Segmentation_base,"_MID02.nrrd"]))
    MID_TEMP03 = os.path.join(OUT_PATH,"".join([Segmentation_base,"_MID03.nrrd"]))

    args=[ImageMath, MID_TEMP00, '-outfile', MID_TEMP01, '-mul', Coronal_Mask]
    call_and_print(args)

    args=[ImageMath, MID_TEMP01, '-outfile', MID_TEMP02, '-extractLabel', '3']
    call_and_print(args)

    args=[ImageMath, MID_TEMP02, '-outfile', MID_TEMP02, '-sub', PRE_CEREBELLUM_MASK]
    call_and_print(args)

    args=[ImageMath, MID_TEMP02, '-outfile', MID_TEMP02, '-threshold', '1,1']
    call_and_print(args)

    args=[ImageMath, MID_TEMP02, '-outfile', MID_TEMP03, '-conComp','1']
    call_and_print(args)

    ######### Make thin mask for preserving outter 2nd or 3rd fracrtion csf ##########
    print_main_info("Make thin mask for preserving outter 2nd or 3rd fracrtion csf")
    BRAIN_MASK = os.path.join(OUT_PATH,'Brain_Mask.nrrd')
    BRAIN_MASK_ERODE = os.path.join(OUT_PATH,'Brain_Mask_Erode.nrrd')
    THIN_MASK = os.path.join(OUT_PATH,'Brain_Thin_Mask.nrrd')

    args=[ImageMath, Segmentation, '-threshold', '1,4', '-outfile', BRAIN_MASK]
    call_and_print(args)

    args=[ImageMath, BRAIN_MASK, '-erode', '6,1', '-outfile', BRAIN_MASK_ERODE]
    call_and_print(args)

    args=[ImageMath, BRAIN_MASK, '-sub', BRAIN_MASK_ERODE, '-outfile', THIN_MASK]
    call_and_print(args)

    args=[ImageMath, THIN_MASK, '-mul', Coronal_Mask, '-outfile', THIN_MASK]
    call_and_print(args)

    ########## Find outer CSF in thin mask and added this csf to extra CSF #############
    print_main_info("Find outer CSF in thin mask and added this csf to extra CSF")
    PRESERVED_OUTERCSF = os.path.join(OUT_PATH,'Preserved_OuterCSF.nrrd')
    FINAL_OUTERCSF = os.path.join(OUT_PATH, "".join([Segmentation_base,"_extCSF.nrrd"]))
    FINAL_OUTERCSF_dir = os.path.dirname(FINAL_OUTERCSF)
    FINAL_OUTERCSF_base = os.path.splitext(os.path.basename(FINAL_OUTERCSF))[0]

    args=[ImageMath, MID_TEMP02, '-outfile', PRESERVED_OUTERCSF, '-mul', THIN_MASK]
    call_and_print(args)

    args=[ImageMath, MID_TEMP03, '-outfile', FINAL_OUTERCSF, '-add', PRESERVED_OUTERCSF]
    call_and_print(args)

    args=[ImageMath, FINAL_OUTERCSF, '-outfile', FINAL_OUTERCSF, '-threshold', '1,2']
    call_and_print(args)

    args=[ImageStat, FINAL_OUTERCSF, '-label', FINAL_OUTERCSF]
    call_and_print(args)

    print_main_info("Auto_EACSF finished")

    sys.exit(0);