def computeStatistics(self, segmentID): import vtkSegmentationCorePython as vtkSegmentationCore requestedKeys = self.getRequestedKeys() segmentationNode = slicer.mrmlScene.GetNodeByID( self.getParameterNode().GetParameter("Segmentation")) if len(requestedKeys) == 0: return {} containsLabelmapRepresentation = segmentationNode.GetSegmentation( ).ContainsRepresentation( vtkSegmentationCore.vtkSegmentationConverter. GetSegmentationBinaryLabelmapRepresentationName()) if not containsLabelmapRepresentation: return {} segmentLabelmap = slicer.vtkOrientedImageData() segmentationNode.GetBinaryLabelmapRepresentation( segmentID, segmentLabelmap) if (not segmentLabelmap or not segmentLabelmap.GetPointData() or not segmentLabelmap.GetPointData().GetScalars()): # No input label data return {} # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(segmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) thresh.Update() # Use binary labelmap as a stencil stencil = vtk.vtkImageToImageStencil() stencil.SetInputData(thresh.GetOutput()) stencil.ThresholdByUpper(labelValue) stencil.Update() stat = vtk.vtkImageAccumulate() stat.SetInputData(thresh.GetOutput()) stat.SetStencilData(stencil.GetOutput()) stat.Update() # Add data to statistics list cubicMMPerVoxel = reduce(lambda x, y: x * y, segmentLabelmap.GetSpacing()) ccPerCubicMM = 0.001 stats = {} if "voxel_count" in requestedKeys: stats["voxel_count"] = stat.GetVoxelCount() if "volume_mm3" in requestedKeys: stats["volume_mm3"] = stat.GetVoxelCount() * cubicMMPerVoxel if "volume_cm3" in requestedKeys: stats["volume_cm3"] = stat.GetVoxelCount( ) * cubicMMPerVoxel * ccPerCubicMM return stats
def TestMarching(atlas): reader = vtk.vtkNIFTIImageReader() reader.SetFileName(atlas) reader.Update() image = reader.GetOutput() # threshold threshold = vtk.vtkImageThreshold() threshold.SetInputData(image) threshold.ThresholdBetween(60,60) threshold.ReplaceOutOn() threshold.SetOutValue(0) threshold.Update() image1 = threshold.GetOutput() marching = vtk.vtkMarchingCubes() marching.SetInputData(image1) marching.SetValue(0,60) marching.Update() area = marching.GetOutput() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("test") colors.InsertNextTupleValue([0,1,1]) area.GetCellData().SetScalars(colors) # visualization print "visualizing..." mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(area) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() window.SetInteractor(interactor) window.Render() interactor.Start()
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 onApply(self): # Make sure the user wants to do the operation, even if the segment is not visible if not self.scriptedEffect.confirmCurrentSegmentVisible(): return self.scriptedEffect.saveStateForUndo() # Get modifier labelmap and parameters modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() marginSizeMM = self.scriptedEffect.doubleParameter("MarginSizeMm") # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(selectedSegmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) if (marginSizeMM < 0): # The distance filter used in the margin filter starts at zero at the border voxels, # so if we need to shrink the margin, it is more accurate to invert the labelmap and # use positive distance when calculating the margin thresh.SetInValue(labelValue) thresh.SetOutValue(backgroundValue) import vtkITK margin = vtkITK.vtkITKImageMargin() margin.SetInputConnection(thresh.GetOutputPort()) margin.CalculateMarginInMMOn() margin.SetOuterMarginMM(abs(marginSizeMM)) margin.Update() if marginSizeMM >= 0: modifierLabelmap.ShallowCopy(margin.GetOutput()) else: # If we are shrinking then the result needs to be inverted. thresh = vtk.vtkImageThreshold() thresh.SetInputData(margin.GetOutput()) thresh.ThresholdByLower(0) thresh.SetInValue(labelValue) thresh.SetOutValue(backgroundValue) thresh.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) thresh.Update() modifierLabelmap.ShallowCopy(thresh.GetOutput()) # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap( modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) qt.QApplication.restoreOverrideCursor()
def __init__(self): self.lookupTable = vtk.vtkLookupTable() self.lookupTable.SetRampToLinear() self.lookupTable.SetNumberOfTableValues(2) self.lookupTable.SetTableRange(0, 1) self.lookupTable.SetTableValue(0, 0, 0, 0, 0) self.colorMapper = vtk.vtkImageMapToRGBA() self.colorMapper.SetOutputFormatToRGBA() self.colorMapper.SetLookupTable(self.lookupTable) self.thresholdFilter = vtk.vtkImageThreshold() self.thresholdFilter.SetInValue(1) self.thresholdFilter.SetOutValue(0) self.thresholdFilter.SetOutputScalarTypeToUnsignedChar() # Feedback actor self.mapper = vtk.vtkImageMapper() self.dummyImage = vtk.vtkImageData() self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1) self.mapper.SetInputData(self.dummyImage) self.actor = vtk.vtkActor2D() self.actor.VisibilityOff() self.actor.SetMapper(self.mapper) self.mapper.SetColorWindow(255) self.mapper.SetColorLevel(128) # Setup pipeline self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort()) self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
def onApply(self): try: # Get master volume image data import vtkSegmentationCore masterImageData = vtkSegmentationCore.vtkOrientedImageData() self.scriptedEffect.masterVolumeImageData(masterImageData) # Get edited labelmap editedLabelmap = self.scriptedEffect.parameterSetNode().GetEditedLabelmap() # Get parameters min = self.scriptedEffect.doubleParameter("MinimumThreshold") max = self.scriptedEffect.doubleParameter("MaximumThreshold") # Save state for undo #TODO: #self.undoRedo.saveState() # Perform thresholding thresh = vtk.vtkImageThreshold() thresh.SetInputData(masterImageData) thresh.ThresholdBetween(min, max) thresh.SetInValue(1) thresh.SetOutValue(0) thresh.SetOutputScalarType(editedLabelmap.GetScalarType()) thresh.Update() editedLabelmap.DeepCopy(thresh.GetOutput()) except IndexError: logging.error('apply: Failed to threshold master volume!') pass # Notify editor about changes. # This needs to be called so that the changes are written back to the edited segment self.scriptedEffect.apply() # De-select effect self.scriptedEffect.selectEffect("")
def splitPerStructureVolumes(masterNode, mergeNode): """Make a separate label map node for each non-empty label value in the merged label map""" colorNode = mergeNode.GetDisplayNode().GetColorNode() accum = vtk.vtkImageAccumulate() accum.SetInputConnection(mergeNode.GetImageDataConnection()) accum.Update() lo = int(accum.GetMin()[0]) hi = int(accum.GetMax()[0]) thresholder = vtk.vtkImageThreshold() for index in xrange(lo,hi+1): logging.info( "Splitting label %d..."%index ) thresholder.SetInputConnection( mergeNode.GetImageDataConnection() ) thresholder.SetInValue( index ) thresholder.SetOutValue( 0 ) thresholder.ReplaceInOn() thresholder.ReplaceOutOn() thresholder.ThresholdBetween( index, index ) thresholder.SetOutputScalarType( mergeNode.GetImageData().GetScalarType() ) thresholder.Update() if thresholder.GetOutput().GetScalarRange() != (0.0, 0.0): structureName = colorNode.GetColorName(index) logging.info( "Creating structure volume %s..."%structureName ) structureVolume = EditUtil.structureVolume( masterNode, structureName ) if not structureVolume: EditUtil.addStructure( masterNode, mergeNode, index ) structureVolume = EditUtil.structureVolume( masterNode, structureName ) structureVolume.GetImageData().DeepCopy( thresholder.GetOutput() ) EditUtil.markVolumeNodeAsModified(structureVolume)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageThreshold(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def onApply(self): try: # Get master volume image data import vtkSegmentationCorePython as vtkSegmentationCore masterImageData = self.scriptedEffect.masterVolumeImageData() # Get modifier labelmap modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() originalImageToWorldMatrix = vtk.vtkMatrix4x4() modifierLabelmap.GetImageToWorldMatrix(originalImageToWorldMatrix) # Get parameters min = self.scriptedEffect.doubleParameter("MinimumThreshold") max = self.scriptedEffect.doubleParameter("MaximumThreshold") self.scriptedEffect.saveStateForUndo() # Perform thresholding thresh = vtk.vtkImageThreshold() thresh.SetInputData(masterImageData) thresh.ThresholdBetween(min, max) thresh.SetInValue(1) thresh.SetOutValue(0) thresh.SetOutputScalarType(modifierLabelmap.GetScalarType()) thresh.Update() modifierLabelmap.DeepCopy(thresh.GetOutput()) except IndexError: logging.error('apply: Failed to threshold master volume!') pass # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) # De-select effect self.scriptedEffect.selectEffect("")
def __init__(self): """ Initialization """ self.defaultLower = 128 self.defaultUpper = 255 self.thresholdInitialized = False lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageThreshold() self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.origCtf = None self.ignoreObjects = 1 self.descs = { "ReplaceInValue": "Value for voxels inside thresholds", "ReplaceOutValue": "Value for voxels outside thresholds", "ReplaceIn": "Inside thresholds", "ReplaceOut": "Outside thresholds", "LowerThreshold": "Lower Threshold", "UpperThreshold": "Upper threshold", "Demonstrate": "Use lookup table to demonstrate effect" } self.filterDesc = "Separates the image pixels/voxels into two classes, foreground and background, using thresholds specified by the user\nInput: Grayscale image\nOutput: Binary image"
def getImageMask(inputVtkImageData): """ @type inputVtkImageData: C{vtkImageData} @param inputVtkImageData: Image data to be normalized @rtype: C{vtkImageData} @return: Normalized (0-1) image data """ t = vtk.vtkImageThreshold() #t.ThresholdBetween(1,255) t.ThresholdByUpper(114) t.ReplaceInOn() t.SetReplaceIn(0) t.ReplaceOutOn() t.SetReplaceOut(255) t.SetInput(inputVtkImageData) norm = vtk.vtkImageNormalize() norm.SetInput(t.GetOutput()) #norm.SetInput(inputVtkImageData) norm.Update() d = vtk.vtkImageDilateErode3D() d.SetKernelSize(4,4,4) d.SetDilateValue(1) d.SetErodeValue(0) d.SetInput(norm.GetOutput()) return d.GetOutput()
def createSTL(mha, stl): reader = vtk.vtkMetaImageReader() reader.SetFileName(mha) reader.Update() threshold = vtk.vtkImageThreshold() threshold.SetInputConnection(reader.GetOutputPort()) threshold.ThresholdByLower(0.1) threshold.ReplaceInOn() threshold.SetInValue(0) # set all values below 0.1 to 0 threshold.ReplaceOutOn() threshold.SetOutValue(1) # set all values above 0.1 to 1 threshold.Update() dmc = vtk.vtkFlyingEdges3D() dmc.SetInputConnection(threshold.GetOutputPort()) dmc.ComputeNormalsOn() dmc.GenerateValues(1, 1, 1) dmc.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(dmc.GetOutputPort()) smoother.SetNumberOfIterations(15) smoother.BoundarySmoothingOff() smoother.Update() writer = vtk.vtkSTLWriter() writer.SetInputConnection(smoother.GetOutputPort()) writer.SetFileTypeToBinary() writer.SetFileName(stl) writer.Write() return 0
def onApply(self): import vtkSegmentationCorePython as vtkSegmentationCore # Get modifier labelmap and parameters operation = self.scriptedEffect.parameter("Operation") if operation in self.operationsRequireModifierSegment: # Get modifier segment segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode() segmentation = segmentationNode.GetSegmentation() modifierSegmentID = self.modifierSegmentID() if not modifierSegmentID: logging.error("Operation {0} requires a selected modifier segment".format(operation)) return modifierSegment = segmentation.GetSegment(modifierSegmentID) modifierSegmentLabelmap = modifierSegment.GetRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()) if operation == LOGICAL_COPY: self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierSegmentLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) elif operation == LOGICAL_UNION: self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierSegmentLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeAdd) elif operation == LOGICAL_SUBTRACT: self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierSegmentLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeRemove) elif operation == LOGICAL_INTERSECT: selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() intersectionLabelmap = vtkSegmentationCore.vtkOrientedImageData() vtkSegmentationCore.vtkOrientedImageDataResample.MergeImage(selectedSegmentLabelmap, modifierSegmentLabelmap, intersectionLabelmap, vtkSegmentationCore.vtkOrientedImageDataResample.OPERATION_MINIMUM, selectedSegmentLabelmap.GetExtent()) selectedSegmentLabelmapExtent = selectedSegmentLabelmap.GetExtent() modifierSegmentLabelmapExtent = modifierSegmentLabelmap.GetExtent() commonExtent = [max(selectedSegmentLabelmapExtent[0], modifierSegmentLabelmapExtent[0]), min(selectedSegmentLabelmapExtent[1], modifierSegmentLabelmapExtent[1]), max(selectedSegmentLabelmapExtent[2], modifierSegmentLabelmapExtent[2]), min(selectedSegmentLabelmapExtent[3], modifierSegmentLabelmapExtent[3]), max(selectedSegmentLabelmapExtent[4], modifierSegmentLabelmapExtent[4]), min(selectedSegmentLabelmapExtent[5], modifierSegmentLabelmapExtent[5])] self.scriptedEffect.modifySelectedSegmentByLabelmap(intersectionLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet, commonExtent) elif operation == LOGICAL_INVERT: selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() inverter = vtk.vtkImageThreshold() inverter.SetInputData(selectedSegmentLabelmap) inverter.SetInValue(1) inverter.SetOutValue(0) inverter.ReplaceInOn() inverter.ThresholdByLower(0) inverter.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) inverter.Update() selectedSegmentLabelmap.DeepCopy(inverter.GetOutput()) self.scriptedEffect.modifySelectedSegmentByLabelmap(selectedSegmentLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) elif operation == LOGICAL_CLEAR or operation == LOGICAL_FILL: selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() vtkSegmentationCore.vtkOrientedImageDataResample.FillImage(selectedSegmentLabelmap, 1 if operation == LOGICAL_FILL else 0, selectedSegmentLabelmap.GetExtent()) self.scriptedEffect.modifySelectedSegmentByLabelmap(selectedSegmentLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) else: logging.error("Uknown operation: {0}".format(operation))
def CreateFrogActor(fileName, tissue): reader = vtk.vtkMetaImageReader() reader.SetFileName(fileName) reader.Update() selectTissue = vtk.vtkImageThreshold() selectTissue.ThresholdBetween(tissue, tissue) selectTissue.SetInValue(255) selectTissue.SetOutValue(0) selectTissue.SetInputConnection(reader.GetOutputPort()) isoValue = 63.5 mcubes = vtk.vtkMarchingCubes() mcubes.SetInputConnection(selectTissue.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOn() mcubes.SetValue(0, isoValue) stripper = vtk.vtkStripper() stripper.SetInputConnection(mcubes.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def __init__(self): self.lookupTable = vtk.vtkLookupTable() self.lookupTable.SetRampToLinear() self.lookupTable.SetNumberOfTableValues(2) self.lookupTable.SetTableRange(0, 1) self.lookupTable.SetTableValue(0, 0, 0, 0, 0) self.colorMapper = vtk.vtkImageMapToRGBA() self.colorMapper.SetOutputFormatToRGBA() self.colorMapper.SetLookupTable(self.lookupTable) self.thresholdFilter = vtk.vtkImageThreshold() self.thresholdFilter.SetInValue(1) self.thresholdFilter.SetOutValue(0) self.thresholdFilter.SetOutputScalarTypeToUnsignedChar() # Feedback actor self.mapper = vtk.vtkImageMapper() self.dummyImage = vtk.vtkImageData() self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1) self.mapper.SetInputData(self.dummyImage) self.actor = vtk.vtkActor2D() self.actor.VisibilityOff() self.actor.SetMapper(self.mapper) self.mapper.SetColorWindow(255) self.mapper.SetColorLevel(128) # Setup pipeline self.colorMapper.SetInputConnection( self.thresholdFilter.GetOutputPort()) self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
def createMeshfromVTKMask(self, imMask): """ Takes a binary mask image and makes it a vtkPolyData VOI_mesh """ # Create a binary Image with 0-255 image_VOIlesion = vtk.vtkImageThreshold() image_VOIlesion.ThresholdByUpper(0.1) image_VOIlesion.SetInValue(255) image_VOIlesion.SetOutValue(0) image_VOIlesion.SetInput(imMask) image_VOIlesion.Update() # Convert VOIlesion into polygonal struct VOIlesion_poly = vtk.vtkMarchingCubes() VOIlesion_poly.SetValue(0, 125) VOIlesion_poly.SetInput(image_VOIlesion.GetOutput()) VOIlesion_poly.ComputeNormalsOff() VOIlesion_poly.Update() # Recalculate num_voxels and vol_lesion on VOI nvoxels = VOIlesion_poly.GetOutput().GetNumberOfCells() npoints = VOIlesion_poly.GetOutput().GetNumberOfPoints() print "Number of points: %d" % npoints print "Number of cells: %d" % nvoxels # prepare output meshlesion3D = VOIlesion_poly.GetOutput() return meshlesion3D
def create_frog_actor(file_name, tissue, use_flying_edges): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) iso_value = 63.5 if use_flying_edges: try: iso_surface = vtk.vtkFlyingEdges3D() except AttributeError: iso_surface = vtk.vtkMarchingCubes() else: iso_surface = vtk.vtkMarchingCubes() iso_surface.SetInputConnection(select_tissue.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOn() iso_surface.SetValue(0, iso_value) stripper = vtk.vtkStripper() stripper.SetInputConnection(iso_surface.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def TestSection_TestSharedLabelmapMultipleLayerEditing(self): self.segmentation.RemoveAllSegments() self.segmentation.AddEmptySegment("Segment_1") self.segmentation.AddEmptySegment("Segment_2") mergedLabelmap = vtkSegmentationCore.vtkOrientedImageData() mergedLabelmap.SetExtent(0, 10, 0, 10, 0, 10) mergedLabelmap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) threshold = vtk.vtkImageThreshold() threshold.SetInputData(mergedLabelmap) threshold.ThresholdBetween(vtk.VTK_UNSIGNED_CHAR_MIN, vtk.VTK_UNSIGNED_CHAR_MAX) threshold.SetInValue(1) threshold.SetOutValue(0) threshold.Update() mergedLabelmap.ShallowCopy(threshold.GetOutput()) self.segmentEditorNode.SetSelectedSegmentID("Segment_1") self.paintEffect.modifySelectedSegmentByLabelmap(mergedLabelmap, self.paintEffect.ModificationModeAdd) self.segmentEditorNode.SetSelectedSegmentID("Segment_2") self.paintEffect.modifySelectedSegmentByLabelmap(mergedLabelmap, self.paintEffect.ModificationModeAdd) layerCount = self.segmentation.GetNumberOfLayers() self.assertEqual(layerCount, 1) self.segmentEditorNode.SetOverwriteMode(self.segmentEditorNode.OverwriteNone) self.segmentEditorNode.SetSelectedSegmentID("Segment_1") self.paintEffect.modifySelectedSegmentByLabelmap(mergedLabelmap, self.paintEffect.ModificationModeAdd) layerCount = self.segmentation.GetNumberOfLayers() self.assertEqual(layerCount, 2) logging.info('Multiple layer editing successful')
def ROIfromImages(self,inputImage,ROIImage,radius,iterations,connectivity,newROI): #TODO: sistemare valori #col=self.ROI.GetDisplayNode().GetColorNode() bg=0 fg=1 if newROI: #slicer.util.delayDisplay('thresholding...') thresh = vtk.vtkImageThreshold() thresh.SetInputData(inputImage) lo, hi = inputImage.GetScalarRange() min=lo + 0.25 * (hi-lo) max=hi thresh.ThresholdBetween(min, max) thresh.SetInValue(fg) thresh.SetOutValue(bg) thresh.SetOutputScalarType(ROIImage.GetScalarType()) thresh.Modified() thresh.Update() ROIImage.DeepCopy(thresh.GetOutput()) try: self.markVolumeNodeAsModified(self.ROI) except: pass if radius>0: ImageBuffer = vtk.vtkImageData() ImageBuffer.DeepCopy(ROIImage) eroder = slicer.vtkImageErodeExt() eroder.SetInputData(ROIImage) eroder.SetOutput(ImageBuffer) #slicer.util.delayDisplay('create kernel') #eroder.SetForeground(fg) eroder.SetbutForeground(True) eroder.SetBackground(bg) eroder.setRadius(radius,radius,1) if connectivity==0: eroder.SetNeighborTo8() elif connectivity==1: eroder.SetNeighborTo4() else: eroder.setConnectivity2D() for f in range(1,int(ROIImage.GetScalarRange()[1]+1)): eroder.SetForeground(f) #slicer.util.delayDisplay('eroding label = ' + str(f)) for n in range(iterations): ImageBuffer.DeepCopy(ROIImage) eroder.Update() ROIImage.DeepCopy(ImageBuffer) eroder.SetOutput(None)
def threshold(self, above=None, below=None, replaceWith=0): """ Binary or continuous volume thresholding. Find the voxels that contain a value above/below the input values and replace them with a new value (default is 0). """ th = vtk.vtkImageThreshold() th.SetInputData(self.imagedata()) if above is not None and below is not None: if above < below: th.ThresholdBetween(above, below) th.SetInValue(replaceWith) elif above == below: return self else: th.SetReplaceOut(True) th.SetOutValue(replaceWith) th.ThresholdBetween(below, above) elif above is not None: th.ThresholdByUpper(above) th.SetInValue(replaceWith) elif below is not None: th.ThresholdByLower(below) th.SetInValue(replaceWith) th.Update() return self._update(th.GetOutput())
def onApply(self): try: # Get master volume image data import vtkSegmentationCorePython as vtkSegmentationCore masterImageData = self.scriptedEffect.masterVolumeImageData() # Get modifier labelmap modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() originalImageToWorldMatrix = vtk.vtkMatrix4x4() modifierLabelmap.GetImageToWorldMatrix(originalImageToWorldMatrix) # Get parameters min = self.scriptedEffect.doubleParameter("MinimumThreshold") max = self.scriptedEffect.doubleParameter("MaximumThreshold") self.scriptedEffect.saveStateForUndo() # Perform thresholding thresh = vtk.vtkImageThreshold() thresh.SetInputData(masterImageData) thresh.ThresholdBetween(min, max) thresh.SetInValue(1) thresh.SetOutValue(0) thresh.SetOutputScalarType(modifierLabelmap.GetScalarType()) thresh.Update() modifierLabelmap.DeepCopy(thresh.GetOutput()) except IndexError: logging.error('apply: Failed to threshold master volume!') pass # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap( modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) # De-select effect self.scriptedEffect.selectEffect("")
def CreateFrogActor(fileName, tissue): #reader = vtk.vtkMetaImageReader() reader = vtk.vtkXMLImageDataReader() reader.SetFileName(fileName) reader.Update() selectTissue = vtk.vtkImageThreshold() #selectTissue.ThresholdBetween(tissue, tissue) selectTissue.ThresholdBetween(120, 125) selectTissue.SetInValue(255) selectTissue.SetOutValue(0) selectTissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(selectTissue.GetOutputPort()) isoValue = 130 mcubes = vtk.vtkMarchingCubes() #mcubes.SetInputConnection(gaussian.GetOutputPort()) mcubes.SetInputConnection(reader.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOff() mcubes.SetValue(0, isoValue) smoothingIterations = 5 passBand = 0.001 featureAngle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(mcubes.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(featureAngle) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(featureAngle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def thresholdByUpper(image,threshold=1,invalue=255,outvalue=0): image2 = vtk.vtkImageThreshold() image2.SetInput(image) image2.ThresholdByUpper(threshold) image2.SetInValue(invalue) image2.SetOutValue(outvalue) image2.Update() return image2.GetOutput()
def onApply(self): # Make sure the user wants to do the operation, even if the segment is not visible if not self.scriptedEffect.confirmCurrentSegmentVisible(): return self.scriptedEffect.saveStateForUndo() # Get modifier labelmap and parameters modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(selectedSegmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) shellMode = self.scriptedEffect.parameter("ShellMode") shellThicknessMM = abs( self.scriptedEffect.doubleParameter("ShellThicknessMm")) import vtkITK margin = vtkITK.vtkITKImageMargin() margin.SetInputConnection(thresh.GetOutputPort()) margin.CalculateMarginInMMOn() spacing = selectedSegmentLabelmap.GetSpacing() voxelDiameter = min(selectedSegmentLabelmap.GetSpacing()) if shellMode == MEDIAL_SURFACE: margin.SetOuterMarginMM(0.5 * shellThicknessMM) margin.SetInnerMarginMM(-0.5 * shellThicknessMM + 0.5 * voxelDiameter) elif shellMode == INSIDE_SURFACE: margin.SetOuterMarginMM(shellThicknessMM + 0.1 * voxelDiameter) margin.SetInnerMarginMM( 0.0 + 0.1 * voxelDiameter) # Don't include the original border (0.0) elif shellMode == OUTSIDE_SURFACE: margin.SetOuterMarginMM(0.0) margin.SetInnerMarginMM(-shellThicknessMM + voxelDiameter) modifierLabelmap.DeepCopy(margin.GetOutput()) # This can be a long operation - indicate it to the user qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor) margin.Update() modifierLabelmap.ShallowCopy(margin.GetOutput()) # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap( modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) qt.QApplication.restoreOverrideCursor()
def create_marching_cube(data, color, opacity=0.5, min_threshold=0, smoothing_iterations=None, spacing=[1., 1., 1.]): im = vtk.vtkImageData() I, J, K = data.shape[:3] im.SetDimensions(I, J, K) im.SetSpacing(spacing[0], spacing[1], spacing[2]) im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) vol = np.swapaxes(data, 0, 2) vol = np.ascontiguousarray(vol) vol = vol.ravel() uchar_array = numpy_support.numpy_to_vtk(vol, deep=0) im.GetPointData().SetScalars(uchar_array) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(im) mapper.Update() threshold = vtk.vtkImageThreshold() threshold.SetInputData(im) threshold.ThresholdByLower(min_threshold) threshold.ReplaceInOn() threshold.SetInValue(0) threshold.ReplaceOutOn() threshold.SetOutValue(1) threshold.Update() dmc = vtk.vtkDiscreteMarchingCubes() dmc.SetInputConnection(threshold.GetOutputPort()) dmc.GenerateValues(1, 1, 1) dmc.Update() mapper = vtk.vtkPolyDataMapper() if smoothing_iterations is not None: smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(dmc.GetOutputPort()) smoother.SetNumberOfIterations(smoothing_iterations) smoother.Update() mapper.SetInputConnection(smoother.GetOutputPort()) else: mapper.SetInputConnection(dmc.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) mapper.ScalarVisibilityOff() actor.GetProperty().SetColor(color) actor.GetProperty().SetOpacity(opacity) return actor
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageThreshold(), 'Processing.', ('vtkImageData', ), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def imagethresholdupper(image, t, invalue=1.0): """Thresholds values equal or greater than t.""" tfilter = vtk.vtkImageThreshold() tfilter.SetInput(image) tfilter.ThresholdByUpper(t) tfilter.SetOutValue(0.0) tfilter.SetInValue(invalue) tfilter.Update() return tfilter.GetOutput()
def computeStatistics(self, segmentID): import vtkSegmentationCorePython as vtkSegmentationCore requestedKeys = self.getRequestedKeys() segmentationNode = slicer.mrmlScene.GetNodeByID(self.getParameterNode().GetParameter("Segmentation")) if len(requestedKeys)==0: return {} containsLabelmapRepresentation = segmentationNode.GetSegmentation().ContainsRepresentation( vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()) if not containsLabelmapRepresentation: return {} segment = segmentationNode.GetSegmentation().GetSegment(segmentID) segBinaryLabelName = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName() segmentLabelmap = segment.GetRepresentation(segBinaryLabelName) if (not segmentLabelmap or not segmentLabelmap.GetPointData() or not segmentLabelmap.GetPointData().GetScalars()): # No input label data return {} # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(segmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) thresh.Update() # Use binary labelmap as a stencil stencil = vtk.vtkImageToImageStencil() stencil.SetInputData(thresh.GetOutput()) stencil.ThresholdByUpper(labelValue) stencil.Update() stat = vtk.vtkImageAccumulate() stat.SetInputData(thresh.GetOutput()) stat.SetStencilData(stencil.GetOutput()) stat.Update() # Add data to statistics list cubicMMPerVoxel = reduce(lambda x,y: x*y, segmentLabelmap.GetSpacing()) ccPerCubicMM = 0.001 stats = {} if "voxel_count" in requestedKeys: stats["voxel_count"] = stat.GetVoxelCount() if "volume_mm3" in requestedKeys: stats["volume_mm3"] = stat.GetVoxelCount() * cubicMMPerVoxel if "volume_cm3" in requestedKeys: stats["volume_cm3"] = stat.GetVoxelCount() * cubicMMPerVoxel * ccPerCubicMM return stats
def getLabelStats(self, image, roi, labelStats): # instantiate results dictionary labelStats["Image"].append(image.GetName()) # copied/modified from labelstatistics module # determine volume of a voxel and conversion factor to cubed centimeters cubicMMPerVoxel = reduce(lambda x, y: x * y, roi.GetSpacing()) ccPerCubicMM = 0.001 # calculate the min and max of the roi image stataccum = vtk.vtkImageAccumulate() stataccum.SetInputConnection(roi.GetImageDataConnection()) stataccum.Update() lo = int(stataccum.GetMin()[0]) hi = int(stataccum.GetMax()[0]) # iterate through all the labels in the image for i in xrange(lo, hi + 1): # threshold roi image thresholder = vtk.vtkImageThreshold() thresholder.SetInputConnection(roi.GetImageDataConnection()) thresholder.SetInValue(1) thresholder.SetOutValue(0) thresholder.ReplaceOutOn() thresholder.ThresholdBetween(i, i) thresholder.SetOutputScalarType( image.GetImageData().GetScalarType()) thresholder.Update() # use vtk's statistics class with the binary labelmap as a stencil stencil = vtk.vtkImageToImageStencil() stencil.SetInputConnection(thresholder.GetOutputPort()) stencil.ThresholdBetween(1, 1) stat1 = vtk.vtkImageAccumulate() stat1.SetInputConnection(image.GetImageDataConnection()) stencil.Update() stat1.SetStencilData(stencil.GetOutput()) stat1.Update() # gather stats if count is greater than zero if stat1.GetVoxelCount() > 0: # add an entry to the LabelStats list labelStats["Labels"].append(i) labelStats[image.GetName(), i, "Image"] = image.GetName() labelStats[image.GetName(), i, "Index"] = i labelStats[image.GetName(), i, "Count"] = stat1.GetVoxelCount() labelStats[image.GetName(), i, "Volume mm^3"] = labelStats[ image.GetName(), i, "Count"] * cubicMMPerVoxel labelStats[image.GetName(), i, "Volume cc"] = labelStats[ image.GetName(), i, "Volume mm^3"] * ccPerCubicMM labelStats[image.GetName(), i, "Min"] = stat1.GetMin()[0] labelStats[image.GetName(), i, "Max"] = stat1.GetMax()[0] labelStats[image.GetName(), i, "Mean"] = stat1.GetMean()[0] labelStats[image.GetName(), i, "StdDev"] = stat1.GetStandardDeviation()[0] return hi
def imagethresholdbetween(image, t1, t2, invalue=1.0): """Thresholds an image between t1 and t2.""" tfilter = vtk.vtkImageThreshold() tfilter.SetInput(image) tfilter.ThresholdBetween(t1, t2) tfilter.SetOutValue(0.0) tfilter.SetInValue(invalue) tfilter.Update() return tfilter.GetOutput()
def create_smooth_frog_actor(file_name, tissue): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(select_tissue.GetOutputPort()) isoValue = 63.5 iso_surface = vtk.vtkFlyingEdges3D() iso_surface.SetInputConnection(gaussian.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOff() iso_surface.SetValue(0, isoValue) smoothing_iterations = 20 pass_band = 0.001 feature_angle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(iso_surface.GetOutputPort()) smoother.SetNumberOfIterations(smoothing_iterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(feature_angle) smoother.SetPassBand(pass_band) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOff() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(feature_angle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def growCut(self): growCutFilter = vtkITK.vtkITKGrowCutSegmentationImageFilter() background = self.getScopedBackground() gestureInput = self.getScopedLabelInput() growCutOutput = self.getScopedLabelOutput() if not self.areInputsValid(): logging.warning(self.getInvalidInputsMessage()) # set the make a zero-valued volume for the output # TODO: maybe this should be done in numpy as a one-liner thresh = vtk.vtkImageThreshold() thresh.ReplaceInOn() thresh.ReplaceOutOn() thresh.SetInValue(0) thresh.SetOutValue(0) thresh.SetOutputScalarType( vtk.VTK_SHORT ) if vtk.VTK_MAJOR_VERSION <= 5: thresh.SetInput( gestureInput ) else: thresh.SetInputData( gestureInput ) thresh.SetOutput( growCutOutput ) thresh.Update() growCutOutput.DeepCopy( gestureInput ) if vtk.VTK_MAJOR_VERSION <= 5: growCutFilter.SetInput( 0, background ) growCutFilter.SetInput( 1, gestureInput ) growCutFilter.SetInput( 2, growCutOutput ) else: growCutFilter.SetInputData( 0, background ) growCutFilter.SetInputData( 1, gestureInput ) growCutFilter.SetInputConnection( 2, thresh.GetOutputPort() ) objectSize = 5. # TODO: this is a magic number contrastNoiseRatio = 0.8 # TODO: this is a magic number priorStrength = 0.003 # TODO: this is a magic number segmented = 2 # TODO: this is a magic number conversion = 1000 # TODO: this is a magic number spacing = gestureInput.GetSpacing() voxelVolume = reduce(lambda x,y: x*y, spacing) voxelAmount = objectSize / voxelVolume voxelNumber = round(voxelAmount) * conversion cubeRoot = 1./3. oSize = int(round(pow(voxelNumber,cubeRoot))) growCutFilter.SetObjectSize( oSize ) growCutFilter.SetContrastNoiseRatio( contrastNoiseRatio ) growCutFilter.SetPriorSegmentConfidence( priorStrength ) growCutFilter.Update() growCutOutput.DeepCopy( growCutFilter.GetOutput() ) self.applyScopedLabel()
def threshold_data(reader, value, min, max): threshold = vtk.vtkImageThreshold() threshold.SetInputConnection(reader.GetOutputPort()) threshold.ThresholdByLower(value) #th threshold.ReplaceInOn() threshold.SetInValue(min) # set all values below th to 0 threshold.ReplaceOutOn() threshold.SetOutValue(max) # set all values above th to 1 threshold.Update() return threshold
def setupIslandLabelmap(self, labelmap, extent, value=1): labelmap.SetExtent(extent) labelmap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) threshold = vtk.vtkImageThreshold() threshold.SetInputData(labelmap) threshold.ThresholdBetween(0,0) threshold.SetInValue(value) threshold.SetOutValue(value) threshold.Update() labelmap.ShallowCopy(threshold.GetOutput())
def preview(self, color=None): if not self.editUtil.getBackgroundImage( ) or not self.editUtil.getLabelImage(): return # # make a lookup table where inside the threshold is opaque and colored # by the label color, while the background is transparent (black) # - apply the threshold operation to the currently visible background # (output of the layer logic's vtkImageReslice instance) # if not color: color = self.getPaintColor if not self.lut: self.lut = vtk.vtkLookupTable() self.lut.SetRampToLinear() self.lut.SetNumberOfTableValues(2) self.lut.SetTableRange(0, 1) self.lut.SetTableValue(0, 0, 0, 0, 0) r, g, b, a = color self.lut.SetTableValue(1, r, g, b, a) if not self.map: self.map = vtk.vtkImageMapToRGBA() self.map.SetOutputFormatToRGBA() self.map.SetLookupTable(self.lut) if not self.thresh: self.thresh = vtk.vtkImageThreshold() sliceLogic = self.sliceWidget.sliceLogic() backgroundLogic = sliceLogic.GetBackgroundLayer() if vtk.VTK_MAJOR_VERSION <= 5: self.thresh.SetInput(backgroundLogic.GetReslice().GetOutput()) else: self.thresh.SetInputConnection( backgroundLogic.GetReslice().GetOutputPort()) self.thresh.ThresholdBetween(self.min, self.max) self.thresh.SetInValue(1) self.thresh.SetOutValue(0) self.thresh.SetOutputScalarTypeToUnsignedChar() if vtk.VTK_MAJOR_VERSION <= 5: self.map.SetInput(self.thresh.GetOutput()) self.map.Update() self.cursorMapper.SetInput(self.map.GetOutput()) else: self.map.SetInputConnection(self.thresh.GetOutputPort()) self.cursorMapper.SetInputConnection(self.map.GetOutputPort()) self.cursorActor.VisibilityOn() self.sliceView.scheduleRender()
def _write_output(self, data, target_file_path): #Check for existing target file, and ask for overwrite confirmation if required if (not self._config.overwrite) and os.path.exists(target_file_path): dlg = wx.MessageDialog( self._view_frame, "%s already exists! \nOverwrite?" % target_file_path, "File already exists", wx.YES_NO | wx.NO_DEFAULT) if dlg.ShowModal() == wx.ID_NO: print 'Skipped writing %s' % target_file_path if self._config.delete_after_conversion: print 'Source %s not deleted, since no output was written' % source_file_path return #skip this file if overwrite is denied writer = None if self._config.target_file_type == 0: # VTI writer = vtk.vtkXMLImageDataWriter() elif self._config.target_file_type == 1: # MHA writer = vtk.vtkMetaImageWriter() writer.SetCompression(True) writer.SetFileDimensionality(3) elif self._config.target_file_type == 2: # MHD writer = vtk.vtkMetaImageWriter() writer.SetCompression(False) writer.SetFileDimensionality(3) elif self._config.target_file_type == 3: # GIPL. We assume floating point values. if self._config.target_numerical_type == 1: #float writer = itk.ImageFileWriter.IF3.New() elif self._config.target_numerical_type == 2: #short writer = itk.ImageFileWriter.ISS3.New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char writer = itk.ImageFileWriter.IUC3.New() else: raise Exception( 'Writing ITK %s is not currently supported.' % data_types_by_number[self._config.source_file_type]) else: raise Exception('Undefined file type with numerical index %d' % self._config.target_file_type) final_data = data if self._config.target_numerical_type == 4: th = vtk.vtkImageThreshold() th.ThresholdByLower(0.0) th.SetInValue(0.0) th.SetOutValue(1.0) th.SetOutputScalarTypeToUnsignedChar() th.SetInput(data) th.Update() final_data = th.GetOutput() #Write the output writer.SetInput(final_data) writer.SetFileName(target_file_path) print "Writing %s ..." % target_file_path writer.Write()
def maskVolumeWithSegment(self, segmentationNode, segmentID, operationMode, fillValues, inputVolumeNode, outputVolumeNode): """ Fill voxels of the input volume inside/outside the masking model with the provided fill value """ segmentIDs = vtk.vtkStringArray() segmentIDs.InsertNextValue(segmentID) maskVolumeNode = slicer.modules.volumes.logic().CreateAndAddLabelVolume(inputVolumeNode, "TemporaryVolumeMask") if not maskVolumeNode: logging.error("maskVolumeWithSegment failed: invalid maskVolumeNode") return False if not slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsToLabelmapNode(segmentationNode, segmentIDs, maskVolumeNode, inputVolumeNode): logging.error("maskVolumeWithSegment failed: ExportSegmentsToLabelmapNode error") slicer.mrmlScene.RemoveNode(maskVolumeNode.GetDisplayNode().GetColorNode()) slicer.mrmlScene.RemoveNode(maskVolumeNode.GetDisplayNode()) slicer.mrmlScene.RemoveNode(maskVolumeNode) return False maskToStencil = vtk.vtkImageToImageStencil() maskToStencil.ThresholdByLower(0) maskToStencil.SetInputData(maskVolumeNode.GetImageData()) stencil = vtk.vtkImageStencil() if operationMode == "FILL_INSIDE_AND_OUTSIDE": # Set input to constant value thresh = vtk.vtkImageThreshold() thresh.SetInputData(inputVolumeNode.GetImageData()) thresh.ThresholdByLower(0) thresh.SetInValue(fillValues[1]) thresh.SetOutValue(fillValues[1]) thresh.SetOutputScalarType(inputVolumeNode.GetImageData().GetScalarType()) thresh.Update() stencil.SetInputData(thresh.GetOutput()) else: stencil.SetInputData(inputVolumeNode.GetImageData()) stencil.SetStencilConnection(maskToStencil.GetOutputPort()) stencil.SetReverseStencil(operationMode == "FILL_OUTSIDE") stencil.SetBackgroundValue(fillValues[0]) stencil.Update() outputVolumeNode.SetAndObserveImageData(stencil.GetOutput()) # Set the same geometry and parent transform as the input volume ijkToRas = vtk.vtkMatrix4x4() inputVolumeNode.GetIJKToRASMatrix(ijkToRas) outputVolumeNode.SetIJKToRASMatrix(ijkToRas) inputVolumeNode.SetAndObserveTransformNodeID(inputVolumeNode.GetTransformNodeID()) slicer.mrmlScene.RemoveNode(maskVolumeNode.GetDisplayNode().GetColorNode()) slicer.mrmlScene.RemoveNode(maskVolumeNode.GetDisplayNode()) slicer.mrmlScene.RemoveNode(maskVolumeNode) return True
def applyThreshold(labelNode, outValue): imageData = labelNode.GetImageData() backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(imageData) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(outValue) thresh.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) thresh.Update() labelNode.SetAndObserveImageData(thresh.GetOutput())
def __init__(self, img, threshold, xysmoothing, zsmoothing, color, alpha): dataImporter = vtk.vtkImageImport() simg = np.ascontiguousarray(img, np.uint8) dataImporter.CopyImportVoidPointer(simg.data, len(simg.data)) dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) dataImporter.SetWholeExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) self.__smoother = vtk.vtkImageGaussianSmooth() self.__smoother.SetStandardDeviation(xysmoothing, xysmoothing, zsmoothing) self.__smoother.SetInputConnection(dataImporter.GetOutputPort()) self.__threshold = vtk.vtkImageThreshold() self.__threshold.SetInputConnection(self.__smoother.GetOutputPort()) self.__threshold.ThresholdByUpper(threshold) self.__threshold.ReplaceInOn() self.__threshold.SetInValue(1) self.__threshold.ReplaceOutOn() self.__threshold.SetOutValue(0) self.__threshold.Update() contour = vtk.vtkDiscreteMarchingCubes() contour.SetInputConnection(self.__threshold.GetOutputPort()) contour.ComputeNormalsOn() contour.SetValue(0, 1) contour.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(contour.GetOutputPort()) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() triangleCellNormals=vtk.vtkPolyDataNormals() triangleCellNormals.SetInputConnection(smoother.GetOutputPort()) triangleCellNormals.ComputeCellNormalsOn() triangleCellNormals.ComputePointNormalsOff() triangleCellNormals.ConsistencyOn() triangleCellNormals.AutoOrientNormalsOn() triangleCellNormals.Update() triangleCellAn = vtk.vtkMeshQuality() triangleCellAn.SetInputConnection(triangleCellNormals.GetOutputPort()) triangleCellAn.SetTriangleQualityMeasureToArea() triangleCellAn.SaveCellQualityOn() triangleCellAn.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(triangleCellAn.GetOutputPort()) mapper.ScalarVisibilityOn() mapper.SetScalarRange(.3, 1) mapper.SetScalarModeToUsePointData() colorLookupTable = vtk.vtkLookupTable() colorLookupTable.SetHueRange(.6, 1) colorLookupTable.Build() mapper.SetLookupTable(colorLookupTable) self.SetMapper(mapper) self.GetProperty().SetColor(*color) self.GetProperty().SetOpacity(alpha)
def preview(self,color=None): if not self.editUtil.getBackgroundImage() or not self.editUtil.getLabelImage(): return # # make a lookup table where inside the threshold is opaque and colored # by the label color, while the background is transparent (black) # - apply the threshold operation to the currently visible background # (output of the layer logic's vtkImageReslice instance) # if not color: color = self.getPaintColor if not self.lut: self.lut = vtk.vtkLookupTable() self.lut.SetRampToLinear() self.lut.SetNumberOfTableValues( 2 ) self.lut.SetTableRange( 0, 1 ) self.lut.SetTableValue( 0, 0, 0, 0, 0 ) r,g,b,a = color self.lut.SetTableValue( 1, r, g, b, a ) if not self.map: self.map = vtk.vtkImageMapToRGBA() self.map.SetOutputFormatToRGBA() self.map.SetLookupTable( self.lut ) if not self.thresh: self.thresh = vtk.vtkImageThreshold() sliceLogic = self.sliceWidget.sliceLogic() backgroundLogic = sliceLogic.GetBackgroundLayer() if vtk.VTK_MAJOR_VERSION <= 5: self.thresh.SetInput( backgroundLogic.GetReslice().GetOutput() ) else: self.thresh.SetInputConnection( backgroundLogic.GetReslice().GetOutputPort() ) self.thresh.ThresholdBetween( self.min, self.max ) self.thresh.SetInValue( 1 ) self.thresh.SetOutValue( 0 ) self.thresh.SetOutputScalarTypeToUnsignedChar() if vtk.VTK_MAJOR_VERSION <= 5: self.map.SetInput( self.thresh.GetOutput() ) self.map.Update() self.cursorMapper.SetInput( self.map.GetOutput() ) else: self.map.SetInputConnection( self.thresh.GetOutputPort() ) self.cursorMapper.SetInputConnection( self.map.GetOutputPort() ) self.cursorActor.VisibilityOn() self.sliceView.scheduleRender()
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 threshold(image, lowerThreshold, upperThreshold): thresh = vtk.vtkImageThreshold() thresh.SetInputData(image) thresh.ThresholdBetween(lowerThreshold, upperThreshold) thresh.ReplaceInOn() thresh.SetInValue(1) thresh.ReplaceOutOn() thresh.SetOutValue(0) thresh.Update() return thresh.GetOutput()
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 onGradientInNewVolBtnClicked(self): # Result is not right! volumeNode = slicer.util.getNode("MRHead") ijkToRas = vtk.vtkMatrix4x4() volumeNode.GetIJKToRASMatrix(ijkToRas) imageData = volumeNode.GetImageData() extent = imageData.GetExtent() imageSize = imageData.GetDimensions() imageSpacing = imageData.GetSpacing() voxelType = vtk.VTK_FLOAT # Create empty image volume imageData_2 = vtk.vtkImageData() imageData_2.SetDimensions(imageSize[0] / 2, imageSize[1] / 2, imageSize[2] / 2) imageData_2.SetSpacing(imageSpacing) imageData_2.AllocateScalars(voxelType, 0) thresholder = vtk.vtkImageThreshold() thresholder.SetInputData(imageData_2) thresholder.SetInValue(0) thresholder.SetOutValue(0) volumeNode_2 = slicer.vtkMRMLScalarVolumeNode() volumeNode_2.SetSpacing(imageSpacing) volumeNode_2.SetImageDataConnection(thresholder.GetOutputPort()) # Add volume to scene scene = slicer.mrmlScene scene.AddNode(volumeNode_2) displayNode = slicer.vtkMRMLScalarVolumeDisplayNode() scene.AddNode(displayNode) colorNode = slicer.util.getNode("Grey") displayNode.SetAndObserveColorNodeID(colorNode.GetID()) volumeNode_2.SetAndObserveDisplayNodeID(displayNode.GetID()) volumeNode_2.CreateDefaultStorageNode() # npData = slicer.util.array('MRHead') impVol = vtk.vtkImplicitVolume() impVol.SetVolume(imageData) for k in xrange(extent[4], extent[5] / 2 + 1): for j in xrange(extent[2], extent[3] / 2 + 1): for i in xrange(extent[0], extent[1] / 2 + 1): g = impVol.FunctionGradient(i, j, k) gradient = math.sqrt(g[0] ** 2 + g[1] ** 2 + g[2] ** 2) imageData_2.SetScalarComponentFromFloat(i, j, k, 0, gradient) imageData_2.Modified()
def buildSimpleLabelMap(self, image, inValue, outValue): threshold = vtk.vtkImageThreshold() threshold.SetInputData(image) threshold.ThresholdByLower(0) threshold.ReplaceInOn() threshold.ReplaceOutOn() threshold.SetOutValue(outValue) threshold.SetInValue(inValue) threshold.Update() outVolumeData = vtk.vtkImageData() outVolumeData.DeepCopy(threshold.GetOutput()) return outVolumeData
def ImageThreshold(self, image, threshold_value): """Threshold an image""" image.SetReleaseDataFlag(1) _filter = vtk.vtkImageThreshold() _filter.ReplaceInOn() _filter.ReplaceOutOn() _filter.SetInValue(1) _filter.SetOutValue(0) _filter.SetOutputScalarType(3) _filter.SetInput(image.GetRealImage()) _filter.ThresholdByUpper(threshold_value) _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent) _filter.SetProgressText("Thresholding...") logging.info("Image thresholded") return MVImage.MVImage(_filter.GetOutputPort(), input=image)
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') thresholdFilter = vtk.vtkImageThreshold() thresholdFilter.SetInputData(self.Image) thresholdFilter.ThresholdByUpper(self.Threshold) thresholdFilter.ReplaceInOn() thresholdFilter.ReplaceOutOn() thresholdFilter.SetInValue(self.UpperLabel) thresholdFilter.SetOutValue(self.LowerLabel) thresholdFilter.SetOutputScalarTypeToShort() thresholdFilter.Update() self.Image = thresholdFilter.GetOutput()
def split(self): """split the merge volume into individual structures""" self.statusText( "Splitting..." ) merge = self.merge if not merge: return colorNode = merge.GetDisplayNode().GetColorNode() accum = vtk.vtkImageAccumulate() if vtk.VTK_MAJOR_VERSION <= 5: accum.SetInput(merge.GetImageData()) else: accum.SetInputConnection(merge.GetImageDataConnection()) accum.Update() lo = int(accum.GetMin()[0]) hi = int(accum.GetMax()[0]) # TODO: pending resolution of bug 1822, run the thresholding # in single threaded mode to avoid data corruption observed on mac release # builds thresholder = vtk.vtkImageThreshold() thresholder.SetNumberOfThreads(1) for i in xrange(lo,hi+1): self.statusText( "Splitting label %d..."%i ) if vtk.VTK_MAJOR_VERSION <= 5: thresholder.SetInput( merge.GetImageData() ) else: thresholder.SetInputConnection( merge.GetImageDataConnection() ) thresholder.SetInValue( i ) thresholder.SetOutValue( 0 ) thresholder.ReplaceInOn() thresholder.ReplaceOutOn() thresholder.ThresholdBetween( i, i ) thresholder.SetOutputScalarType( merge.GetImageData().GetScalarType() ) thresholder.Update() if thresholder.GetOutput().GetScalarRange() != (0.0, 0.0): labelName = colorNode.GetColorName(i) self.statusText( "Creating structure volume %s..."%labelName ) structureVolume = self.structureVolume( labelName ) if not structureVolume: self.addStructure( i, "noEdit" ) structureVolume = self.structureVolume( labelName ) structureVolume.GetImageData().DeepCopy( thresholder.GetOutput() ) EditUtil.markVolumeNodeAsModified(structureVolume) self.statusText( "Finished splitting." )
def calculateFrontAndRear(self, reader, maxPush, minPush): """ Method to calculate front and rear of objects in the track Image parameter must be vtkImageData """ spacing = [] for i in range(len(self.voxelSize)): spacing.append(self.voxelSize[i] / self.voxelSize[0]) for tp in range(self.mintp, self.maxtp + 1): label = self.values[tp] com1 = self.points[tp] if tp == self.maxtp: # Use latest direction for i in range(len(direction)): direction[i] *= -1.0 else: com2 = self.points[tp+1] direction = [] for i in range(len(com1)): direction.append(com2[i] - com1[i]) # Polygon data image = reader.getDataSet(tp) objThreshold = vtk.vtkImageThreshold() objThreshold.SetInput(image) objThreshold.SetOutputScalarTypeToUnsignedChar() objThreshold.SetInValue(255) objThreshold.SetOutValue(0) objThreshold.ThresholdBetween(label,label) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInput(objThreshold.GetOutput()) marchingCubes.SetValue(0, 255) marchingCubes.Update() polydata = marchingCubes.GetOutput() polydata.Update() front = self.locateOutmostPoint(polydata, com1, direction, maxPush, minPush) for i in range(len(direction)): direction[i] *= -1.0 rear = self.locateOutmostPoint(polydata, com1, direction, maxPush, minPush) for i in range(len(front)): front[i] /= spacing[i] rear[i] /= spacing[i] self.fronts[tp] = tuple(front) self.rears[tp] = tuple(rear)
def ensureInSegment(self, image, lesionMesh, pathSegment, nameSegment, image_pos_pat, image_ori_pat): # Proceed to build reference frame for display objects based on DICOM coords [transformed_image, transform_cube] = self.loadDisplay.dicomTransform(image, image_pos_pat, image_ori_pat) dataToStencil = vtk.vtkPolyDataToImageStencil() dataToStencil.SetInput(lesionMesh) dataToStencil.SetOutputOrigin(transformed_image.GetOrigin()) print transformed_image.GetOrigin() dataToStencil.SetOutputSpacing(transformed_image.GetSpacing()) print transformed_image.GetSpacing() dataToStencil.SetOutputWholeExtent(transformed_image.GetExtent()) dataToStencil.Update() stencil = vtk.vtkImageStencil() stencil.SetInput(transformed_image) stencil.SetStencil(dataToStencil.GetOutput()) stencil.ReverseStencilOff() stencil.SetBackgroundValue(0.0) stencil.Update() newSegment = vtk.vtkMetaImageWriter() newSegment.SetFileName(pathSegment+'/'+nameSegment+'.mhd') newSegment.SetInput(stencil.GetOutput()) newSegment.Write() thresh = vtk.vtkImageThreshold() thresh.SetInput(stencil.GetOutput()) thresh.ThresholdByUpper(1) thresh.SetInValue(255) thresh.SetOutValue(0) thresh.Update() contouriso = vtk.vtkMarchingCubes() contouriso.SetInput(thresh.GetOutput()) contouriso.SetValue(0,125) contouriso.ComputeScalarsOn() contouriso.Update() # Recalculate num_voxels and vol_lesion on VOI nvoxels = contouriso.GetOutput().GetNumberOfCells() npoints = contouriso.GetOutput().GetNumberOfPoints() print "Number of points: %d" % npoints print "Number of cells: %d" % nvoxels return contouriso.GetOutput()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # 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) self._dualGreyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D() # first input is I (the modified mask) self._dualGreyReconstruct.SetDual(1) self._dualGreyReconstruct.SetInput1(self._maskSource.GetStructuredPointsOutput()) # 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) self._dualGreyReconstruct.SetInput2(self._markerSource.GetStructuredPointsOutput()) # 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) module_utils.setup_vtk_object_progress( self, self._dualGreyReconstruct, "Performing dual greyscale reconstruction" ) NoConfigModuleMixin.__init__( self, {"Module (self)": self, "vtkImageGreyscaleReconstruct3D": self._dualGreyReconstruct} ) self.sync_module_logic_with_config()
def onApply(self): self.scriptedEffect.saveStateForUndo() # Get modifier labelmap and parameters modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() marginSizeMm = self.scriptedEffect.doubleParameter("MarginSizeMm") kernelSizePixel = self.getKernelSizePixel() # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(selectedSegmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) erodeDilate = vtk.vtkImageDilateErode3D() erodeDilate.SetInputConnection(thresh.GetOutputPort()) if marginSizeMm>0: # grow erodeDilate.SetDilateValue(labelValue) erodeDilate.SetErodeValue(backgroundValue) else: # shrink erodeDilate.SetDilateValue(backgroundValue) erodeDilate.SetErodeValue(labelValue) # This can be a long operation - indicate it to the user qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor) erodeDilate.SetKernelSize(kernelSizePixel[0],kernelSizePixel[1],kernelSizePixel[2]) erodeDilate.Update() modifierLabelmap.DeepCopy(erodeDilate.GetOutput()) # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet) qt.QApplication.restoreOverrideCursor()
def apply(self): if not self.editUtil.getBackgroundImage() or not self.editUtil.getLabelImage(): return node = self.editUtil.getParameterNode() self.undoRedo.saveState() thresh = vtk.vtkImageThreshold() thresh.SetInputData( self.editUtil.getBackgroundImage() ) thresh.ThresholdBetween(self.min, self.max) thresh.SetInValue( self.editUtil.getLabel() ) thresh.SetOutValue( 0 ) thresh.SetOutputScalarType( self.editUtil.getLabelImage().GetScalarType() ) # $this setProgressFilter $thresh "Threshold" thresh.Update() self.editUtil.getLabelImage().DeepCopy( thresh.GetOutput() ) self.editUtil.markVolumeNodeAsModified(self.editUtil.getLabelVolume())
def onNewVolBtnClicked(self): imageSize = [128] * 3 imageSpacing = [1.0] * 3 voxelType = vtk.VTK_UNSIGNED_CHAR # Create an empty image volume imageData = vtk.vtkImageData() imageData.SetDimensions(imageSize) imageData.AllocateScalars(voxelType, 64) thresholder = vtk.vtkImageThreshold() thresholder.SetInputData(imageData) thresholder.SetInValue(0) thresholder.SetOutValue(0) # Create volume node volumeNode = slicer.vtkMRMLScalarVolumeNode() volumeNode.SetSpacing(imageSpacing) volumeNode.SetImageDataConnection(thresholder.GetOutputPort()) # Add volume to scene scene = slicer.mrmlScene scene.AddNode(volumeNode) displayNode = slicer.vtkMRMLScalarVolumeDisplayNode() scene.AddNode(displayNode) colorNode = slicer.util.getNode("Grey") displayNode.SetAndObserveColorNodeID(colorNode.GetID()) volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID()) volumeNode.CreateDefaultStorageNode() # Show the new volume in the Slice view applicationLogic = slicer.app.applicationLogic() selectionNode = applicationLogic.GetSelectionNode() selectionNode.SetSecondaryVolumeID(volumeNode.GetID()) applicationLogic.PropagateForegroundVolumeSelection(0) # Center the 3D View on the scene # It works only after showing the 3D scene layoutManager = slicer.app.layoutManager() threeDWidget = layoutManager.threeDWidget(0) threeDView = threeDWidget.threeDView() threeDView.resetFocalPoint()
def getInvertedBinaryLabelmap(self, modifierLabelmap): import vtkSegmentationCorePython as vtkSegmentationCore fillValue = 1 eraseValue = 0 inverter = vtk.vtkImageThreshold() inverter.SetInputData(modifierLabelmap) inverter.SetInValue(fillValue) inverter.SetOutValue(eraseValue) inverter.ReplaceInOn() inverter.ThresholdByLower(0) inverter.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) inverter.Update() invertedModifierLabelmap = vtkSegmentationCore.vtkOrientedImageData() invertedModifierLabelmap.ShallowCopy(inverter.GetOutput()) imageToWorldMatrix = vtk.vtkMatrix4x4() modifierLabelmap.GetImageToWorldMatrix(imageToWorldMatrix) invertedModifierLabelmap.SetGeometryFromImageToWorldMatrix(imageToWorldMatrix) return invertedModifierLabelmap
def __init__(self): """ Initialization """ self.defaultLower = 128 self.defaultUpper = 255 self.thresholdInitialized = False lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageThreshold() self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.origCtf = None self.ignoreObjects = 1 self.descs = {"ReplaceInValue": "Value for voxels inside thresholds", "ReplaceOutValue": "Value for voxels outside thresholds", "ReplaceIn": "Inside thresholds", "ReplaceOut": "Outside thresholds", "LowerThreshold": "Lower Threshold", "UpperThreshold": "Upper threshold", "Demonstrate": "Use lookup table to demonstrate effect"} self.filterDesc = "Separates the image pixels/voxels into two classes, foreground and background, using thresholds specified by the user\nInput: Grayscale image\nOutput: Binary image"
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._image_threshold = vtk.vtkImageThreshold() # seedconnect wants unsigned char at input self._image_threshold.SetOutputScalarTypeToUnsignedChar() self._image_threshold.SetInValue(1) self._image_threshold.SetOutValue(0) self._seed_connect = vtk.vtkImageSeedConnectivity() self._seed_connect.SetInputConnectValue(1) self._seed_connect.SetOutputConnectedValue(1) self._seed_connect.SetOutputUnconnectedValue(0) self._seed_connect.SetInput(self._image_threshold.GetOutput()) module_utils.setup_vtk_object_progress(self, self._seed_connect, 'Performing region growing') module_utils.setup_vtk_object_progress(self, self._image_threshold, 'Thresholding data') # we'll use this to keep a binding (reference) to the passed object self._input_points = None # this will be our internal list of points self._seed_points = [] self._config._thresh_interval = 5 config_list = [ ('Auto threshold interval:', '_thresh_interval', 'base:float', 'text', 'Used to calculate automatic threshold (unit %).')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkImageSeedConnectivity' : self._seed_connect, 'vtkImageThreshold' : self._image_threshold}) self.sync_module_logic_with_config()