def ComputeKSpaceOperation(self,kSpace): kSpaceMValue = vtk.vtkImageMathematics() kSpaceMValue.SetInput(kSpace) kSpaceMValue.SetOperationToMultiplyByK() kSpaceMValue.SetConstantK(self.MValue) kSpaceMValue.Update() kSpace = kSpaceMValue.GetOutput() if not self.KSpace: return kSpace if self.KSpaceOperation == 'none': return kSpace kSpaceMaths = vtk.vtkImageMathematics() if self.KSpaceOperation == 'add': kSpaceMaths.SetOperationToAdd() elif self.KSpaceOperation == 'subtract': kSpaceMaths.SetOperationToSubtract() else: self.PrintError('KSpaceOperation not supported.') return kSpace kSpaceMaths.SetInput1(self.KSpace) kSpaceMaths.SetInput2(kSpace) kSpaceMaths.Update() return kSpaceMaths.GetOutput()
def IsosurfaceInitialize(self): self.PrintLog('Isosurface initialization.') if self.Interactive: queryString = "Please input isosurface level (\'n\' for none): " self.IsoSurfaceValue = self.ThresholdInput(queryString) imageMathematics = vtk.vtkImageMathematics() imageMathematics.SetInput(self.Image) imageMathematics.SetConstantK(-1.0) imageMathematics.SetOperationToMultiplyByK() imageMathematics.Update() subtract = vtk.vtkImageMathematics() subtract.SetInput(imageMathematics.GetOutput()) subtract.SetOperationToAddConstant() subtract.SetConstantC(self.IsoSurfaceValue) subtract.Update() self.InitialLevelSets = vtk.vtkImageData() self.InitialLevelSets.DeepCopy(subtract.GetOutput()) self.InitialLevelSets.Update() self.IsoSurfaceValue = 0.0
def ComputeKSpaceOperation(self, kSpace): kSpaceMValue = vtk.vtkImageMathematics() kSpaceMValue.SetInput(kSpace) kSpaceMValue.SetOperationToMultiplyByK() kSpaceMValue.SetConstantK(self.MValue) kSpaceMValue.Update() kSpace = kSpaceMValue.GetOutput() if not self.KSpace: return kSpace if self.KSpaceOperation == 'none': return kSpace kSpaceMaths = vtk.vtkImageMathematics() if self.KSpaceOperation == 'add': kSpaceMaths.SetOperationToAdd() elif self.KSpaceOperation == 'subtract': kSpaceMaths.SetOperationToSubtract() else: self.PrintError('KSpaceOperation not supported.') return kSpace kSpaceMaths.SetInput1(self.KSpace) kSpaceMaths.SetInput2(kSpace) kSpaceMaths.Update() return kSpaceMaths.GetOutput()
def AddShotNoise(inputImage, outputImage, noiseAmplitude, noiseFraction, extent): shotNoiseSource = vtk.vtkImageNoiseSource() shotNoiseSource.SetWholeExtent(extent) shotNoiseSource.SetMinimum(0.0) shotNoiseSource.SetMaximum(1.0) shotNoiseThresh1 = vtk.vtkImageThreshold() shotNoiseThresh1.SetInputConnection(shotNoiseSource.GetOutputPort()) shotNoiseThresh1.ThresholdByLower(1.0 - noiseFraction) shotNoiseThresh1.SetInValue(0) shotNoiseThresh1.SetOutValue(noiseAmplitude) shotNoiseThresh2 = vtk.vtkImageThreshold() shotNoiseThresh2.SetInputConnection(shotNoiseSource.GetOutputPort()) shotNoiseThresh2.ThresholdByLower(noiseFraction) shotNoiseThresh2.SetInValue(1.0 - noiseAmplitude) shotNoiseThresh2.SetOutValue(0.0) shotNoise = vtk.vtkImageMathematics() shotNoise.SetInputConnection(0, shotNoiseThresh1.GetOutputPort()) shotNoise.SetInputConnection(1, shotNoiseThresh2.GetOutputPort()) shotNoise.SetOperationToAdd() add = vtk.vtkImageMathematics() add.SetInputData(0, inputImage) add.SetInputConnection(1, shotNoise.GetOutputPort()) add.SetOperationToAdd() add.Update() outputImage.DeepCopy(add.GetOutput())
def BuildVTKGradientBasedFeatureImage(self): cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetInputConnection(cast.GetOutputPort()) gradientMagnitude.SetDimensionality(self.Dimensionality) gradientMagnitude.Update() imageAdd = vtk.vtkImageMathematics() imageAdd.SetInputConnection(gradientMagnitude.GetOutputPort()) imageAdd.SetOperationToAddConstant() imageAdd.SetConstantC(1.0) imageAdd.Update() imageInvert = vtk.vtkImageMathematics() imageInvert.SetInputConnection(imageAdd.GetOutputPort()) imageInvert.SetOperationToInvert() imageInvert.SetConstantC(1E20) imageInvert.DivideByZeroToCOn() imageInvert.Update() self.FeatureImage = vtk.vtkImageData() self.FeatureImage.DeepCopy(imageInvert.GetOutput())
def ipl_cl_rank_extract(image_in, first_rank, last_rank): ipl_cl_rank_extract_settings(first_rank, last_rank) step1 = image_in temp = vtk.vtkImageMathematics() temp.SetInput1(image_in) temp.SetConstantC(127) temp.SetConstantK(0) temp.SetOperationToReplaceCByK() for x in range(first_rank, last_rank + 1): connect = vtkn88.vtkn88ImageConnectivityFilter() connect.SetInput(image_in) connect.SetExtractionModeToLargestRegion() connect.Update() sub = vtk.vtkImageMathematics() sub.SetInput1(image_in) sub.SetInput2(connect.GetOutput()) sub.SetOperationToSubtract() sub.Update() add = vtk.vtkImageMathematics() add.SetInput1(temp.GetOutput()) add.SetInput2(connect.GetOutput()) add.SetOperationToAdd() add.Update() temp = add image_in = sub.GetOutput() image_out = temp.GetOutput() return image_out
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.Image2 == None: self.PrintError('Error: No input image2.') if self.NegateImage2: negateFilter = vtk.vtkImageMathematics() negateFilter.SetInputData(self.Image2) negateFilter.SetOperationToMultiplyByK() negateFilter.SetConstantK(-1.0) negateFilter.Update() self.Image2 = negateFilter.GetOutput() composeFilter = vtk.vtkImageMathematics() composeFilter.SetInput1Data(self.Image) composeFilter.SetInput2Data(self.Image2) if self.Operation == 'min': composeFilter.SetOperationToMin() elif self.Operation == 'max': composeFilter.SetOperationToMax() elif self.Operation == 'multiply': composeFilter.SetOperationToMultiply() elif self.Operation == 'subtract': composeFilter.SetOperationToSubtract() else: self.PrintError('Error: Unsupported operation') composeFilter.Update() self.Image = composeFilter.GetOutput()
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.Image2 == None: self.PrintError('Error: No input image2.') if self.NegateImage2: negateFilter = vtk.vtkImageMathematics() negateFilter.SetInput(self.Image2) negateFilter.SetOperationToMultiplyByK() negateFilter.SetConstantK(-1.0) negateFilter.Update() self.Image2 = negateFilter.GetOutput() composeFilter = vtk.vtkImageMathematics() composeFilter.SetInput1(self.Image) composeFilter.SetInput2(self.Image2) if self.Operation == 'min': composeFilter.SetOperationToMin() elif self.Operation == 'max': composeFilter.SetOperationToMax() elif self.Operation == 'multiply': composeFilter.SetOperationToMultiply() elif self.Operation == 'subtract': composeFilter.SetOperationToSubtract() else: self.PrintError('Error: Unsupported operation') composeFilter.Update() self.Image = composeFilter.GetOutput()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # main morph gradient self._imageDilate = vtk.vtkImageContinuousDilate3D() self._imageErode = vtk.vtkImageContinuousErode3D() self._imageMath = vtk.vtkImageMathematics() self._imageMath.SetOperationToSubtract() self._imageMath.SetInput1(self._imageDilate.GetOutput()) self._imageMath.SetInput2(self._imageErode.GetOutput()) # inner gradient self._innerImageMath = vtk.vtkImageMathematics() self._innerImageMath.SetOperationToSubtract() self._innerImageMath.SetInput1(None) # has to take image self._innerImageMath.SetInput2(self._imageErode.GetOutput()) # outer gradient self._outerImageMath = vtk.vtkImageMathematics() self._outerImageMath.SetOperationToSubtract() self._outerImageMath.SetInput1(self._imageDilate.GetOutput()) self._outerImageMath.SetInput2(None) # has to take image module_utils.setup_vtk_object_progress( self, self._imageDilate, 'Performing greyscale 3D dilation') module_utils.setup_vtk_object_progress( self, self._imageErode, 'Performing greyscale 3D erosion') module_utils.setup_vtk_object_progress( self, self._imageMath, 'Subtracting erosion from ' 'dilation') module_utils.setup_vtk_object_progress( self, self._innerImageMath, 'Subtracting erosion from ' 'image (inner)') module_utils.setup_vtk_object_progress( self, self._outerImageMath, 'Subtracting image from ' 'dilation (outer)') self._config.kernelSize = (3, 3, 3) configList = [('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__( self, configList, { 'Module (self)': self, 'vtkImageContinuousDilate3D': self._imageDilate, 'vtkImageContinuousErode3D': self._imageErode, 'vtkImageMathematics': self._imageMath }) self.sync_module_logic_with_config()
def convert_aim_to_density(img, m, b): mult = vtk.vtkImageMathematics() mult.SetOperationToMultiplyByK() mult.SetConstantK(m) mult.SetInputData(img) add = vtk.vtkImageMathematics() add.SetOperationToAddConstant() add.SetConstantC(b) add.SetInputConnection(mult.GetOutputPort()) add.Update() return add.GetOutput()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageMath = vtk.vtkImageMathematics() self._imageMath.SetInput1(None) self._imageMath.SetInput2(None) module_utils.setup_vtk_object_progress(self, self._imageMath, 'Performing image math') self._config.operation = 'subtract' self._config.constantC = 0.0 self._config.constantK = 1.0 configList = [('Operation:', 'operation', 'base:str', 'choice', 'The operation that should be performed.', tuple(OPS_DICT.keys())), ('Constant C:', 'constantC', 'base:float', 'text', 'The constant C used in some operations.'), ('Constant K:', 'constantK', 'base:float', 'text', 'The constant C used in some operations.')] ScriptedConfigModuleMixin.__init__( self, configList, { 'Module (self)': self, 'vtkImageMathematics': self._imageMath }) self.sync_module_logic_with_config()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageMath = vtk.vtkImageMathematics() self._imageMath.SetInput1(None) self._imageMath.SetInput2(None) module_utils.setup_vtk_object_progress(self, self._imageMath, 'Performing image math') self._config.operation = 'subtract' self._config.constantC = 0.0 self._config.constantK = 1.0 configList = [ ('Operation:', 'operation', 'base:str', 'choice', 'The operation that should be performed.', tuple(OPS_DICT.keys())), ('Constant C:', 'constantC', 'base:float', 'text', 'The constant C used in some operations.'), ('Constant K:', 'constantK', 'base:float', 'text', 'The constant C used in some operations.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageMathematics' : self._imageMath}) self.sync_module_logic_with_config()
def test_vtk_pyexception_deadlock(self): """Test if VTK has been patched to release the GIL during all VTK method calls. """ import vtk # this gives floats by default s = vtk.vtkImageGridSource() c1 = vtk.vtkImageCast() c1.SetOutputScalarTypeToShort() c1.SetInput(s.GetOutput()) c2 = vtk.vtkImageCast() c2.SetOutputScalarTypeToFloat() c2.SetInput(s.GetOutput()) m = vtk.vtkImageMathematics() # make sure we are multi-threaded if m.GetNumberOfThreads() < 2: m.SetNumberOfThreads(2) m.SetInput1(c1.GetOutput()) m.SetInput2(c2.GetOutput()) # without the patch, this call will deadlock forever try: # with the patch this should generate a RuntimeError m.Update() except RuntimeError: pass else: self.fail( 'Multi-threaded error vtkImageMathematics did not raise ' 'exception.')
def _maskSourceExecute(self): inputI = self._inputImage if inputI: inputI.Update() self._markerSource.Update() outputJ = self._markerSource.GetStructuredPointsOutput() # we now have an outputJ if not inputI.GetScalarPointer() or \ not outputJ.GetScalarPointer() or \ not inputI.GetDimensions() > (0,0,0): vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: Input is empty.') return iMath = vtk.vtkImageMathematics() iMath.SetOperationToMin() iMath.SetInput1(outputJ) iMath.SetInput2(inputI) iMath.GetOutput().SetUpdateExtentToWholeExtent() iMath.Update() outputI = self._maskSource.GetStructuredPointsOutput() outputI.DeepCopy(iMath.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageMathematics(), 'Processing.', ('vtkImageData', 'vtkImageData'), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def addConstant(image, c): addfilter = vtk.vtkImageMathematics() addfilter.SetInput(image) addfilter.SetConstantC(c) addfilter.SetOperationToAddConstant() addfilter.Update() return addfilter.GetOutput()
def vtkImageReader(file, segmentation=False): """ using vtkMetaImageReader to read mhd file :param file: the path of the mhd file (note: using '/' instead of '\' in absolute path) :param segmentation: assign true when file is partial volume segmentation :return: updated reader """ image = vtk.vtkMetaImageReader() image.SetFileName(file) image.Update() print(image.GetOutput()) if segmentation: # turn datatype to ushort # and increase the voxel value by multiply a constant if it is a partial volume segmentation file cast = vtk.vtkImageCast() cast.SetInputConnection(image.GetOutputPort()) cast.SetOutputScalarTypeToUnsignedShort() cast.Update() math = vtk.vtkImageMathematics() math.SetOperationToMultiplyByK() math.SetConstantK(1150.0) math.SetInputConnection(cast.GetOutputPort()) math.Update() return math else: return image
def multiplyByConstant(image, c): mulfilter = vtk.vtkImageMathematics() mulfilter.SetInput(image) mulfilter.SetConstantK(c) mulfilter.SetOperationToMultiplyByK() mulfilter.Update() return mulfilter.GetOutput()
def subtractionCompare(self): imagePoints = self.Image.GetNumberOfPoints() referencePoints = self.ReferenceImage.GetNumberOfPoints() self.InputInfo('Image Points: ' + str(imagePoints)) self.InputInfo('Reference Image Points: ' + str(referencePoints)) if abs(imagePoints - referencePoints) > 0 : self.ResultLog = 'Uneven NumberOfPoints' return False imageScalarType = self.Image.GetScalarType() referenceScalarType = self.ReferenceImage.GetScalarType() minScalarType = min(imageScalarType,referenceScalarType) self.Image.SetScalarType(minScalarType) self.ReferenceImage.SetScalarType(minScalarType) imageMath = vtk.vtkImageMathematics() imageMath.SetInput1Data(self.Image) imageMath.SetInput2Data(self.ReferenceImage) imageMath.SetOperationToSubtract() imageMath.Update() differenceImage = imageMath.GetOutput() differenceRange = differenceImage.GetPointData().GetScalars().GetRange() self.InputInfo('Difference Range: ' + str(differenceRange)) if max([abs(d) for d in differenceRange]) < self.Tolerance: return True return False
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.LevelSets == None: self.PrintError('Error: No input level sets.') if self.NegateLevelSets: negateFilter = vtk.vtkImageMathematics() negateFilter.SetInput(self.LevelSets) negateFilter.SetOperationToMultiplyByK() negateFilter.SetConstantK(-1.0) negateFilter.Update() self.LevelSets = negateFilter.GetOutput() sigmoid = vtkvmtk.vtkvmtkLevelSetSigmoidFilter() sigmoid.SetInput(self.Image) sigmoid.SetLevelSetsImage(self.LevelSets) sigmoid.SetSigma(self.Sigma) sigmoid.SetScaleValue(self.ScaleValue) if self.ComputeScaleValueFromInput: sigmoid.ComputeScaleValueFromInputOn() else: sigmoid.ComputeScaleValueFromInputOff() sigmoid.Update() self.Image = sigmoid.GetOutput()
def subtractionCompare(self): imagePoints = self.Image.GetNumberOfPoints() referencePoints = self.ReferenceImage.GetNumberOfPoints() self.InputInfo('Image Points: ' + str(imagePoints)) self.InputInfo('Reference Image Points: ' + str(referencePoints)) if abs(imagePoints - referencePoints) > 0: self.ResultLog = 'Uneven NumberOfPoints' return False imageScalarType = self.Image.GetScalarType() referenceScalarType = self.ReferenceImage.GetScalarType() minScalarType = min(imageScalarType, referenceScalarType) self.Image.SetScalarType(minScalarType) self.ReferenceImage.SetScalarType(minScalarType) imageMath = vtk.vtkImageMathematics() imageMath.SetInput1Data(self.Image) imageMath.SetInput2Data(self.ReferenceImage) imageMath.SetOperationToSubtract() imageMath.Update() differenceImage = imageMath.GetOutput() differenceRange = differenceImage.GetPointData().GetScalars().GetRange( ) self.InputInfo('Difference Range: ' + str(differenceRange)) if max([abs(d) for d in differenceRange]) < self.Tolerance: return True return False
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.LevelSets == None: self.PrintError('Error: No input level sets.') if self.NegateLevelSets: negateFilter = vtk.vtkImageMathematics() negateFilter.SetInputData(self.LevelSets) negateFilter.SetOperationToMultiplyByK() negateFilter.SetConstantK(-1.0) negateFilter.Update() self.LevelSets = negateFilter.GetOutput() sigmoid = vtkvmtk.vtkvmtkLevelSetSigmoidFilter() sigmoid.SetInputData(self.Image) sigmoid.SetLevelSetsImage(self.LevelSets) sigmoid.SetSigma(self.Sigma) sigmoid.SetScaleValue(self.ScaleValue) if self.ComputeScaleValueFromInput: sigmoid.ComputeScaleValueFromInputOn() else: sigmoid.ComputeScaleValueFromInputOff() sigmoid.Update() self.Image = sigmoid.GetOutput()
def sumManualSegmentations(self, manualSegmentationsDirectory, mergedVolume): # Get the manual segmentations and create a single summed image import glob manualSegmentationFilenames = glob.glob(manualSegmentationsDirectory+"/*.mha") # Get the first image which each successive image will be added to reader = vtk.vtkMetaImageReader() reader.SetFileName(manualSegmentationFilenames[0]) reader.Update() summedImage = vtk.vtkImageData() summedImage.SetExtent(reader.GetOutput().GetExtent()) summedImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,1) summedImage.ShallowCopy(reader.GetOutput()) # Initialize filter to add images together mathFilter = vtk.vtkImageMathematics() # Iterate list and add each new image for currentFile in manualSegmentationFilenames[1:]: # Get new image reader.SetFileName(currentFile) reader.Update() # Add it to existing summation mathFilter.SetInput1Data(summedImage) mathFilter.SetInput2Data(reader.GetOutput()) mathFilter.Update() # Get new summation summedImage.ShallowCopy(mathFilter.GetOutput()) # Add summed image to slicer scene mergedVolume.SetRASToIJKMatrix(self.rasToIjk) mergedVolume.SetIJKToRASMatrix(self.ijkToRas) mergedVolume.SetAndObserveImageData(summedImage)
def subtractImages(image1, image2): addfilter = vtk.vtkImageMathematics() addfilter.SetInput1(image1) addfilter.SetInput2(image2) addfilter.SetOperationToSubtract() addfilter.Update() return addfilter.GetOutput()
def subtractionCompare(self): imagePoints = self.Image.GetNumberOfPoints() referencePoints = self.ReferenceImage.GetNumberOfPoints() self.InputInfo('Image Points: ' + str(imagePoints)) self.InputInfo('Reference Image Points: ' + str(referencePoints)) if abs(imagePoints - referencePoints) > 0 : self.ResultLog = 'Uneven NumberOfPoints' return False imageScalarType = self.Image.GetScalarType() referenceScalarType = self.ReferenceImage.GetScalarType() if imageScalarType != referenceScalarType: self.PrintError('Error: Input image and reference image are not of \ the same type. Please cast images to the same type.') imageMath = vtk.vtkImageMathematics() imageMath.SetInput1Data(self.Image) imageMath.SetInput2Data(self.ReferenceImage) imageMath.SetOperationToSubtract() imageMath.Update() differenceImage = imageMath.GetOutput() differenceRange = differenceImage.GetPointData().GetScalars().GetRange() self.InputInfo('Difference Range: ' + str(differenceRange)) if max([abs(d) for d in differenceRange]) < self.Tolerance: return True return False
def VTKImageArith(x1,x2,op,numret=False,rep=0.0): if type(x1) == np.ndarray and type(x2) == np.ndarray: if x1.dtype == np.float64 or x2.dtype == np.float64: x1,x2 = x1.astype(np.float64), x2.astype(np.float64) elif x1.dtype == np.float32 or x2.dtype == np.float32: x1,x2 = x1.astype(np.float32), x2.astype(np.float32) if type(x1) == np.ndarray: i1 = NumToVTKImage(x1) else: i1 = x1 if type(x2) == np.ndarray: i2 = NumToVTKImage(x2) else: i2 = x2 m = vtk.vtkImageMathematics() numops = [ "multiply","divide","add","subtract"] if op == "divide": m.SetConstantC(rep); m.DivideByZeroToCOn() if type(x1) == np.ndarray and type(x2) == np.ndarray: m.SetInput1Data(i1) m.SetInput2Data(i2) vtkops = [ m.SetOperationToMultiply, m.SetOperationToDivide, m.SetOperationToAdd, m.SetOperationToSubtract] elif type(x1) == np.ndarray: m.SetInput1Data(i1) if i2 == 0: const = 0.0 else: const = [i2,1.0/i2,i2,-i2][numops.index(op)] m.SetConstantK(const) m.SetConstantC(const) vtkops = [ m.SetOperationToMultiplyByK, m.SetOperationToMultiplyByK, m.SetOperationToAddConstant, m.SetOperationToAddConstant] if type(x1) != np.ndarray and type(x2) != np.ndarray: return eval(op)(x1,x2) else: vtkops[numops.index(op)]() o = m.GetOutput() m.Update() if numret: return VTKImageToNum(o) else: return o
def getIndexedImageData(inputVtkImageData, indexVal): """ @type inputVtkImageData: C{vtkImageData} @param inputVtkImageData: Image data to be processed @type indexVal: C{unsigned int} @param indexVal: Index value that will be assigned to all non-zero values. Function replaces all non-zero valued pixels of provided C{inputVtkImageData} with C{indexVal} and returns the result. @rtype: C{vtkImageData} @return: UnsignedInt vtkImageData with two values 0 and provided C{indexVal}. """ # Convert normalized input image to unsigned int scalars cast = vtk.vtkImageCast() cast.SetInput(getImageMask(inputVtkImageData)) cast.SetOutputScalarTypeToUnsignedInt() # Then multiply the normalized image data by priovided constant multip = vtk.vtkImageMathematics() multip.SetOperationToMultiplyByK() multip.SetConstantK(indexVal) multip.SetInput(cast.GetOutput()) return multip.GetOutput()
def loadTestData(self): #download data and add to dicom database zipFileUrl = 'http://slicer.kitware.com/midas3/download/item/257234/QIN-HEADNECK-01-0139-PET.zip' zipFilePath = self.tempDataDir + '/dicom.zip' zipFileData = self.tempDataDir + '/dicom' expectedNumOfFiles = 545 if not os.access(self.tempDataDir, os.F_OK): os.mkdir(self.tempDataDir) if not os.access(zipFileData, os.F_OK): os.mkdir(zipFileData) dicomWidget = slicer.modules.dicom.widgetRepresentation().self() dicomPluginCheckbox = dicomWidget.detailsPopup.pluginSelector.checkBoxByPlugin dicomPluginStates = {(key, value.checked) for key, value in dicomPluginCheckbox.iteritems()} for cb in dicomPluginCheckbox.itervalues(): cb.checked = False dicomPluginCheckbox['DICOMScalarVolumePlugin'].checked = True # Download, unzip, import, and load data. Verify loaded nodes. loadedNodes = {'vtkMRMLScalarVolumeNode': 1} with DICOMUtils.LoadDICOMFilesToDatabase(zipFileUrl, zipFilePath, zipFileData, expectedNumOfFiles, {}, loadedNodes) as success: self.assertTrue(success) print('loading returned true') self.assertEqual( len(slicer.util.getNodes('vtkMRMLSubjectHierarchyNode*')), 1) imageNode = slicer.mrmlScene.GetFirstNodeByClass( 'vtkMRMLScalarVolumeNode') for key, value in dicomPluginStates: dicomPluginCheckbox[key].checked = value # apply the SUVbw conversion factor and set units and quantity suvNormalizationFactor = 0.00040166400000000007 quantity = slicer.vtkCodedEntry() quantity.SetFromString( 'CodeValue:126400|CodingSchemeDesignator:DCM|CodeMeaning:Standardized Uptake Value' ) units = slicer.vtkCodedEntry() units.SetFromString( 'CodeValue:{SUVbw}g/ml|CodingSchemeDesignator:UCUM|CodeMeaning:Standardized Uptake Value body weight' ) multiplier = vtk.vtkImageMathematics() multiplier.SetOperationToMultiplyByK() multiplier.SetConstantK(suvNormalizationFactor) multiplier.SetInput1Data(imageNode.GetImageData()) multiplier.Update() imageNode.GetImageData().DeepCopy(multiplier.GetOutput()) imageNode.GetVolumeDisplayNode().SetWindowLevel(6, 3) imageNode.GetVolumeDisplayNode().SetAndObserveColorNodeID( 'vtkMRMLColorTableNodeInvertedGrey') imageNode.SetVoxelValueQuantity(quantity) imageNode.SetVoxelValueUnits(units) return imageNode
def replaceCbyK(image, c, k): replfilter = vtk.vtkImageMathematics() replfilter.SetInput(image) replfilter.SetConstantC(c) replfilter.SetConstantK(k) replfilter.SetOperationToReplaceCByK() replfilter.Update() return replfilter.GetOutput()
def imagesum(image1, image2): """Adds two images.""" sumfilter = vtk.vtkImageMathematics() sumfilter.SetInput1(image1) sumfilter.SetInput2(image2) sumfilter.SetOperationToAdd() sumfilter.Update() return sumfilter.GetOutput()
def diff(im1, im2): #Takes the differences of two aim files and adds them together shift1 = vtk.vtkImageShiftScale() shift1.SetInputConnection(im1.GetOutputPort()) shift1.SetOutputScalarTypeToChar() shift2 = vtk.vtkImageShiftScale() shift2.SetInputConnection(im2.GetOutputPort()) shift2.SetOutputScalarTypeToChar() box1 = vtk.vtkImageReslice() box1.SetInput(shift1.GetOutput()) box1.SetResliceAxesOrigin(im2.GetOutput().GetOrigin()) box1.Update() sub1 = vtk.vtkImageMathematics() sub1.SetInput1(box1.GetOutput()) sub1.SetInput2(shift2.GetOutput()) sub1.SetOperationToSubtract() sub2 = vtk.vtkImageMathematics() sub2.SetInput1(shift2.GetOutput()) sub2.SetInput2(shift1.GetOutput()) sub2.SetOperationToSubtract() step1 = vtk.vtkImageMathematics() step1.SetInput1(sub1.GetOutput()) step1.SetConstantC(-127) step1.SetConstantK(0) step1.SetOperationToReplaceCByK() step2 = vtk.vtkImageMathematics() step2.SetInput1(sub2.GetOutput()) step2.SetConstantC(-127) step2.SetConstantK(0) step2.SetOperationToReplaceCByK() add = vtk.vtkImageMathematics() add.SetInput1(step2.GetOutput()) add.SetInput2(step1.GetOutput()) add.SetOperationToAdd() return add
def imagereplacevalue(image, const1, const2): """Replaces the scalar value in a image with another.""" kfilter = vtk.vtkImageMathematics() kfilter.SetInput1(image) kfilter.SetConstantC(const1) kfilter.SetConstantK(const2) kfilter.SetOperationToReplaceCByK() kfilter.Update() return kfilter.GetOutput()
def VTKAbs(x1): if type(x1) == np.ndarray: i1 = NumToVTKImage(x1) else: i1 = x1 m = vtk.vtkImageMathematics() m.SetOperationToAbsoluteValue() m.AddInputData(i1) o = m.GetOutput() m.Update() return VTKImageToNum(o)
def inverseVTKImage(self, inputImageData): imgvtk = vtk.vtkImageData() imgvtk.DeepCopy(inputImageData) imgvtk.GetPointData().GetScalars().FillComponent(0, 1) subtractFilter = vtk.vtkImageMathematics() subtractFilter.SetInput1Data(imgvtk) subtractFilter.SetInput2Data(inputImageData) subtractFilter.SetOperationToSubtract() # performed inverse operation on the subtractFilter.Update() return subtractFilter.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageMathematics(), 'Processing.', ('vtkImageData', 'vtkImageData'), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def ipl_add_aims(image_in1, image_in2): ipl_add_aims_settings() extent1 = image_in1.GetExtent() voi1 = vtk.vtkExtractVOI() voi1.SetInput(image_in1) voi1.SetVOI(extent1[0], extent1[1], extent1[2], extent1[3], extent1[4], extent1[5]) extent2 = image_in2.GetExtent() voi2 = vtk.vtkExtractVOI() voi2.SetInput(image_in2) voi2.SetVOI(extent2[0], extent2[1], extent2[2], extent2[3], extent2[4], extent2[5]) shift1 = vtk.vtkImageShiftScale() shift1.SetInputConnection(voi1.GetOutputPort()) shift1.SetOutputScalarTypeToChar() shift1.Update() shift2 = vtk.vtkImageShiftScale() shift2.SetInputConnection(voi2.GetOutputPort()) shift2.SetOutputScalarTypeToChar() shift2.Update() add = vtk.vtkImageMathematics() add.SetInput1(shift1.GetOutput()) add.SetInput2(shift2.GetOutput()) add.SetOperationToAdd() add.Update() temp = vtk.vtkImageMathematics() temp.SetInput1(add.GetOutput()) temp.SetConstantC(-2) temp.SetConstantK(127) temp.SetOperationToReplaceCByK() temp.Update() image_out = temp.GetOutput() return image_out
def VTKInvert(x1,rep=0.0): if type(x1) == np.ndarray: i1 = NumToVTKImage(x1) else: i1 = x1 m = vtk.vtkImageMathematics() m.SetOperationToInvert() m.AddInputData(i1) m.SetConstantC(rep) m.DivideByZeroToCOn() o = m.GetOutput() m.Update() return VTKImageToNum(o)
def MergeLevelSet(self): if self.LevelSets == None: self.LevelSets = self.LevelSetsOutput else: minFilter = vtk.vtkImageMathematics() minFilter.SetOperationToMin() minFilter.SetInput1Data(self.LevelSets) minFilter.SetInput2Data(self.LevelSetsOutput) minFilter.Update() self.LevelSets = minFilter.GetOutput()
def MergeLevelSets(self): if self.MergedInitialLevelSets == None: self.MergedInitialLevelSets = vtk.vtkImageData() self.MergedInitialLevelSets.DeepCopy(self.InitialLevelSets) else: minFilter = vtk.vtkImageMathematics() minFilter.SetOperationToMin() minFilter.SetInput1Data(self.MergedInitialLevelSets) minFilter.SetInput2Data(self.InitialLevelSets) minFilter.Update() self.MergedInitialLevelSets = minFilter.GetOutput()
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._imageMathSubtractH = vtk.vtkImageMathematics() self._imageMathSubtractH.SetOperationToAddConstant() self._reconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D() # second input is marker self._reconstruct.SetInput(1, self._imageMathSubtractH.GetOutput()) self._imageMathSubtractR = vtk.vtkImageMathematics() self._imageMathSubtractR.SetOperationToSubtract() self._imageMathSubtractR.SetInput(1, self._reconstruct.GetOutput()) module_utils.setup_vtk_object_progress(self, self._imageMathSubtractH, 'Preparing marker image.') module_utils.setup_vtk_object_progress(self, self._reconstruct, 'Performing reconstruction.') module_utils.setup_vtk_object_progress(self, self._imageMathSubtractR, 'Subtracting reconstruction.') self._config.h = 50 configList = [ ('H-dome height:', 'h', 'base:float', 'text', 'The required difference in brightness between an h-dome and\n' 'its surroundings.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'ImageMath Subtract H' : self._imageMathSubtractH, 'ImageGreyscaleReconstruct3D' : self._reconstruct, 'ImageMath Subtract R' : self._imageMathSubtractR}) self.sync_module_logic_with_config()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) # these will be our markers self._inputPoints = None # we can't connect the image input directly to the masksource, # so we have to keep track of it separately. self._inputImage = None self._inputImageObserverID = None # we need to modify the mask (I) as well. The problem with a # ProgrammableFilter is that you can't request GetOutput() before # the input has been set... self._maskSource = vtk.vtkProgrammableSource() self._maskSource.SetExecuteMethod(self._maskSourceExecute) # we'll use this to synthesise a volume according to the seed points self._markerSource = vtk.vtkProgrammableSource() self._markerSource.SetExecuteMethod(self._markerSourceExecute) # second input is J (the marker) # we'll use this to change the markerImage into something we can use self._imageThreshold = vtk.vtkImageThreshold() # everything equal to or above 1.0 will be "on" self._imageThreshold.ThresholdByUpper(1.0) self._imageThresholdObserverID = self._imageThreshold.AddObserver( 'EndEvent', self._observerImageThreshold) self._viewFrame = self._createViewFrame( {'Module (self)' : self}) # we're not going to give imageErode any input... that's going to # to happen manually in the execute_module function :) self._imageErode = vtk.vtkImageContinuousErode3D() self._imageErode.SetKernelSize(3,3,3) module_utils.setup_vtk_object_progress(self, self._imageErode, 'Performing greyscale 3D erosion') self._sup = vtk.vtkImageMathematics() self._sup.SetOperationToMax() self._sup.SetInput1(self._imageErode.GetOutput()) self._sup.SetInput2(self._maskSource.GetStructuredPointsOutput()) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic()
def GetRawDICOMData(filenames,fileID): print filenames,fileID vtkRealDcmReader = vtk.vtkDICOMImageReader() vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) ) vtkRealDcmReader.Update() vtkRealData = vtk.vtkImageCast() vtkRealData.SetOutputScalarTypeToFloat() vtkRealData.SetInput( vtkRealDcmReader.GetOutput() ) vtkRealData.Update( ) real_image = vtkRealData.GetOutput().GetPointData() real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) vtkImagDcmReader = vtk.vtkDICOMImageReader() vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) ) vtkImagDcmReader.Update() vtkImagData = vtk.vtkImageCast() vtkImagData.SetOutputScalarTypeToFloat() vtkImagData.SetInput( vtkImagDcmReader.GetOutput() ) vtkImagData.Update( ) imag_image = vtkImagData.GetOutput().GetPointData() imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) vtkAppend = vtk.vtkImageAppendComponents() vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() ) vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() ) vtkAppend.Update( ) # write raw data vtkRawData = vtkAppend.GetOutput() vtkRawData.SetSpacing( spacing ) vtkDcmWriter = vtk.vtkDataSetWriter() vtkDcmWriter.SetFileTypeToBinary() vtkDcmWriter.SetFileName("s%d/rawdata.%04d.vtk" % (dirID,fileID) ) vtkDcmWriter.SetInput( vtkRawData ) vtkDcmWriter.Update() # write raw phase data vtkPhase = vtk.vtkImageMathematics() vtkPhase.SetInput1( vtkRealData.GetOutput() ) vtkPhase.SetInput2( vtkImagData.GetOutput() ) vtkPhase.SetOperationToATAN2( ) vtkPhase.Update( ) vtkPhaseData = vtkPhase.GetOutput() vtkPhaseData.SetSpacing( spacing ) vtkDcmWriter = vtk.vtkDataSetWriter() vtkDcmWriter.SetFileTypeToBinary() vtkDcmWriter.SetFileName("s%d/phase.%04d.vtk" % (dirID,fileID) ) vtkDcmWriter.SetInput( vtkPhaseData) vtkDcmWriter.Update() return (real_array,imag_array)
def MergeLevelSet(self): if self.LevelSets == None: self.LevelSets = self.LevelSetsOutput else: minFilter = vtk.vtkImageMathematics() minFilter.SetOperationToMin() minFilter.SetInput1(self.LevelSets) minFilter.SetInput2(self.LevelSetsOutput) minFilter.Update() self.LevelSets = minFilter.GetOutput() if self.LevelSets.GetSource(): self.LevelSets.GetSource().UnRegisterAllOutputs()
def subImage(self, Images2Sub, timep): '''subtract volumes based on indicated postS''' sub_preMat = vtk.vtkImageMathematics() sub_preMat.SetOperationToSubtract() sub_preMat.SetInput1(Images2Sub[timep]) sub_preMat.SetInput2(Images2Sub[0]) sub_preMat.Update() sub_pre = vtk.vtkImageData() sub_pre = sub_preMat.GetOutput() # define image based on subtraction of postS -preS subtractedImage = sub_pre return subtractedImage
def loadTestData(self): self.patienName = 'QIN-HEADNECK-01-0139' #download data and add to dicom database zipFileUrl = 'http://slicer.kitware.com/midas3/download/item/257234/QIN-HEADNECK-01-0139-PET.zip' zipFilePath = self.tempDataDir+'/dicom.zip' zipFileData = self.tempDataDir+'/dicom' expectedNumOfFiles = 545 if not os.access(self.tempDataDir, os.F_OK): os.mkdir(self.tempDataDir) if not os.access(zipFileData, os.F_OK): os.mkdir(zipFileData) dicomWidget = slicer.modules.dicom.widgetRepresentation().self() dicomPluginCheckbox = dicomWidget.detailsPopup.pluginSelector.checkBoxByPlugin dicomPluginStates = {(key,value.checked) for key,value in dicomPluginCheckbox.iteritems()} for cb in dicomPluginCheckbox.itervalues(): cb.checked=False dicomPluginCheckbox['DICOMScalarVolumePlugin'].checked = True # Download, unzip, import, and load data. Verify loaded nodes. loadedNodes = {'vtkMRMLScalarVolumeNode':1} with DICOMUtils.LoadDICOMFilesToDatabase(zipFileUrl, zipFilePath, zipFileData, expectedNumOfFiles, {}, loadedNodes) as success: self.assertTrue(success) print ('loading returned true') self.assertEqual( len( slicer.util.getNodes('vtkMRMLSubjectHierarchyNode*') ), 1 ) imageNode = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLScalarVolumeNode') for key,value in dicomPluginStates: dicomPluginCheckbox[key].checked=value # apply the SUVbw conversion factor and set units and quantity suvNormalizationFactor = 0.00040166400000000007 quantity = slicer.vtkCodedEntry() quantity.SetFromString('CodeValue:126400|CodingSchemeDesignator:DCM|CodeMeaning:Standardized Uptake Value') units = slicer.vtkCodedEntry() units.SetFromString('CodeValue:{SUVbw}g/ml|CodingSchemeDesignator:UCUM|CodeMeaning:Standardized Uptake Value body weight') multiplier = vtk.vtkImageMathematics() multiplier.SetOperationToMultiplyByK() multiplier.SetConstantK(suvNormalizationFactor) multiplier.SetInput1Data(imageNode.GetImageData()) multiplier.Update() imageNode.GetImageData().DeepCopy(multiplier.GetOutput()) imageNode.GetVolumeDisplayNode().SetWindowLevel(6,3) imageNode.GetVolumeDisplayNode().SetAndObserveColorNodeID('vtkMRMLColorTableNodeInvertedGrey') imageNode.SetVoxelValueQuantity(quantity) imageNode.SetVoxelValueUnits(units) return imageNode
def Execute(self): if not self.KSpace: self.PrintError('Error: No input KSpace.') imageMathematics = vtk.vtkImageMathematics() imageMathematics.SetInput(self.KSpace) imageMathematics.SetInput2(self.KSpace2) imageMathematics.SetOperationToSubtract() imageMathematics.Update() imageMagnitude = vtk.vtkImageMagnitude() imageMagnitude.SetInput(imageMathematics.GetOutput()) imageMagnitude.Update() self.ErrorImage = imageMagnitude.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') surfaceModellerFilter = vtk.vtkSurfaceReconstructionFilter() surfaceModellerFilter.SetInputData(self.Surface) surfaceModellerFilter.SetSampleSpacing(self.SampleSpacing) surfaceModellerFilter.SetNeighborhoodSize(40) surfaceModellerFilter.Update() self.Image = surfaceModellerFilter.GetOutput() if self.NegativeInside: negate = vtk.vtkImageMathematics() negate.SetInputData(self.Image) negate.SetConstantK(-1.0) negate.SetOperationToMultiplyByK() negate.Update() self.Image = negate.GetOutput()
def compareVolumes(self, volume1, volume2): subtractFilter = vtk.vtkImageMathematics() subtractFilter.SetOperationToSubtract() subtractFilter.SetInput1Data(volume1.GetImageData()) subtractFilter.SetInput2Data(volume2.GetImageData()) subtractFilter.Update() histogramFilter = vtk.vtkImageAccumulate() histogramFilter.SetComponentSpacing([1,0,0]) histogramFilter.SetInputData(subtractFilter.GetOutput()) histogramFilter.Update() # Both should be zero if generated scanlines == groundtruth maxValue = histogramFilter.GetMax() minValue = histogramFilter.GetMin() if (maxValue[0] == 0 and minValue[0] == 0): return True else: return False
def create_overlay(self, emphysemavalue, severeemphysemavalue): """Creates an overlay for the slice-based volume view 0: no emphysema 1: moderate emphysema 2: severe emphysema """ self._view_frame.SetStatusText("Creating Overlay...") mask = vtk.vtkImageMask() mask2 = vtk.vtkImageMask() threshold = vtk.vtkImageThreshold() threshold2 = vtk.vtkImageThreshold() math=vtk.vtkImageMathematics() mask.SetInput(self.image_data) mask.SetMaskInput(self.mask_data) threshold.SetInput(mask.GetOutput()) threshold.ThresholdByLower(emphysemavalue) threshold.SetOutValue(0) threshold.SetInValue(1) threshold2.SetInput(mask.GetOutput()) threshold2.ThresholdByLower(severeemphysemavalue) threshold2.SetOutValue(1) threshold2.SetInValue(2) math.SetOperationToMultiply() math.SetInput1(threshold.GetOutput()) math.SetInput2(threshold2.GetOutput()) math.Update() overlay = math.GetOutput() self.slice_viewer1.set_overlay_input(None) self.slice_viewer1.set_overlay_input(overlay) self.render() self._view_frame.SetStatusText("Created Overlay")
def TestReadWriteRead(infile, outfile): """Read, write, and re-read a file, return difference.""" inpath = os.path.join(str(VTK_DATA_ROOT), "Data", infile) outpath = os.path.join(str(VTK_TEMP_DIR), outfile) # read a NIFTI file reader = vtk.vtkNIFTIImageReader() reader.SetFileName(inpath) reader.TimeAsVectorOn() reader.Update() writer = vtk.vtkNIFTIImageWriter() writer.SetInputConnection(reader.GetOutputPort()) writer.SetFileName(outpath) # copy most information directoy from the header writer.SetNIFTIHeader(reader.GetNIFTIHeader()) # this information will override the reader's header writer.SetQFac(reader.GetQFac()) writer.SetTimeDimension(reader.GetTimeDimension()) writer.SetQFormMatrix(reader.GetQFormMatrix()) writer.SetSFormMatrix(reader.GetSFormMatrix()) writer.Write() reader2 = vtk.vtkNIFTIImageReader() reader2.SetFileName(outpath) reader2.TimeAsVectorOn() reader2.Update() diff = vtk.vtkImageMathematics() diff.SetOperationToSubtract() diff.SetInputConnection(0,reader.GetOutputPort()) diff.SetInputConnection(1,reader2.GetOutputPort()) diff.Update() diffrange = diff.GetOutput().GetScalarRange() differr = diffrange[0]**2 + diffrange[1]**2 return differr
def execute_module(self): # FIXME: if this module ever becomes anything other than an experiment, build # this logic into yet another ProgrammableSource # make sure marker is up to date self._markerSource.GetStructuredPointsOutput().Update() self._maskSource.GetStructuredPointsOutput().Update() tempJ = vtk.vtkStructuredPoints() tempJ.DeepCopy(self._markerSource.GetStructuredPointsOutput()) self._imageErode.SetInput(tempJ) self._diff = vtk.vtkImageMathematics() self._diff.SetOperationToSubtract() self._accum = vtk.vtkImageAccumulate() self._accum.SetInput(self._diff.GetOutput()) # now begin our loop stable = False while not stable: # do erosion, get supremum of erosion and mask I self._sup.GetOutput().Update() # compare this result with tempJ self._diff.SetInput1(tempJ) self._diff.SetInput2(self._sup.GetOutput()) self._accum.Update() print "%f == %f ?" % (self._accum.GetMin()[0], self._accum.GetMax()[0]) if abs(self._accum.GetMin()[0] - self._accum.GetMax()[0]) < 0.0001: stable = True else: # not stable yet... print "Trying again..." tempJ.DeepCopy(self._sup.GetOutput())
def Execute(self): if self.Image == None: self.PrintError('Error: no Image.') cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() self.Image = cast.GetOutput() if self.NegateImage: scalarRange = self.Image.GetScalarRange() negate = vtk.vtkImageMathematics() negate.SetInputData(self.Image) negate.SetOperationToMultiplyByK() negate.SetConstantK(-1.0) negate.Update() shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputConnection(negate.GetOutputPort()) shiftScale.SetShift(scalarRange[1]+scalarRange[0]) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() self.Image = shiftScale.GetOutput() if self.Interactive: if not self.vmtkRenderer: self.vmtkRenderer = vmtkscripts.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) if not self.ImageSeeder: self.ImageSeeder = vmtkscripts.vmtkImageSeeder() self.ImageSeeder.vmtkRenderer = self.vmtkRenderer self.ImageSeeder.Image = self.Image self.ImageSeeder.Display = 0 self.ImageSeeder.Execute() ##self.ImageSeeder.Display = 1 self.ImageSeeder.BuildView() if not self.SurfaceViewer: self.SurfaceViewer = vmtkscripts.vmtkSurfaceViewer() self.SurfaceViewer.vmtkRenderer = self.vmtkRenderer initializationMethods = { '0': self.CollidingFrontsInitialize, '1': self.FastMarchingInitialize, '2': self.ThresholdInitialize, '3': self.IsosurfaceInitialize, '4': self.SeedInitialize } endInitialization = False while not endInitialization: queryString = 'Please choose initialization type: \n 0: colliding fronts;\n 1: fast marching;\n 2: threshold;\n 3: isosurface;\n 4: seed\n ' initializationType = self.InputText(queryString,self.InitializationTypeValidator) initializationMethods[initializationType]() self.DisplayLevelSetSurface(self.InitialLevelSets) queryString = 'Accept initialization? (y/n): ' inputString = self.InputText(queryString,self.YesNoValidator) if inputString == 'y': self.MergeLevelSets() self.DisplayLevelSetSurface(self.MergedInitialLevelSets) queryString = 'Initialize another branch? (y/n): ' inputString = self.InputText(queryString,self.YesNoValidator) if inputString == 'y': endInitialization = False elif inputString == 'n': endInitialization = True self.InitialLevelSets = self.MergedInitialLevelSets self.MergedInitialLevelSets = None else: if self.Method == "collidingfronts": self.CollidingFrontsInitialize() elif self.Method == "fastmarching": self.FastMarchingInitialize() elif self.Method == "threshold": self.ThresholdInitialize() elif self.Method == "isosurface": self.IsosurfaceInitialize() elif self.Method == "seeds": self.SeedInitialize() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def CollidingFrontsInitialize(self): self.PrintLog('Colliding fronts initialization.') seedIds1 = vtk.vtkIdList() seedIds2 = vtk.vtkIdList() if self.Interactive: queryString = "Please input lower threshold (\'n\' for none): " self.LowerThreshold = self.ThresholdInput(queryString) queryString = "Please input upper threshold (\'n\' for none): " self.UpperThreshold = self.ThresholdInput(queryString) queryString = 'Please place two seeds' seeds = self.SeedInput(queryString,2) seedIds1.InsertNextId(self.Image.FindPoint(seeds.GetPoint(0))) seedIds2.InsertNextId(self.Image.FindPoint(seeds.GetPoint(1))) else: seedIds1.InsertNextId(self.Image.ComputePointId([self.SourcePoints[0],self.SourcePoints[1],self.SourcePoints[2]])) seedIds2.InsertNextId(self.Image.ComputePointId([self.TargetPoints[0],self.TargetPoints[1],self.TargetPoints[2]])) scalarRange = self.Image.GetScalarRange() thresholdedImage = self.Image if (self.LowerThreshold is not None) | (self.UpperThreshold is not None): threshold = vtk.vtkImageThreshold() threshold.SetInputData(self.Image) if (self.LowerThreshold is not None) & (self.UpperThreshold is not None): threshold.ThresholdBetween(self.LowerThreshold,self.UpperThreshold) elif (self.LowerThreshold is not None): threshold.ThresholdByUpper(self.LowerThreshold) elif (self.UpperThreshold is not None): threshold.ThresholdByLower(self.UpperThreshold) threshold.ReplaceInOff() threshold.ReplaceOutOn() threshold.SetOutValue(scalarRange[0] - scalarRange[1]) threshold.Update() scalarRange = threshold.GetOutput().GetScalarRange() thresholdedImage = threshold.GetOutput() scale = 1.0 if scalarRange[1]-scalarRange[0] > 0.0: scale = 1.0 / (scalarRange[1]-scalarRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(thresholdedImage) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() speedImage = shiftScale.GetOutput() collidingFronts = vtkvmtk.vtkvmtkCollidingFrontsImageFilter() collidingFronts.SetInputData(speedImage) collidingFronts.SetSeeds1(seedIds1) collidingFronts.SetSeeds2(seedIds2) collidingFronts.ApplyConnectivityOn() collidingFronts.StopOnTargetsOn() collidingFronts.Update() subtract = vtk.vtkImageMathematics() subtract.SetInputConnection(collidingFronts.GetOutputPort()) subtract.SetOperationToAddConstant() subtract.SetConstantC(-10.0 * collidingFronts.GetNegativeEpsilon()) subtract.Update() self.InitialLevelSets = vtk.vtkImageData() self.InitialLevelSets.DeepCopy(subtract.GetOutput()) self.IsoSurfaceValue = 0.0
def FastMarchingInitialize(self): self.PrintLog('Fast marching initialization.') sourceSeedIds = vtk.vtkIdList() targetSeedIds = vtk.vtkIdList() if self.Interactive: queryString = "Please input lower threshold (\'n\' for none): " self.LowerThreshold = self.ThresholdInput(queryString) queryString = "Please input upper threshold (\'n\' for none): " self.UpperThreshold = self.ThresholdInput(queryString) queryString = 'Please place source seeds' sourceSeeds = self.SeedInput(queryString,0) queryString = 'Please place target seeds' targetSeeds = self.SeedInput(queryString,0) for i in range(sourceSeeds.GetNumberOfPoints()): sourceSeedIds.InsertNextId(self.Image.FindPoint(sourceSeeds.GetPoint(i))) for i in range(targetSeeds.GetNumberOfPoints()): targetSeedIds.InsertNextId(self.Image.FindPoint(targetSeeds.GetPoint(i))) else: for i in range(len(self.SourcePoints)/3): sourceSeedIds.InsertNextId(self.Image.ComputePointId([self.SourcePoints[3*i+0],self.SourcePoints[3*i+1],self.SourcePoints[3*i+2]])) for i in range(len(self.TargetPoints)/3): targetSeedIds.InsertNextId(self.Image.ComputePointId([self.TargetPoints[3*i+0],self.TargetPoints[3*i+1],self.TargetPoints[3*i+2]])) scalarRange = self.Image.GetScalarRange() thresholdedImage = self.Image if (self.LowerThreshold is not None) | (self.UpperThreshold is not None): threshold = vtk.vtkImageThreshold() threshold.SetInputData(self.Image) if (self.LowerThreshold is not None) & (self.UpperThreshold is not None): threshold.ThresholdBetween(self.LowerThreshold,self.UpperThreshold) elif (self.LowerThreshold is not None): threshold.ThresholdByUpper(self.LowerThreshold) elif (self.UpperThreshold is not None): threshold.ThresholdByLower(self.UpperThreshold) threshold.ReplaceInOff() threshold.ReplaceOutOn() threshold.SetOutValue(scalarRange[0] - scalarRange[1]) threshold.Update() scalarRange = threshold.GetOutput().GetScalarRange() thresholdedImage = threshold.GetOutput() scale = 1.0 if scalarRange[1]-scalarRange[0] > 0.0: scale = 1.0 / (scalarRange[1]-scalarRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(thresholdedImage) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() speedImage = shiftScale.GetOutput() fastMarching = vtkvmtk.vtkvmtkFastMarchingUpwindGradientImageFilter() fastMarching.SetInputData(speedImage) fastMarching.SetSeeds(sourceSeedIds) fastMarching.GenerateGradientImageOff() fastMarching.SetTargetOffset(100.0) fastMarching.SetTargets(targetSeedIds) if targetSeedIds.GetNumberOfIds() > 0: fastMarching.SetTargetReachedModeToOneTarget() else: fastMarching.SetTargetReachedModeToNoTargets() fastMarching.Update() subtract = vtk.vtkImageMathematics() subtract.SetInputConnection(fastMarching.GetOutputPort()) subtract.SetOperationToAddConstant() subtract.SetConstantC(-fastMarching.GetTargetValue()) subtract.Update() self.InitialLevelSets = vtk.vtkImageData() self.InitialLevelSets.DeepCopy(subtract.GetOutput()) self.IsoSurfaceValue = 0.0