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( ) vtkDcmWriter = vtk.vtkDataSetWriter() vtkDcmWriter.SetFileName("rawdata.%04d.vtk" % fileID ) vtkDcmWriter.SetInput(vtkAppend.GetOutput()) vtkDcmWriter.Update() return (real_array,imag_array)
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 execute(self, inputs, update = 0, last = 0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None image = self.getInput(1) origType = image.GetScalarType() cast1 = vtk.vtkImageCast() cast1.SetInput(image) cast1.SetOutputScalarTypeToShort() # vtkImageCityBlockDistance requires short input self.vtkfilter.SetInput(cast1.GetOutput()) data = self.vtkfilter.GetOutput() if self.parameters["CastToOriginal"]: cast = vtk.vtkImageCast() cast.SetInput(self.vtkfilter.GetOutput()) cast.SetOutputScalarType(origType) cast.SetClampOverflow(1) data = cast.GetOutput() if update: self.vtkfilter.Update() return data
def onApply(self): # This can be a long operation - indicate it to the user qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor) self.scriptedEffect.saveStateForUndo() # Get parameters fullyConnected = self.scriptedEffect.integerParameter("FullyConnected") minimumSize = self.scriptedEffect.integerParameter("MinimumSize") # Get modifier labelmap selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() castIn = vtk.vtkImageCast() castIn.SetInputData(selectedSegmentLabelmap) castIn.SetOutputScalarTypeToUnsignedLong() # Identify the islands in the inverted volume and # find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() islandMath.SetInputConnection(castIn.GetOutputPort()) islandMath.SetFullyConnected(fullyConnected) islandMath.SetMinimumSize(minimumSize) # Note that island operation happens in unsigned long space # but the segment editor works in unsigned char castOut = vtk.vtkImageCast() castOut.SetInputConnection(islandMath.GetOutputPort()) castOut.SetOutputScalarTypeToUnsignedChar() castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount logging.info("%d islands created (%d ignored)" % (islandCount, ignoredIslands)) # Create oriented image data from output import vtkSegmentationCorePython as vtkSegmentationCore multiLabelImage = vtkSegmentationCore.vtkOrientedImageData() multiLabelImage.DeepCopy(castOut.GetOutput()) selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4() selectedSegmentLabelmap.GetImageToWorldMatrix( selectedSegmentLabelmapImageToWorldMatrix) multiLabelImage.SetGeometryFromImageToWorldMatrix( selectedSegmentLabelmapImageToWorldMatrix) # Import multi-label labelmap to segmentation segmentationNode = self.scriptedEffect.parameterSetNode( ).GetSegmentationNode() selectedSegmentID = self.scriptedEffect.parameterSetNode( ).GetSelectedSegmentID() selectedSegmentName = segmentationNode.GetSegmentation().GetSegment( selectedSegmentID).GetName() slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode( \ multiLabelImage, segmentationNode, selectedSegmentName ) segmentationNode.GetSegmentation().RemoveSegment(selectedSegmentID) qt.QApplication.restoreOverrideCursor()
def onApply(self): # TODO: # self.logic.undoRedo = self.undoRedo # Get parameters fullyConnected = self.scriptedEffect.integerParameter("FullyConnected") minimumSize = self.scriptedEffect.integerParameter("MinimumSize") # Get modifier labelmap selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() castIn = vtk.vtkImageCast() castIn.SetInputData(selectedSegmentLabelmap) castIn.SetOutputScalarTypeToUnsignedLong() # Identify the islands in the inverted volume and # find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() islandMath.SetInputConnection(castIn.GetOutputPort()) islandMath.SetFullyConnected(fullyConnected) islandMath.SetMinimumSize(minimumSize) # Note that island operation happens in unsigned long space # but the segment editor works in unsigned char castOut = vtk.vtkImageCast() castOut.SetInputConnection(islandMath.GetOutputPort()) castOut.SetOutputScalarTypeToUnsignedChar() castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount logging.info("%d islands created (%d ignored)" % (islandCount, ignoredIslands)) # Create oriented image data from output import vtkSegmentationCorePython as vtkSegmentationCore multiLabelImage = vtkSegmentationCore.vtkOrientedImageData() multiLabelImage.DeepCopy(castOut.GetOutput()) selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4() selectedSegmentLabelmap.GetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) multiLabelImage.SetGeometryFromImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) # Import multi-label labelmap to segmentation segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode() selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID() selectedSegmentName = segmentationNode.GetSegmentation().GetSegment(selectedSegmentID).GetName() slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode( multiLabelImage, segmentationNode, selectedSegmentName ) # Set labelmap visibility to outline for the new segments displayNode = segmentationNode.GetDisplayNode() # for index in xrange(1,islandCount+1): # segmentID = selectedSegmentName + "_" + str(index) # displayNode.SetSegmentVisibility2DFill(segmentID, False) # displayNode.SetSegmentVisibility2DOutline(segmentID, True) displayNode.SetSegmentVisibility(selectedSegmentID, False)
def onApply(self): #TODO: #self.logic.undoRedo = self.undoRedo # Get parameters fullyConnected = self.scriptedEffect.integerParameter("FullyConnected") minimumSize = self.scriptedEffect.integerParameter("MinimumSize") # Get modifier labelmap selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() castIn = vtk.vtkImageCast() castIn.SetInputData(selectedSegmentLabelmap) castIn.SetOutputScalarTypeToUnsignedLong() # Identify the islands in the inverted volume and # find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() islandMath.SetInputConnection(castIn.GetOutputPort()) islandMath.SetFullyConnected(fullyConnected) islandMath.SetMinimumSize(minimumSize) # Note that island operation happens in unsigned long space # but the segment editor works in unsigned char castOut = vtk.vtkImageCast() castOut.SetInputConnection(islandMath.GetOutputPort()) castOut.SetOutputScalarTypeToUnsignedChar() castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount logging.info( "%d islands created (%d ignored)" % (islandCount, ignoredIslands) ) # Create oriented image data from output import vtkSegmentationCorePython as vtkSegmentationCore multiLabelImage = vtkSegmentationCore.vtkOrientedImageData() multiLabelImage.DeepCopy(castOut.GetOutput()) selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4() selectedSegmentLabelmap.GetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) multiLabelImage.SetGeometryFromImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) # Import multi-label labelmap to segmentation segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode() selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID() selectedSegmentName = segmentationNode.GetSegmentation().GetSegment(selectedSegmentID).GetName() slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode( \ multiLabelImage, segmentationNode, selectedSegmentName ) # Set labelmap visibility to outline for the new segments displayNode = segmentationNode.GetDisplayNode() #for index in xrange(1,islandCount+1): # segmentID = selectedSegmentName + "_" + str(index) # displayNode.SetSegmentVisibility2DFill(segmentID, False) # displayNode.SetSegmentVisibility2DOutline(segmentID, True) displayNode.SetSegmentVisibility(selectedSegmentID, False)
def onApply(self): # This can be a long operation - indicate it to the user qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor) self.scriptedEffect.saveStateForUndo() # Get parameters fullyConnected = self.scriptedEffect.integerParameter("FullyConnected") minimumSize = self.scriptedEffect.integerParameter("MinimumSize") # Get modifier labelmap selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() castIn = vtk.vtkImageCast() castIn.SetInputData(selectedSegmentLabelmap) castIn.SetOutputScalarTypeToUnsignedLong() # Identify the islands in the inverted volume and # find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() islandMath.SetInputConnection(castIn.GetOutputPort()) islandMath.SetFullyConnected(fullyConnected) islandMath.SetMinimumSize(minimumSize) # Note that island operation happens in unsigned long space # but the segment editor works in unsigned char castOut = vtk.vtkImageCast() castOut.SetInputConnection(islandMath.GetOutputPort()) castOut.SetOutputScalarTypeToUnsignedChar() castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount logging.info( "%d islands created (%d ignored)" % (islandCount, ignoredIslands) ) # Create oriented image data from output import vtkSegmentationCorePython as vtkSegmentationCore multiLabelImage = vtkSegmentationCore.vtkOrientedImageData() multiLabelImage.DeepCopy(castOut.GetOutput()) selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4() selectedSegmentLabelmap.GetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) multiLabelImage.SetGeometryFromImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix) # Import multi-label labelmap to segmentation segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode() selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID() selectedSegmentName = segmentationNode.GetSegmentation().GetSegment(selectedSegmentID).GetName() slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode( \ multiLabelImage, segmentationNode, selectedSegmentName ) segmentationNode.GetSegmentation().RemoveSegment(selectedSegmentID) qt.QApplication.restoreOverrideCursor()
def removeIslands(self): # # change the label values based on the parameter node # if not self.sliceLogic: self.sliceLogic = self.editUtil.getSliceLogic() parameterNode = self.editUtil.getParameterNode() minimumSize = int( parameterNode.GetParameter("IslandEffect,minimumSize")) fullyConnected = bool( parameterNode.GetParameter("IslandEffect,fullyConnected")) label = self.editUtil.getLabel() # note that island operation happens in unsigned long space # but the slicer editor works in Short castIn = vtk.vtkImageCast() if vtk.VTK_MAJOR_VERSION <= 5: castIn.SetInput(self.getScopedLabelInput()) else: castIn.SetInputData(self.getScopedLabelInput()) castIn.SetOutputScalarTypeToUnsignedLong() # now identify the islands in the inverted volume # and find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() if vtk.VTK_MAJOR_VERSION <= 5: islandMath.SetInput(castIn.GetOutput()) else: islandMath.SetInputConnection(castIn.GetOutputPort()) islandMath.SetFullyConnected(fullyConnected) islandMath.SetMinimumSize(minimumSize) # TODO: $this setProgressFilter $islandMath "Calculating Islands..." # note that island operation happens in unsigned long space # but the slicer editor works in Short castOut = vtk.vtkImageCast() if vtk.VTK_MAJOR_VERSION <= 5: castOut.SetInput(islandMath.GetOutput()) else: castOut.SetInputConnection(islandMath.GetOutputPort()) castOut.SetOutputScalarTypeToShort() castOut.SetOutput(self.getScopedLabelOutput()) # TODO $this setProgressFilter $postThresh "Applying to Label Map..." castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount print("%d islands created (%d ignored)" % (islandCount, ignoredIslands)) self.applyScopedLabel() castOut.SetOutput(None)
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 removeIslands(self): # # change the label values based on the parameter node # if not self.sliceLogic: self.sliceLogic = self.editUtil.getSliceLogic() parameterNode = self.editUtil.getParameterNode() minimumSize = int(parameterNode.GetParameter("IslandEffect,minimumSize")) fullyConnected = bool(parameterNode.GetParameter("IslandEffect,fullyConnected")) label = self.editUtil.getLabel() # note that island operation happens in unsigned long space # but the slicer editor works in Short castIn = vtk.vtkImageCast() if vtk.VTK_MAJOR_VERSION <= 5: castIn.SetInput( self.getScopedLabelInput() ) else: castIn.SetInputData( self.getScopedLabelInput() ) castIn.SetOutputScalarTypeToUnsignedLong() # now identify the islands in the inverted volume # and find the pixel that corresponds to the background islandMath = vtkITK.vtkITKIslandMath() if vtk.VTK_MAJOR_VERSION <= 5: islandMath.SetInput( castIn.GetOutput() ) else: islandMath.SetInputConnection( castIn.GetOutputPort() ) islandMath.SetFullyConnected( fullyConnected ) islandMath.SetMinimumSize( minimumSize ) # TODO: $this setProgressFilter $islandMath "Calculating Islands..." # note that island operation happens in unsigned long space # but the slicer editor works in Short castOut = vtk.vtkImageCast() if vtk.VTK_MAJOR_VERSION <= 5: castOut.SetInput( islandMath.GetOutput() ) else: castOut.SetInputConnection( islandMath.GetOutputPort() ) castOut.SetOutputScalarTypeToShort() castOut.SetOutput( self.getScopedLabelOutput() ) # TODO $this setProgressFilter $postThresh "Applying to Label Map..." castOut.Update() islandCount = islandMath.GetNumberOfIslands() islandOrigCount = islandMath.GetOriginalNumberOfIslands() ignoredIslands = islandOrigCount - islandCount print( "%d islands created (%d ignored)" % (islandCount, ignoredIslands) ) self.applyScopedLabel() castOut.SetOutput( None )
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 run(self): global vtk_error #----- verify extension ------------------ extension = VerifyDataType(self.filepath) file_name = self.filepath.split(os.path.sep)[-1] n_array = ReadBitmap(self.filepath) if not(isinstance(n_array, numpy.ndarray)): return False image = converters.to_vtk(n_array, spacing=(1,1,1),\ slice_number=1, orientation="AXIAL") dim = image.GetDimensions() x = dim[0] y = dim[1] img = vtk.vtkImageResample() img.SetInputData(image) img.SetAxisMagnificationFactor ( 0, 0.25 ) img.SetAxisMagnificationFactor ( 1, 0.25 ) img.SetAxisMagnificationFactor ( 2, 1 ) img.Update() tp = img.GetOutput().GetScalarTypeAsString() image_copy = vtk.vtkImageData() image_copy.DeepCopy(img.GetOutput()) thumbnail_path = tempfile.mktemp() write_png = vtk.vtkPNGWriter() write_png.SetInputConnection(img.GetOutputPort()) write_png.AddObserver("WarningEvent", VtkErrorPNGWriter) write_png.SetFileName(thumbnail_path) write_png.Write() if vtk_error: img = vtk.vtkImageCast() img.SetInputData(image_copy) img.SetOutputScalarTypeToUnsignedShort() #img.SetClampOverflow(1) img.Update() write_png = vtk.vtkPNGWriter() write_png.SetInputConnection(img.GetOutputPort()) write_png.SetFileName(thumbnail_path) write_png.Write() vtk_error = False id = wx.NewId() bmp_item = [self.filepath, thumbnail_path, extension, x, y,\ str(x) + ' x ' + str(y), file_name, id] self.bmp_file.Add(bmp_item)
def __init__(self, data_reader): #if vtk_structured_points_data!=None: # ukosniki=vtk_structured_points_data.count("/") # etykieta=vtk_structured_points_data.split("/",ukosniki) # self.WhoAmI=self.WhoAmI+" "+ etykieta[ukosniki] #def make_name(self,name): # if name!=None: # ukosniki=name.count("/") # etykieta=name.split("/",ukosniki) # self.WhoAmI=self.WhoAmI+" "+ etykieta[ukosniki] self.make_color_function(data_reader.get_data_set().GetScalarRange()) # The property describes how the data will look self.volumeProperty = vtk.vtkVolumeProperty() self.volumeProperty.SetColor(self.colorTransferFunction) self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction) self.volumeProperty.SetGradientOpacity(self.gradientTransferFunction) # The mapper / ray cast function know how to render the data self.compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() self.cast = vtk.vtkImageCast() self.cast.SetInput(data_reader.get_data_set()) self.cast.SetOutputScalarTypeToUnsignedShort() self.cast.ClampOverflowOff() self.mapper = vtk.vtkVolumeRayCastMapper() self.mapper.SetVolumeRayCastFunction(self.compositeFunction) self.mapper.SetInputConnection(self.cast.GetOutputPort()) self.actor = vtk.vtkVolume() self.actor.SetMapper(self.mapper) self.actor.SetProperty(self.volumeProperty)
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 write_image(_data, path_to_image): # == make sure data type is unsigned char cast = vtk.vtkImageCast() if vtk.VTK_MAJOR_VERSION <= 5: cast.SetInput(_data) else: cast.SetInputData(_data) cast.SetOutputScalarTypeToUnsignedChar() cast.Update() _data = cast.GetOutput() # == write file_ext = fu.get_file_extension(path_to_image) if (file_ext == "vti"): print("Writing as '.vti' file.") image_writer = vtk.vtkXMLImageDataWriter() elif (file_ext == "nii"): print("Writing as '.nii' file.") image_writer = vtk.vtkNIFTIImageWriter() print( "VTK seems to change image orientation of NIFTI. Make sure to check image orientation relative to original image" ) elif (file_ext == "mhd" or file_ext == "mha"): print("Writing as .mhd/.raw or .mha image.") image_writer = vtk.vtkMetaImageWriter() image_writer.SetCompression(False) else: print("No valid image file extension specified!") if vtk.VTK_MAJOR_VERSION <= 5: image_writer.SetInput(_data) else: image_writer.SetInputData(_data) image_writer.SetFileName(path_to_image) # image_writer.Update() image_writer.Write() print("Image has been saved as %s " % (path_to_image))
def castVolumeNodeToShort(self, volumeNode): imageData = volumeNode.GetImageData() cast=vtk.vtkImageCast() cast.SetInputData(imageData) cast.SetOutputScalarTypeToShort() cast.SetOutput(imageData) cast.Update()
def read_metaimage(self, fname_meta, cast_type=5): reader = vtk.vtkMetaImageReader() reader.SetFileName(fname_meta) # VTK image cast img_cast = vtk.vtkImageCast() if cast_type == 0: # return a vtkImageData with wrong dims and bounds value self.reader = reader.GetOutput() # return reader.GetOutput() elif cast_type in [i for i in range(2, 12)]: img_cast.SetInputConnection(reader.GetOutputPort()) img_cast.SetOutputScalarType(cast_type) img_cast.Update() self.reader = img_cast.GetOutput() # return img_cast.GetOutput() # a vtkImageData else: sys.stderr.write( ('Wrong Cast Type! It should be 2, 3, ..., 11\n') ('No Image Cast Applied') ) self.reader = img_cast.GetOutput() # return reader.GetOutput() self.flag_read = True return self.reader
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.OutputType == 'uchar' and self.ShiftScale: shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() scale = 255.0 if (scalarRange[1]-scalarRange[0]) > 0.0: scale = 255.0/(scalarRange[1]-scalarRange[0]) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) else: shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0)) shiftScale.SetScale(255.0/self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() self.Image = shiftScale.GetOutput() else: cast = vtk.vtkImageCast() cast.SetInputData(self.Image) if self.OutputType == 'float': cast.SetOutputScalarTypeToFloat() elif self.OutputType == 'double': cast.SetOutputScalarTypeToDouble() elif self.OutputType == 'uchar': cast.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == 'short': cast.SetOutputScalarTypeToShort() cast.Update() self.Image = cast.GetOutput()
def execute(self, inputs, update = 0, last = 0): """ Execute the filter with given inputs and return the output """ lib.ProcessingFilter.ProcessingFilter.execute(self, inputs) image = self.getInput(1) image2 = self.getInput(2) self.vtkfilter.SetClampOverflow(self.parameters["ClampOverflow"]) if self.numberOfInputs[0] > 1: if image.GetScalarType != image2.GetScalarType(): cast = vtk.vtkImageCast() cast.SetOutputScalarType(image.GetScalarType()) cast.SetInput(image2) cast.Update() image2 = cast.GetOutput() self.vtkfilter.SetInput1(image) self.vtkfilter.SetInput2(image2) else: self.vtkfilter.SetInput1(image) self.vtkfilter.SetInput2(image) self.vtkfilter.SetInput(image) f = "self.vtkfilter.SetOperationTo%s()" % self.operation eval(f) if update: self.vtkfilter.Update() return self.vtkfilter.GetOutput()
def main(argv): #Just get something working for testing... try: opts, args = getopt.getopt(argv, "hi:", ["ifile="]) except getopt.GetoptError as err: print 'tviewer.py -i <inputfile.vtk>' print(str(err)) for opt, arg in opts: if opt == '-h': print 'tviewer.py -i <inputfile.vtk>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg print("Going to load and generate png from ", inputfile) #Read data reader = vtk.vtkXMLImageDataReader() reader.SetFileName(inputfile) reader.Update() image = reader.GetOutput() #image.SetSpacing(1,1,1) #image.GetPointData().SetScalars(image.GetPointData().GetVectors()) #Compute Q Criterion for texture mapping #Now put this in a png file castFilter = vtk.vtkImageCast() castFilter.SetInputData(image) castFilter.Update() w = vtk.vtkPNGWriter() w.SetInputData(castFilter.GetOutput()) w.SetFileName("xyslice.png") w.Write()
def __init__(self): """ Initialization """ lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageCast() self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.eventDesc = "Casting the image to datatype" self.descs = { "ClampOverflow": "Prevent over/underflow", "Float": "Float", "Double": "Double", "Int": "Int", "UnsignedInt": "Unsigned int", "Long": "Long", "UnsignedLong": "Unsigned long", "Short": "Short", "UnsignedShort": "Unsigned short", "UnsignedChar": "Unsigned char", "Char": "Char", "RescaleCTF": "Rescale current CTF to range of a new datatype" } self.filterDesc = "Converts input data type to another data type\nInput: Grayscale/Binary/Label image\nOutput: Grayscale/Binary/Label image"
def update_mask(self, src): # Filter cast_filter = vtk.vtkImageCast() cast_filter.SetOutputScalarTypeToUnsignedInt() cast_filter.SetInputData(src) cast_filter.Update() # Create mesh using marching cube march = vtk.vtkDiscreteMarchingCubes() march.ComputeNormalsOn() march.ComputeGradientsOn() for i, organ in enumerate(Settings.organs): march.SetValue(i, Settings.labels[organ]['value']) march.SetInputData(cast_filter.GetOutput()) march.Update() # Filtrate the masks smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInputConnection(march.GetOutputPort()) smooth.SetNumberOfIterations(15) smooth.BoundarySmoothingOff() smooth.FeatureEdgeSmoothingOff() smooth.SetFeatureAngle(120.0) smooth.SetPassBand(.001) smooth.NonManifoldSmoothingOn() smooth.NormalizeCoordinatesOn() smooth.Update() self.surface_mapper.SetInputConnection(smooth.GetOutputPort())
def convertITKtoVTK(self, image, cast=None, force=0): """ Convert the ITK image data to VTK image """ # For non-ITK images, do nothing if image.__class__ == vtk.vtkImageData: return image try: import itk except ImportError: print "Could not import ITK, terminating." sys.exit() self.itkToVtk = itk.ImageToVTKImageFilter[image].New() # If the next filter is also an ITK filter, then won't # convert if not force and self.nextFilter and self.nextFilter.getITK(): return image self.itkToVtk.SetInput(image) self.itkToVtk.Update() if cast: icast = vtk.vtkImageCast() if cast == "UC3": icast.SetOutputScalarTypeToUnsignedChar() elif cast == "US3": icast.SetOutputScalarTypeToUnsignedShort() icast.SetInput(self.itkToVtk.GetOutput()) icast.Update() return icast.GetOutput() return self.itkToVtk.GetOutput()
def castImagesToLargestDataType(images): """ This function casts a list of images using the vtkImageCast so that they all have the same type that is large enough to hold all of the images @param images A list of vtkImageData objects """ returnValues = [] largestType = -1 largestMax = 0 types = [] differ = 0 for index, i in enumerate(images): types.append(i.GetScalarType()) if types[index] != types[index - 1]: differ = 1 if i.GetScalarTypeMax() > largestMax: largestType = i.GetScalarType() largestMax = i.GetScalarTypeMax() if not differ: return images for i, image in enumerate(images): cast = vtk.vtkImageCast() cast.SetOutputScalarType(largestType) cast.SetInput(image) image = cast.GetOutput() returnValues.append(image) return returnValues
def BuildUpwindGradientBasedFeatureImage(self): cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter() gradientMagnitude.SetInputConnection(cast.GetOutputPort()) gradientMagnitude.SetUpwindFactor(self.UpwindFactor) gradientMagnitude.Update() featureImage = None if self.SigmoidRemapping==1: scalarRange = gradientMagnitude.GetOutput().GetPointData().GetScalars().GetRange() inputMinimum = scalarRange[0] inputMaximum = scalarRange[1] alpha = - (inputMaximum - inputMinimum) / 6.0 beta = (inputMaximum + inputMinimum) / 2.0 sigmoid = vtkvmtk.vtkvmtkSigmoidImageFilter() sigmoid.SetInputConnection(gradientMagnitude.GetOutputPort()) sigmoid.SetAlpha(alpha) sigmoid.SetBeta(beta) sigmoid.SetOutputMinimum(0.0) sigmoid.SetOutputMaximum(1.0) sigmoid.Update() featureImage = sigmoid.GetOutput() else: boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter() boundedReciprocal.SetInputConnection(gradientMagnitude.GetOutputPort()) boundedReciprocal.Update() featureImage = boundedReciprocal.GetOutput() self.FeatureImage = vtk.vtkImageData() self.FeatureImage.DeepCopy(featureImage)
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') morphologyFilter = vtkvmtk.vtkvmtkGrayscaleMorphologyImageFilter() if self.Operation == 'close': morphologyFilter.SetOperationToClose() elif self.Operation == 'open': morphologyFilter.SetOperationToOpen() elif self.Operation == 'dilate': morphologyFilter.SetOperationToDilate() elif self.Operation == 'erode': morphologyFilter.SetOperationToErode() cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() morphologyFilter.SetInputConnection(cast.GetOutputPort()) morphologyFilter.SetBallRadius(self.BallRadius) morphologyFilter.Update() self.Image = morphologyFilter.GetOutput()
def onApply(self): inputVolume = self.inputSelector.currentNode() outputVolume = self.outputSelector.currentNode() if not (inputVolume): qt.QMessageBox.critical( slicer.util.mainWindow(), 'Averaging', 'Input volumes are required') return outVolumeNode = self.outputSelector.currentNode() volumesLogic = slicer.modules.volumes.logic() # newNode = volumesLogic.CloneVolume(slicer.mrmlScene, sourceVolumeNode, 'average volume') # create output volume by cloning the selected reference volume # volumesLogic = slicer.modules.volumes.logic() newNode = volumesLogic.CloneVolume(self.inputSelector.currentNode(), "average volume") # vtk function to average the images imgsum = vtk.vtkImageWeightedSum() imgsum.NormalizeByWeightOn() # add all of the input image data for (i,n) in enumerate(self.inputSelector.checkedNodes()): print("adding input image: {0}".format(n.GetName())) cast = vtk.vtkImageCast() cast.SetOutputScalarTypeToFloat() cast.AddInputConnection(n.GetImageDataConnection()) imgsum.AddInputConnection(cast.GetOutputPort()) imgsum.SetWeight(i, 1.) # run the filter and set the result to the output image imgsum.Update() newNode.SetAndObserveImageData(imgsum.GetOutput())
def execute(self, inputs = (1,1), update = 0, last = 0): """ Execute filter in input image and return output image """ if not lib.ProcessingFilter.ProcessingFilter.execute(self,inputs): return None self.eventDesc = "Calculating FFT" inputImage = self.getInput(1) # Convert image to float origType = inputImage.GetScalarType() castFloat = vtk.vtkImageCast() castFloat.SetOutputScalarTypeToFloat() self.filter = vtk.vtkImageFFT() #magnitude = vtk.vtkImageMagnitude() #fourierCenter = vtk.vtkImageFourierCenter() #logarithmic = vtk.vtkImageLogarithmicScale() #logarithmic.SetConstant(15) castFloat.SetInput(inputImage) self.filter.SetInputConnection(castFloat.GetOutputPort()) #magnitude.SetInputConnection(self.filter.GetOutputPort()) #fourierCenter.SetInputConnection(magnitude.GetOutputPort()) #logarithmic.SetInputConnection(fourierCenter.GetOutputPort()) #outputImage = logarithmic.GetOutput() outputImage = self.filter.GetOutput() if update: outputImage.Update() return outputImage
def Execute(self): if self.Image == None: self.PrintError('Error: no Image.') cast = vtk.vtkImageCast() cast.SetInput(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() self.Image = cast.GetOutput() if not self.vmtkRenderer: self.vmtkRenderer = vmtkscripts.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 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: (0: colliding fronts; 1: fast marching; 2: threshold; 3: isosurface, 4: seed): ' 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 if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def execute(self, inputs, update=0, last=0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None if self.parameters["UseImageROI"]: maskImage = self.getInput(2) # If scalar type is not unsigned char, then cast the data cast = vtk.vtkImageCast() cast.SetInput(maskImage) cast.SetOutputScalarType(3) cast.SetClampOverflow(1) maskImage = cast.GetOutput() else: maxx, maxy, maxz = self.dataUnit.getDimensions() roi = self.parameters["ROI"][1] n, maskImage = lib.ImageOperations.getMaskFromROIs([roi], maxx, maxy, maxz) scripting.wantWholeDataset = 1 imagedata = self.getInput(1) imagedata.SetUpdateExtent(imagedata.GetWholeExtent()) imagedata.Update() maskFilter = vtk.vtkImageMask() maskFilter.SetImageInput(imagedata) maskFilter.SetMaskInput(maskImage) maskFilter.SetMaskedOutputValue(self.parameters["OutputValue"]) return maskFilter.GetOutput()
def execute(self, inputs, update=0, last=0): """ Execute the filter with given inputs and return the output """ lib.ProcessingFilter.ProcessingFilter.execute(self, inputs) image = self.getInput(1) image2 = self.getInput(2) self.vtkfilter.SetClampOverflow(self.parameters["ClampOverflow"]) if self.numberOfInputs[0] > 1: if image.GetScalarType != image2.GetScalarType(): cast = vtk.vtkImageCast() cast.SetOutputScalarType(image.GetScalarType()) cast.SetInput(image2) cast.Update() image2 = cast.GetOutput() self.vtkfilter.SetInput1(image) self.vtkfilter.SetInput2(image2) else: self.vtkfilter.SetInput1(image) self.vtkfilter.SetInput2(image) self.vtkfilter.SetInput(image) f = "self.vtkfilter.SetOperationTo%s()" % self.operation eval(f) if update: self.vtkfilter.Update() return self.vtkfilter.GetOutput()
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._input = None self._image_cast = vtk.vtkImageCast() self._vtk2itk = None # this stores the short_string of the current converter, e.g. # F3 or US3, etc. self._vtk2itk_short_string = None self._config.autotype = False # this will store the current type as full text, e.g. "unsigned char" self._config.type = 'float' config_list = [ ('AutoType:', 'autotype', 'base:bool', 'checkbox', 'If activated, output data type is set to ' 'input type.'), ('Data type:', 'type', 'base:str', 'choice', 'Data will be cast to this type if AutoType is not used.', [ 'float', 'signed short', 'unsigned short', 'unsigned char', 'unsigned long' ]) ] ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)': self}) self.sync_module_logic_with_config()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageCast(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.Grayscale: morphologyFilter = vtkvmtk.vtkvmtkGrayscaleMorphologyImageFilter() if self.Operation == 'close': morphologyFilter.SetOperationToClose() elif self.Operation == 'open': morphologyFilter.SetOperationToOpen() elif self.Operation == 'dilate': morphologyFilter.SetOperationToDilate() elif self.Operation == 'erode': morphologyFilter.SetOperationToErode() cast = vtk.vtkImageCast() cast.SetInput(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() morphologyFilter.SetInput(cast.GetOutput()) morphologyFilter.SetBallRadius(self.BallRadius) morphologyFilter.Update() self.Image = morphologyFilter.GetOutput()
def convertITKtoVTK(self, image, cast = None, force = 0): """ Convert the ITK image data to VTK image """ # For non-ITK images, do nothing if image.__class__ == vtk.vtkImageData: return image try: import itk except ImportError: print "Could not import ITK, terminating." sys.exit() self.itkToVtk = itk.ImageToVTKImageFilter[image].New() # If the next filter is also an ITK filter, then won't # convert if not force and self.nextFilter and self.nextFilter.getITK(): return image self.itkToVtk.SetInput(image) self.itkToVtk.Update() if cast: icast = vtk.vtkImageCast() if cast == "UC3": icast.SetOutputScalarTypeToUnsignedChar() elif cast == "US3": icast.SetOutputScalarTypeToUnsignedShort() icast.SetInput(self.itkToVtk.GetOutput()) icast.Update() return icast.GetOutput() return self.itkToVtk.GetOutput()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._image_logic = vtk.vtkImageLogic() module_utils.setup_vtk_object_progress(self, self._image_logic, 'Performing image logic') self._image_cast = vtk.vtkImageCast() module_utils.setup_vtk_object_progress( self, self._image_cast, 'Casting scalar type before image logic') self._config.operation = 0 self._config.output_true_value = 1.0 # 'choice' widget with 'base:int' type will automatically get cast # to index of selection that user makes. config_list = [ ('Operation:', 'operation', 'base:int', 'choice', 'The operation that should be performed.', tuple(self._operations)), ('Output true value:', 'output_true_value', 'base:float', 'text', 'Output voxels that are TRUE will get this value.') ] ScriptedConfigModuleMixin.__init__(self, config_list, { 'Module (self)': self, 'vtkImageLogic': self._image_logic }) self.sync_module_logic_with_config()
def __init__(self, fileName=None, channel=0, ImageType=None): from vtk import vtkLSMReader, vtkImageCast import itk itk.pipeline.__init__(self) # if ImageType is None, give it a default value # this is useful to avoid loading Base while loading this module if ImageType == None: ImageType = itk.Image.UC3 # remove useless SetInput() method created by the constructor of the pipeline class # del self.SetInput # set up the pipeline self.connect(vtkLSMReader()) self.connect(vtkImageCast()) PType = itk.template(ImageType)[1][0] if PType == itk.UC: self[-1].SetOutputScalarTypeToUnsignedChar() elif PType == itk.US: self[-1].SetOutputScalarTypeToUnsignedShort() self.connect(itk.VTKImageToImageFilter[ImageType].New()) self.connect(itk.ChangeInformationImageFilter[ImageType].New( ChangeSpacing=True)) # and configure the pipeline if fileName: self.SetFileName(fileName) self.SetChannel(channel)
def read_meta_image(meta_name, cast_type=5): """ Usually Meta Image is `unsigned short` No casting leads to wrong reslut! """ reader = vtk.vtkMetaImageReader() reader.SetFileName(meta_name) # No cast if cast_type == 0: # vtkImageData with wrong dims and bounds value. return reader.GetOutput() # Cast the image to another data type elif cast_type in [i for i in range(2, 12)]: cast = vtk.vtkImageCast() # cast.SetInputData(img_vtk) cast.SetInputConnection(reader.GetOutputPort()) cast.SetOutputScalarType(cast_type) cast.Update() return cast.GetOutput() # The output of `cast` is a vtkImageData # Wrong cast type. Return the no-cast vtkImageData else: sys.stderr.write('Wrong Cast Type! It should be 2, 3, ..., or 11') return reader.GetOutput()
def read_metaimage(self, fname_meta, cast_type=5): reader = vtk.vtkMetaImageReader() reader.SetFileName(fname_meta) # VTK image cast img_cast = vtk.vtkImageCast() if cast_type == 0: # return a vtkImageData with wrong dims and bounds value self.reader = reader.GetOutput() # return reader.GetOutput() elif cast_type in [i for i in range(2, 12)]: img_cast.SetInputConnection(reader.GetOutputPort()) img_cast.SetOutputScalarType(cast_type) img_cast.Update() self.reader = img_cast.GetOutput() # return img_cast.GetOutput() # a vtkImageData else: sys.stderr.write(('Wrong Cast Type! It should be 2, 3, ..., 11\n' )('No Image Cast Applied')) self.reader = img_cast.GetOutput() # return reader.GetOutput() self.flag_read = True return self.reader
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 execute(self, inputs=(1, 1), update=0, last=0): """ Execute filter in input image and return output image """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None self.eventDesc = "Calculating FFT" inputImage = self.getInput(1) # Convert image to float origType = inputImage.GetScalarType() castFloat = vtk.vtkImageCast() castFloat.SetOutputScalarTypeToFloat() self.filter = vtk.vtkImageFFT() #magnitude = vtk.vtkImageMagnitude() #fourierCenter = vtk.vtkImageFourierCenter() #logarithmic = vtk.vtkImageLogarithmicScale() #logarithmic.SetConstant(15) castFloat.SetInput(inputImage) self.filter.SetInputConnection(castFloat.GetOutputPort()) #magnitude.SetInputConnection(self.filter.GetOutputPort()) #fourierCenter.SetInputConnection(magnitude.GetOutputPort()) #logarithmic.SetInputConnection(fourierCenter.GetOutputPort()) #outputImage = logarithmic.GetOutput() outputImage = self.filter.GetOutput() if update: outputImage.Update() return outputImage
def Execute(self): if self.Image == None: self.PrintError("Error: No input image.") if self.OutputType == "uchar" and self.ShiftScale: shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInput(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(255.0 / (scalarRange[1] - scalarRange[0])) else: shiftScale.SetShift(-(self.WindowLevel[1] - self.WindowLevel[0] / 2.0)) shiftScale.SetScale(255.0 / self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() self.Image = shiftScale.GetOutput() else: cast = vtk.vtkImageCast() cast.SetInput(self.Image) if self.OutputType == "float": cast.SetOutputScalarTypeToFloat() elif self.OutputType == "double": cast.SetOutputScalarTypeToDouble() elif self.OutputType == "uchar": cast.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == "short": cast.SetOutputScalarTypeToShort() cast.Update() self.Image = cast.GetOutput()
def ndarray2vtkImageData(ndarray, cast_type=11, spacing=[1, 1, 1]): """ Convert a NumPy array to a vtkImageData, with a default casting type VTK_DOUBLE :param ndarray: input NumPy array, can be 3D array :param cast_type: 11 means VTK_DOUBLE :return: a vtkImageData """ # Convert numpy array to VTK array (vtkDoubleArray) vtk_data_array = numpy_support.numpy_to_vtk( num_array=ndarray.transpose(2, 1, 0).ravel(), deep=True, array_type=vtk.VTK_DOUBLE) # Convert the VTK array to vtkImageData img_vtk = vtk.vtkImageData() img_vtk.SetDimensions(ndarray.shape) img_vtk.SetSpacing(spacing[::-1]) # Note the order should be reversed! img_vtk.GetPointData().SetScalars(vtk_data_array) # is a vtkImageData # casting cast = vtk.vtkImageCast() cast.SetInputData(img_vtk) cast.SetOutputScalarType(cast_type) cast.Update() return cast.GetOutput() # vtkImageData
def main(argv): #Just get something working for testing... try: opts, args = getopt.getopt(argv,"hi:", ["ifile="]) except getopt.GetoptError as err: print 'tviewer.py -i <inputfile.vtk>' print (str(err)) for opt, arg in opts: if opt == '-h': print 'tviewer.py -i <inputfile.vtk>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg print("Going to load and generate png from ", inputfile) #Read data reader = vtk.vtkXMLImageDataReader() reader.SetFileName(inputfile) reader.Update() image = reader.GetOutput() #image.SetSpacing(1,1,1) #image.GetPointData().SetScalars(image.GetPointData().GetVectors()) #Compute Q Criterion for texture mapping #Now put this in a png file castFilter = vtk.vtkImageCast() castFilter.SetInputData(image) castFilter.Update() w = vtk.vtkPNGWriter() w.SetInputData(castFilter.GetOutput()) w.SetFileName("xyslice.png") w.Write()
def onApply(self): inputVolume = self.inputSelector.currentNode() outputVolume = self.outputSelector.currentNode() if not (inputVolume): qt.QMessageBox.critical(slicer.util.mainWindow(), 'Averaging', 'Input volumes are required') return outVolumeNode = self.outputSelector.currentNode() volumesLogic = slicer.modules.volumes.logic() # newNode = volumesLogic.CloneVolume(slicer.mrmlScene, sourceVolumeNode, 'average volume') # create output volume by cloning the selected reference volume # volumesLogic = slicer.modules.volumes.logic() newNode = volumesLogic.CloneVolume(self.inputSelector.currentNode(), "average volume") # vtk function to average the images imgsum = vtk.vtkImageWeightedSum() imgsum.NormalizeByWeightOn() # add all of the input image data for (i, n) in enumerate(self.inputSelector.checkedNodes()): print("adding input image: {0}".format(n.GetName())) cast = vtk.vtkImageCast() cast.SetOutputScalarTypeToFloat() cast.AddInputConnection(n.GetImageDataConnection()) imgsum.AddInputConnection(cast.GetOutputPort()) imgsum.SetWeight(i, 1.) # run the filter and set the result to the output image imgsum.Update() newNode.SetAndObserveImageData(imgsum.GetOutput())
def buildGradientBasedFeatureImage(self, imageData): ''' ''' # import the vmtk libraries try: import vtkvmtkSegmentationPython as vtkvmtkSegmentation except ImportError: logging.error("Unable to import the SlicerVmtk libraries") derivativeSigma = 0.0 sigmoidRemapping = 1 cast = vtk.vtkImageCast() cast.SetInputData(imageData) cast.SetOutputScalarTypeToFloat() cast.Update() if (derivativeSigma > 0.0): gradientMagnitude = vtkvmtkSegmentation.vtkvmtkGradientMagnitudeRecursiveGaussianImageFilter( ) gradientMagnitude.SetInputData(cast.GetOutput()) gradientMagnitude.SetSigma(derivativeSigma) gradientMagnitude.SetNormalizeAcrossScale(0) gradientMagnitude.Update() else: gradientMagnitude = vtkvmtkSegmentation.vtkvmtkGradientMagnitudeImageFilter( ) gradientMagnitude.SetInputData(cast.GetOutput()) gradientMagnitude.Update() featureImage = None if sigmoidRemapping == 1: scalarRange = gradientMagnitude.GetOutput().GetPointData( ).GetScalars().GetRange() inputMinimum = scalarRange[0] inputMaximum = scalarRange[1] alpha = -(inputMaximum - inputMinimum) / 6.0 beta = (inputMaximum + inputMinimum) / 2.0 sigmoid = vtkvmtkSegmentation.vtkvmtkSigmoidImageFilter() sigmoid.SetInputData(gradientMagnitude.GetOutput()) sigmoid.SetAlpha(alpha) sigmoid.SetBeta(beta) sigmoid.SetOutputMinimum(0.0) sigmoid.SetOutputMaximum(1.0) sigmoid.Update() featureImage = sigmoid.GetOutput() else: boundedReciprocal = vtkvmtkSegmentation.vtkvmtkBoundedReciprocalImageFilter( ) boundedReciprocal.SetInputData(gradientMagnitude.GetOutput()) boundedReciprocal.Update() featureImage = boundedReciprocal.GetOutput() outImageData = vtk.vtkImageData() outImageData.DeepCopy(featureImage) return outImageData
def convert_vtk_to_itk_image(vtk_image_data, itk_pixel_type=None): """Get an ITK image from the provided vtkImageData object. This image can be passed to ITK filters.""" # Save the VTKGlue optimization for later #------------------------------------------ #itk_import = itk.VTKImageToImageFilter[image_type].New() #itk_import.SetInput(vtk_image_data) #itk_import.Update() #itk_image = itk_import.GetOutput() #itk_image.DisconnectPipeline() #------------------------------------------ import itk import itkTypes import vtk from tomviz import utils itk_to_vtk_type_map = { itkTypes.F: vtk.VTK_FLOAT, itkTypes.D: vtk.VTK_DOUBLE, itkTypes.LD: vtk.VTK_DOUBLE, itkTypes.UC: vtk.VTK_UNSIGNED_CHAR, itkTypes.US: vtk.VTK_UNSIGNED_SHORT, itkTypes.UI: vtk.VTK_UNSIGNED_INT, itkTypes.UL: vtk.VTK_UNSIGNED_LONG, itkTypes.SC: vtk.VTK_CHAR, itkTypes.SS: vtk.VTK_SHORT, itkTypes.SI: vtk.VTK_INT, itkTypes.SL: vtk.VTK_LONG, itkTypes.B: vtk.VTK_INT } # See if we need to cast to a wrapped type in ITK. src_type = vtk_image_data.GetScalarType() if itk_pixel_type is None: dst_type = vtk_cast_map()[src_type] else: dst_type = vtk_cast_map()[itk_to_vtk_type_map[itk_pixel_type]] if src_type != dst_type: caster = vtk.vtkImageCast() caster.SetOutputScalarType(dst_type) caster.ClampOverflowOn() caster.SetInputData(vtk_image_data) caster.Update() vtk_image_data = caster.GetOutput() array = utils.get_array(vtk_image_data) image_type = _get_itk_image_type(vtk_image_data) itk_converter = itk.PyBuffer[image_type] itk_image = itk_converter.GetImageFromArray(array) spacing = vtk_image_data.GetSpacing() origin = vtk_image_data.GetOrigin() itk_image.SetSpacing(spacing) itk_image.SetOrigin(origin) return itk_image
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageCast(), 'Processing.', ('vtkImageData', ), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def buildGradientBasedFeatureImage(self, imageData): ''' ''' # import the vmtk libraries try: import vtkvmtkSegmentationPython as vtkvmtkSegmentation except ImportError: logging.error("Unable to import the SlicerVmtk libraries") derivativeSigma = 0.0 sigmoidRemapping = 1 cast = vtk.vtkImageCast() cast.SetInputData(imageData) cast.SetOutputScalarTypeToFloat() cast.Update() if (derivativeSigma > 0.0): gradientMagnitude = vtkvmtkSegmentation.vtkvmtkGradientMagnitudeRecursiveGaussianImageFilter() gradientMagnitude.SetInputData(cast.GetOutput()) gradientMagnitude.SetSigma(derivativeSigma) gradientMagnitude.SetNormalizeAcrossScale(0) gradientMagnitude.Update() else: gradientMagnitude = vtkvmtkSegmentation.vtkvmtkGradientMagnitudeImageFilter() gradientMagnitude.SetInputData(cast.GetOutput()) gradientMagnitude.Update() featureImage = None if sigmoidRemapping == 1: scalarRange = gradientMagnitude.GetOutput().GetPointData().GetScalars().GetRange() inputMinimum = scalarRange[0] inputMaximum = scalarRange[1] alpha = -(inputMaximum - inputMinimum) / 6.0 beta = (inputMaximum + inputMinimum) / 2.0 sigmoid = vtkvmtkSegmentation.vtkvmtkSigmoidImageFilter() sigmoid.SetInputData(gradientMagnitude.GetOutput()) sigmoid.SetAlpha(alpha) sigmoid.SetBeta(beta) sigmoid.SetOutputMinimum(0.0) sigmoid.SetOutputMaximum(1.0) sigmoid.Update() featureImage = sigmoid.GetOutput() else: boundedReciprocal = vtkvmtkSegmentation.vtkvmtkBoundedReciprocalImageFilter() boundedReciprocal.SetInputData(gradientMagnitude.GetOutput()) boundedReciprocal.Update() featureImage = boundedReciprocal.GetOutput() outImageData = vtk.vtkImageData() outImageData.DeepCopy(featureImage) return outImageData
def setImage(self, dicomfile): logging.debug("In VTKImageView::setImage()") if dicomfile: if os.path.exists(dicomfile): self.reader = vtkgdcm.vtkGDCMImageReader() self.reader.SetFileName(dicomfile) self.reader.Update() vtkImageData = self.reader.GetOutput() vtkImageData.UpdateInformation() srange = vtkImageData.GetScalarRange() cast = vtk.vtkImageCast() cast.SetInput(vtkImageData) cast.SetOutputScalarType(4) cast.Update() cast.GetOutput().SetUpdateExtentToWholeExtent() table = vtk.vtkLookupTable() table.SetNumberOfColors(256) table.SetHueRange(0.0, 0.0) table.SetSaturationRange(0.0, 0.0) table.SetValueRange(0.0, 1.0) table.SetAlphaRange(1.0, 1.0) table.SetRange(srange) table.SetRampToLinear() table.Build() color = vtk.vtkImageMapToColors() color.SetLookupTable(table) color.SetInputConnection(cast.GetOutputPort()) color.Update() self.cast = vtk.vtkImageMapToWindowLevelColors() self.cast.SetOutputFormatToLuminance() self.cast.SetInputConnection(color.GetOutputPort()) self.cast.SetWindow(255.0) self.cast.SetLevel(127.0) self.cast.Update() self.cast.UpdateWholeExtent() self.render.RemoveActor(self.actor) self.actor = vtk.vtkImageActor() self.actor.SetInput(self.cast.GetOutput()) self.render.AddActor(self.actor) self.render.ResetCamera() self.Render() else: self.render.RemoveActor(self.actor) self.Render() else: self.render.RemoveActor(self.actor) self.Render()
def GetNumPyData(filename): print filename vtiReader = vtk.vtkXMLImageDataReader() vtiReader.SetFileName(filename) vtiReader.Update() vtiData = vtk.vtkImageCast() vtiData.SetOutputScalarTypeToDouble() vtiData.SetInput( vtiReader.GetOutput() ) vtiData.Update( ) vti_image = vtiData.GetOutput().GetPointData() vti_array = vtkNumPy.vtk_to_numpy(vti_image.GetArray(0)) return vti_array
def ProcessOneFilePublic(filename, outfilename, tmpfile): gdcm.ImageHelper.SetForceRescaleInterceptSlope(True) vtkreader = vtkgdcm.vtkGDCMImageReader() vtkreader.SetFileName( filename ) vtkreader.Update() cast = vtk.vtkImageCast() cast.SetInput( vtkreader.GetOutput() ) cast.SetOutputScalarTypeToUnsignedShort() # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first: # Some operation will actually be discarded (we simply need a temp storage) vtkwriter = vtkgdcm.vtkGDCMImageWriter() vtkwriter.SetFileName( tmpfile ) vtkwriter.SetMedicalImageProperties( vtkreader.GetMedicalImageProperties() ) vtkwriter.SetDirectionCosines( vtkreader.GetDirectionCosines() ) print "Format:",vtkreader.GetImageFormat() vtkwriter.SetImageFormat( vtkreader.GetImageFormat() ) vtkwriter.SetInput( cast.GetOutput() ) #vtkwriter.Update() vtkwriter.Write() # ok now rewrite the exact same file as the original (keep all info) # but use the Pixel Data Element from the written file tmpreader = gdcm.ImageReader() tmpreader.SetFileName( tmpfile ) if not tmpreader.Read(): sys.exit(1) reader = gdcm.Reader() reader.SetFileName( filename ) if not reader.Read(): sys.exit(1) # Make sure to remove Slope/Rescale to avoid re-execution ds = reader.GetFile().GetDataSet() tags = [ gdcm.Tag(0x0028,0x1052), gdcm.Tag(0x0028,0x1053), gdcm.Tag(0x0028,0x1053), ] for tag in tags: ds.Remove( tag ) writer = gdcm.ImageWriter() writer.SetFileName( outfilename ) # Pass image from vtk written file writer.SetImage( tmpreader.GetImage() ) # pass dataset from initial 'reader' writer.SetFile( reader.GetFile() ) if not writer.Write(): sys.exit(1)
def GetNumpyPhaseData(filename): vtkReader = vtkImageReader() vtkReader.SetFileName(filename) vtkReader.Update() vtkImageCast = vtk.vtkImageCast() vtkImageCast.SetOutputScalarTypeToDouble() vtkImageCast.SetInput( vtkReader.GetOutput() ) vtkImageCast.Update( ) phase_image = vtkImageCast.GetOutput().GetPointData() # convert to phase phase_array = vtkNumPy.vtk_to_numpy(phase_image.GetArray(0)) #return (2.0 * numpy.pi / 4095. ) *phase_array return phase_array.reshape(dimensions,order='F')