def watershed(operator, step_pct, input_image, level): import itk from tomviz import itkutils dimension = input_image.GetImageDimension() watershed_input_type = itk.Image[itk.F, dimension] watershed_output_type = itk.Image[itk.US, dimension] caster = itk.CastImageFilter[type(input_image), watershed_input_type].New() caster.SetInput(input_image) watershed_filter = \ itk.MorphologicalWatershedImageFilter[ watershed_input_type, watershed_output_type].New(Input=caster.GetOutput()) watershed_filter.SetLevel(level) watershed_filter.SetMarkWatershedLine(True) watershed_filter.SetFullyConnected(True) operator.progress.message = "Watershed filter" progress = operator.progress.value itkutils.observe_filter_progress(operator, watershed_filter, progress, progress + next(step_pct)) try: watershed_filter.Update() except RuntimeError: return return watershed_filter.GetOutput()
def transform_scalars(self, dataset, amount=0.5, threshold=0.0, sigma=1.0): """This filter performs anisotropic diffusion on an image using the classic Perona-Malik, gradient magnitude-based equation. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform step_pct = iter([10, 20, 90, 100]) try: import itk from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc try: self.progress.message = "Converting data to ITK image" self.progress.value = 0 # Get the ITK image. The itk.GradientAnisotropicDiffusionImageFilter # is templated over float pixel types only, so explicitly request a # float ITK image type. itk_image = itkutils.convert_vtk_to_itk_image(dataset) self.progress.value = next(step_pct) self.progress.message = "Running filter" self.progress.value = next(step_pct) unsharp_mask = \ itk.UnsharpMaskImageFilter.New(Input=itk_image) unsharp_mask.SetAmount(amount) unsharp_mask.SetThreshold(threshold) unsharp_mask.SetSigma(sigma) itkutils.observe_filter_progress(self, unsharp_mask, self.progress.value, next(step_pct)) try: unsharp_mask.Update() except RuntimeError: return self.progress.message = "Saving results" enhanced = unsharp_mask.GetOutput() itkutils.set_array_from_itk_image(dataset, enhanced) self.progress.value = next(step_pct) except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # 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: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
def transform(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # 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: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.dataset_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_itk_image_on_dataset(filter.GetOutput(), dataset) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
def fill_holes(operator, step_pct, input_image): import itk from tomviz import itkutils fill_hole = \ itk.GrayscaleFillholeImageFilter.New(Input=input_image) operator.progress.message = "Fill holes" progress = operator.progress.value itkutils.observe_filter_progress(operator, fill_hole, progress, progress + next(step_pct)) try: fill_hole.Update() except RuntimeError: return return fill_hole.GetOutput()
def threshold(operator, step_pct, input_image): import itk from tomviz import itkutils import itkExtras import itkTypes otsu_filter = \ itk.OtsuMultipleThresholdsImageFilter.New(Input=input_image) otsu_filter.SetNumberOfThresholds(1) operator.progress.message = "Otsu threshold" progress = operator.progress.value itkutils.observe_filter_progress(operator, otsu_filter, progress, progress + next(step_pct)) try: otsu_filter.Update() except RuntimeError: return # Cast threshold output to an integral type if needed. input_image_type = type(input_image) voxel_type = itkExtras.template(input_image_type)[1][0] if voxel_type is itkTypes.F or voxel_type is itkTypes.D: operator.progress.message = "Casting output to integral type" # Unsigned char supports 256 labels, or 255 threshold levels. # This should be sufficient for all but the most unusual use # cases. dimension = input_image_type.GetImageDimension() py_buffer_type = itk.Image[itk.UC, dimension] caster = itk.CastImageFilter[input_image_type, py_buffer_type].New() caster.SetInput(thresholded) progress = operator.progress.value itkutils.observe_filter_progress(operator, caster, progress, progress + next(step_pct)) try: caster.Update() except RuntimeError: return thresholded = caster.GetOutput() thresholded = otsu_filter.GetOutput() return thresholded
def invert(operator, step_pct, input_image): import itk from tomviz import itkutils inverter = \ itk.NotImageFilter.New(Input=input_image) operator.progress.message = "Invert threshold" progress = operator.progress.value itkutils.observe_filter_progress(operator, inverter, progress, progress + next(step_pct)) try: inverter.Update() except RuntimeError: return return inverter.GetOutput()
def morphological_closing(operator, step_pct, input_image, structuring_element): import itk from tomviz import itkutils closer = \ itk.GrayscaleMorphologicalClosingImageFilter.New(Input=input_image) closer.SetKernel(structuring_element) operator.progress.message = "Morphological closing" progress = operator.progress.value itkutils.observe_filter_progress(operator, closer, progress, progress + next(step_pct)) try: closer.Update() except RuntimeError: return return closer.GetOutput()
def get_distance(operator, step_pct, input_image): import itk from tomviz import itkutils distance_mapper = \ itk.SignedMaurerDistanceMapImageFilter.New(Input=input_image) distance_mapper.SetInsideIsPositive(True) distance_mapper.SetSquaredDistance(False) distance_mapper.SetUseImageSpacing(True) operator.progress.message = "Distance map" progress = operator.progress.value itkutils.observe_filter_progress(operator, distance_mapper, progress, progress + next(step_pct)) try: distance_mapper.Update() except RuntimeError: return return distance_mapper.GetOutput()
def opening_by_reconstruction(operator, step_pct, input_image, structuring_element): import itk from tomviz import itkutils opening = \ itk.OpeningByReconstructionImageFilter.New(Input=input_image) opening.SetKernel(structuring_element) operator.progress.message = "Opening by reconstruction" progress = operator.progress.value itkutils.observe_filter_progress(operator, opening, progress, progress + next(step_pct)) try: opening.Update() except RuntimeError: return return opening.GetOutput()
def median_filter(operator, step_pct, input_image): import itk from tomviz import itkutils median_filter = \ itk.MedianImageFilter.New(Input=input_image) median_radius = itk.Size[3]() median_radius.Fill(1) median_filter.SetRadius(median_radius) operator.progress.message = "Median filter" progress = operator.progress.value itkutils.observe_filter_progress(operator, median_filter, progress, progress + next(step_pct)) try: median_filter.Update() except RuntimeError: return return median_filter.GetOutput()
def unsharp_mask(operator, step_pct, input_image): import itk from tomviz import itkutils import numpy as np enhancer = \ itk.UnsharpMaskImageFilter.New(Input=input_image) enhancer.SetAmount(3.0) spacing = input_image.GetSpacing() enhancer.SetSigma(2.0 * np.max(spacing)) operator.progress.message = "Unsharp mask" progress = operator.progress.value itkutils.observe_filter_progress(operator, enhancer, progress, progress + next(step_pct)) try: enhancer.Update() except RuntimeError: return return enhancer.GetOutput()
def encapsulate(operator, step_pct, input_image, mask, structuring_element): import itk from tomviz import itkutils dilater = \ itk.GrayscaleDilateImageFilter.New(Input=input_image) dilater.SetKernel(structuring_element) operator.progress.message = "Encapsulate" progress = operator.progress.value nextprogress = progress + next(step_pct) itkutils.observe_filter_progress(operator, dilater, progress, nextprogress) xor_filter = \ itk.XorImageFilter.New(Input1=mask, Input2=dilater.GetOutput()) progress = nextprogress nextprogress = progress + next(step_pct) itkutils.observe_filter_progress(operator, xor_filter, progress, nextprogress) or_filter = \ itk.OrImageFilter.New(Input1=input_image, Input2=xor_filter.GetOutput()) progress = nextprogress nextprogress = progress + next(step_pct) itkutils.observe_filter_progress(operator, or_filter, progress, nextprogress) try: or_filter.Update() except RuntimeError: return return or_filter.GetOutput()
def transform_scalars(self, dataset, conductance=1.0, iterations=100, timestep=0.0625): """This filter performs anisotropic diffusion on an image using the classic Perona-Malik, gradient magnitude-based equation. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 90, 100] try: import itk import itkTypes from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc try: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image. The itk.GradientAnisotropicDiffusionImageFilter # is templated over float pixel types only, so explicitly request a # float ITK image type. itk_image = itkutils.convert_vtk_to_itk_image(dataset, itkTypes.F) itk_image_type = type(itk_image) self.progress.value = STEP_PCT[1] self.progress.message = "Running filter" DiffusionFilterType = \ itk.GradientAnisotropicDiffusionImageFilter[itk_image_type, itk_image_type] diffusion_filter = DiffusionFilterType.New() diffusion_filter.SetConductanceParameter(conductance) diffusion_filter.SetNumberOfIterations(iterations) diffusion_filter.SetTimeStep(timestep) diffusion_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, diffusion_filter, STEP_PCT[1], STEP_PCT[2]) try: diffusion_filter.Update() except RuntimeError: return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, diffusion_filter.GetOutput()) self.progress.value = STEP_PCT[3] except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
def transform_scalars(self, dataset, lower_threshold=40.0, upper_threshold=255.0): """This filter computes a binary threshold on the data set and stores the result in a child data set. It does not modify the dataset passed in.""" # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [20, 40, 75, 90, 100] # Set up return value returnValue = None # Try imports to make sure we have everything that is needed try: self.progress.message = "Loading modules" import itk import vtk from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = STEP_PCT[1] self.progress.message = "Running filter" # We change the output type to unsigned char 3D # (itk.Image.UC3D) to save memory in the output label map # representation. itk_output_image_type = itk.Image.UC3 # ITK's BinaryThresholdImageFilter does the hard work threshold_filter = itk.BinaryThresholdImageFilter[ itk_input_image_type, itk_output_image_type].New() python_cast = itkutils.get_python_voxel_type(itk_image) threshold_filter.SetLowerThreshold(python_cast(lower_threshold)) threshold_filter.SetUpperThreshold(python_cast(upper_threshold)) threshold_filter.SetInsideValue(1) threshold_filter.SetOutsideValue(0) threshold_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, threshold_filter, STEP_PCT[2], STEP_PCT[3]) try: threshold_filter.Update() except RuntimeError: return returnValue self.progress.message = "Creating child data set" # Set the output as a new child data object of the current data set label_map_dataset = vtk.vtkImageData() label_map_dataset.CopyStructure(dataset) itkutils.set_array_from_itk_image(label_map_dataset, threshold_filter.GetOutput()) self.progress.value = STEP_PCT[4] returnValue = { "thresholded_segmentation": label_map_dataset } except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValue
def transform_scalars(self, dataset, number_of_thresholds=1, enable_valley_emphasis=False): """This filter performs semi-automatic multithresholding of a data set. Voxels are automatically classified into a chosen number of classes such that inter-class variance of the voxel values is minimized. The output is a label map with one label per voxel class. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 70, 90, 100] try: import itk import itkExtras import itkTypes from vtkmodules.vtkCommonDataModel import vtkImageData from tomviz import itkutils from tomviz import utils except Exception as exc: print("Could not import necessary module(s)") raise exc # Return values returnValues = None # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) # OtsuMultipleThresholdsImageFilter's wrapping requires that the # input and output image types be the same. itk_threshold_image_type = itk_input_image_type # Otsu multiple threshold filter otsu_filter = itk.OtsuMultipleThresholdsImageFilter[ itk_input_image_type, itk_threshold_image_type].New() otsu_filter.SetNumberOfThresholds(number_of_thresholds) otsu_filter.SetValleyEmphasis(enable_valley_emphasis) otsu_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, otsu_filter, STEP_PCT[1], STEP_PCT[2]) try: otsu_filter.Update() except RuntimeError: return print("Otsu threshold(s): %s" % (otsu_filter.GetThresholds(),)) itk_image_data = otsu_filter.GetOutput() # Cast threshold output to an integral type if needed. py_buffer_type = itk_threshold_image_type voxel_type = itkExtras.template(itk_threshold_image_type)[1][0] if voxel_type is itkTypes.F or voxel_type is itkTypes.D: self.progress.message = "Casting output to integral type" # Unsigned char supports 256 labels, or 255 threshold levels. # This should be sufficient for all but the most unusual use # cases. py_buffer_type = itk.Image.UC3 caster = itk.CastImageFilter[itk_threshold_image_type, py_buffer_type].New() caster.SetInput(itk_image_data) itkutils.observe_filter_progress(self, caster, STEP_PCT[2], STEP_PCT[3]) try: caster.Update() except RuntimeError: return itk_image_data = caster.GetOutput() self.progress.value = STEP_PCT[3] self.progress.message = "Saving results" label_buffer = itk.PyBuffer[py_buffer_type] \ .GetArrayFromImage(itk_image_data) label_map_dataset = vtkImageData() label_map_dataset.CopyStructure(dataset) utils.set_array(label_map_dataset, label_buffer, isFortran=False) self.progress.value = STEP_PCT[4] # Set up dictionary to return operator results returnValues = {} returnValues["label_map"] = label_map_dataset except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValues
def transform(self, dataset, stencil_radius=2, iterations=10, threshold=50.0): """This filter smooths a binary image by evolving a level set with a curvature-based speed function. The Stencil Radius determines the scale of the noise to remove. The Threshold determines the iso-contour brightness to discriminate between two pixel classes. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 30, 70, 80, 90, 100] try: import itk import itkTypes from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # Return values returnValue = None # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.dataset_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.message = "Casting input to float type" itk_filter_image_type = itk.Image[itkTypes.F, itk_image.GetImageDimension()] caster = itk.CastImageFilter[itk_input_image_type, itk_filter_image_type].New() caster.SetInput(itk_image) itkutils.observe_filter_progress(self, caster, STEP_PCT[1], STEP_PCT[2]) try: caster.Update() except RuntimeError: return self.progress.message = "Running filter" smoothing_filter = itk.BinaryMinMaxCurvatureFlowImageFilter[ itk_filter_image_type, itk_filter_image_type].New() smoothing_filter.SetThreshold(threshold) smoothing_filter.SetStencilRadius(stencil_radius) smoothing_filter.SetNumberOfIterations(iterations) smoothing_filter.SetTimeStep(0.0625) smoothing_filter.SetInput(caster) itkutils.observe_filter_progress(self, smoothing_filter, STEP_PCT[2], STEP_PCT[3]) try: smoothing_filter.Update() except RuntimeError: return itk_image_data = smoothing_filter.GetOutput() # Cast output to the input type self.progress.message = "Casting output to input type" caster = itk.CastImageFilter[itk_filter_image_type, itk_input_image_type].New() caster.SetInput(itk_image_data) itkutils.observe_filter_progress(self, caster, STEP_PCT[3], STEP_PCT[4]) try: caster.Update() except RuntimeError: return itk_image_data = caster.GetOutput() self.progress.value = STEP_PCT[5] self.progress.message = "Saving results" itkutils.set_itk_image_on_dataset(itk_image_data, dataset) self.progress.value = STEP_PCT[6] except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValue
def transform_scalars(self, dataset, number_of_thresholds=1, enable_valley_emphasis=False): """This filter performs semi-automatic multithresholding of a data set. Voxels are automatically classified into a chosen number of classes such that inter-class variance of the voxel values is minimized. The output is a label map with one label per voxel class. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 70, 90, 100] try: import itk import itkExtras import itkTypes import vtk from tomviz import itkutils from tomviz import utils except Exception as exc: print("Could not import necessary module(s)") raise exc # Return values returnValues = None # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) # OtsuMultipleThresholdsImageFilter's wrapping requires that the # input and output image types be the same. itk_threshold_image_type = itk_input_image_type # Otsu multiple threshold filter otsu_filter = itk.OtsuMultipleThresholdsImageFilter[ itk_input_image_type, itk_threshold_image_type].New() otsu_filter.SetNumberOfThresholds(number_of_thresholds) otsu_filter.SetValleyEmphasis(enable_valley_emphasis) otsu_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, otsu_filter, STEP_PCT[1], STEP_PCT[2]) try: otsu_filter.Update() except RuntimeError: return print("Otsu threshold(s): %s" % (otsu_filter.GetThresholds(),)) itk_image_data = otsu_filter.GetOutput() # Cast threshold output to an integral type if needed. py_buffer_type = itk_threshold_image_type voxel_type = itkExtras.template(itk_threshold_image_type)[1][0] if voxel_type is itkTypes.F or voxel_type is itkTypes.D: self.progress.message = "Casting output to integral type" # Unsigned char supports 256 labels, or 255 threshold levels. # This should be sufficient for all but the most unusual use # cases. py_buffer_type = itk.Image.UC3 caster = itk.CastImageFilter[itk_threshold_image_type, py_buffer_type].New() caster.SetInput(itk_image_data) itkutils.observe_filter_progress(self, caster, STEP_PCT[2], STEP_PCT[3]) try: caster.Update() except RuntimeError: return itk_image_data = caster.GetOutput() self.progress.value = STEP_PCT[3] self.progress.message = "Saving results" label_buffer = itk.PyBuffer[py_buffer_type] \ .GetArrayFromImage(itk_image_data) label_map_dataset = vtk.vtkImageData() label_map_dataset.CopyStructure(dataset) utils.set_array(label_map_dataset, label_buffer) self.progress.value = STEP_PCT[4] # Set up dictionary to return operator results returnValues = {} returnValues["label_map"] = label_map_dataset except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValues
def transform(self, dataset, structuring_element_id=0, radius=1, object_label=1, background_label=0): """Erode segmented objects with a given label by a spherically symmetric structuring element with a given radius. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 90, 100] try: import itk from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.dataset_to_itk_image(dataset) itk_input_image_type = type(itk_image) itk_kernel_type = itk.FlatStructuringElement[3] if (structuring_element_id == 0): itk_kernel = itk_kernel_type.Box(radius) elif (structuring_element_id == 1): itk_kernel = itk_kernel_type.Ball(radius) elif (structuring_element_id == 2): itk_kernel = itk_kernel_type.Cross(radius) else: raise Exception('Invalid kernel shape id %d' % structuring_element_id) self.progress.value = STEP_PCT[1] self.progress.message = "Running filter" erode_filter = itk.BinaryErodeImageFilter[itk_input_image_type, itk_input_image_type, itk_kernel_type].New() erode_filter.SetErodeValue(object_label) erode_filter.SetBackgroundValue(background_label) erode_filter.SetKernel(itk_kernel) erode_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, erode_filter, STEP_PCT[1], STEP_PCT[2]) try: erode_filter.Update() except RuntimeError: return self.progress.message = "Saving results" itkutils.set_itk_image_on_dataset(erode_filter.GetOutput(), dataset) self.progress.value = STEP_PCT[3] except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
def transform_scalars(self, dataset, lower_threshold=40.0, upper_threshold=255.0): """This filter computes a binary threshold on the data set and stores the result in a child data set. It does not modify the dataset passed in.""" # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [20, 40, 75, 90, 100] # Set up return value returnValue = None # Try imports to make sure we have everything that is needed try: self.progress.message = "Loading modules" import itk from vtkmodules.vtkCommonDataModel import vtkImageData from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = STEP_PCT[1] self.progress.message = "Running filter" # We change the output type to unsigned char 3D # (itk.Image.UC3D) to save memory in the output label map # representation. itk_output_image_type = itk.Image.UC3 # ITK's BinaryThresholdImageFilter does the hard work threshold_filter = itk.BinaryThresholdImageFilter[ itk_input_image_type, itk_output_image_type].New() python_cast = itkutils.get_python_voxel_type(itk_image) threshold_filter.SetLowerThreshold(python_cast(lower_threshold)) threshold_filter.SetUpperThreshold(python_cast(upper_threshold)) threshold_filter.SetInsideValue(1) threshold_filter.SetOutsideValue(0) threshold_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, threshold_filter, STEP_PCT[2], STEP_PCT[3]) try: threshold_filter.Update() except RuntimeError: return returnValue self.progress.message = "Creating child data set" # Set the output as a new child data object of the current data set label_map_dataset = vtkImageData() label_map_dataset.CopyStructure(dataset) itkutils.set_array_from_itk_image(label_map_dataset, threshold_filter.GetOutput()) self.progress.value = STEP_PCT[4] returnValue = {"thresholded_segmentation": label_map_dataset} except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValue
def transform_scalars(self, dataset, stencil_radius=2, iterations=10, threshold=50.0): """This filter smooths a binary image by evolving a level set with a curvature-based speed function. The Stencil Radius determines the scale of the noise to remove. The Threshold determines the iso-contour brightness to discriminate between two pixel classes. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 20, 30, 70, 80, 90, 100] try: import itk import itkTypes from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # Return values returnValue = None # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.message = "Casting input to float type" itk_filter_image_type = itk.Image[itkTypes.F, itk_image.GetImageDimension()] caster = itk.CastImageFilter[itk_input_image_type, itk_filter_image_type].New() caster.SetInput(itk_image) itkutils.observe_filter_progress(self, caster, STEP_PCT[1], STEP_PCT[2]) try: caster.Update() except RuntimeError: return self.progress.message = "Running filter" smoothing_filter = itk.BinaryMinMaxCurvatureFlowImageFilter[ itk_filter_image_type, itk_filter_image_type].New() smoothing_filter.SetThreshold(threshold) smoothing_filter.SetStencilRadius(stencil_radius) smoothing_filter.SetNumberOfIterations(iterations) smoothing_filter.SetTimeStep(0.0625) smoothing_filter.SetInput(caster) itkutils.observe_filter_progress(self, smoothing_filter, STEP_PCT[2], STEP_PCT[3]) try: smoothing_filter.Update() except RuntimeError: return itk_image_data = smoothing_filter.GetOutput() # Cast output to the input type self.progress.message = "Casting output to input type" caster = itk.CastImageFilter[itk_filter_image_type, itk_input_image_type].New() caster.SetInput(itk_image_data) itkutils.observe_filter_progress(self, caster, STEP_PCT[3], STEP_PCT[4]) try: caster.Update() except RuntimeError: return itk_image_data = caster.GetOutput() self.progress.value = STEP_PCT[5] self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, itk_image_data) self.progress.value = STEP_PCT[6] except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc return returnValue
def transform_scalars(self, dataset, structuring_element_id=0, radius=1, object_label=1, background_label=0): """Perform morphological opening on segmented objects with a given label by a spherically symmetric structuring element with a given radius. """ # Initial progress self.progress.value = 0 self.progress.maximum = 100 # Approximate percentage of work completed after each step in the # transform STEP_PCT = [10, 30, 60, 90, 100] try: import itk from tomviz import itkutils except Exception as exc: print("Could not import necessary module(s)") raise exc # 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: self.progress.value = STEP_PCT[0] self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) itk_kernel_type = itk.FlatStructuringElement[3] if (structuring_element_id == 0): itk_kernel = itk_kernel_type.Box(radius) elif (structuring_element_id == 1): itk_kernel = itk_kernel_type.Ball(radius) elif (structuring_element_id == 2): itk_kernel = itk_kernel_type.Cross(radius) else: raise Exception('Invalid kernel shape id %d' % structuring_element_id) self.progress.value = STEP_PCT[1] self.progress.message = "Running filter" erode_filter = itk.BinaryErodeImageFilter[itk_input_image_type, itk_input_image_type, itk_kernel_type].New() erode_filter.SetErodeValue(object_label) erode_filter.SetBackgroundValue(background_label) erode_filter.SetKernel(itk_kernel) erode_filter.SetInput(itk_image) itkutils.observe_filter_progress(self, erode_filter, STEP_PCT[1], STEP_PCT[2]) dilate_filter = itk.BinaryDilateImageFilter[itk_input_image_type, itk_input_image_type, itk_kernel_type].New() dilate_filter.SetDilateValue(object_label) dilate_filter.SetBackgroundValue(background_label) dilate_filter.SetKernel(itk_kernel) dilate_filter.SetInput(erode_filter.GetOutput()) itkutils.observe_filter_progress(self, dilate_filter, STEP_PCT[2], STEP_PCT[3]) try: dilate_filter.Update() except RuntimeError: return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, dilate_filter.GetOutput()) self.progress.value = STEP_PCT[4] except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc