code
stringlengths
1
1.72M
language
stringclasses
1 value
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class ivWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkIVWriter() # sorry about this, but the files get REALLY big if we write them # in ASCII - I'll make this a gui option later. #self._writer.SetFileTypeToBinary() # following is the standard way of connecting up the devide progress # callback to a VTK object; you should do this for all objects in module_utils.setup_vtk_object_progress( self, self._writer, 'Writing polydata to Inventor Viewer format') # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'InventorViewer data (*.iv)|*.iv|All files (*)|*', {'vtkIVWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx # need this for wx.SAVE class metaImageWRT(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkMetaImageWriter() module_utils.setup_vtk_object_progress( self, self._writer, 'Writing VTK ImageData') # set up some defaults self._config.filename = '' self._config.compression = True config_list = [ ('Filename:', 'filename', 'base:str', 'filebrowser', 'Output filename for MetaImage file.', {'fileMode' : wx.SAVE, 'fileMask' : 'MetaImage single file (*.mha)|*.mha|MetaImage separate header/(z)raw files (*.mhd)|*.mhd|All files (*)|*', 'defaultExt' : '.mha'} ), ('Compression:', 'compression', 'base:bool', 'checkbox', 'Compress the image / volume data') ] ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)' : self}) def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer # deinit our mixins ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename self._config.compression = self._writer.GetCompression() def config_to_logic(self): self._writer.SetFileName(self._config.filename) self._writer.SetCompression(self._config.compression) def execute_module(self): if self._writer.GetFileName() and self._writer.GetInput(): self._writer.GetInput().UpdateInformation() self._writer.GetInput().SetUpdateExtentToWholeExtent() self._writer.GetInput().Update() self._writer.Write() def streaming_execute_module(self): if self._writer.GetFileName() and self._writer.GetInput(): # if you use Update(), everything crashes (VTK 5.6.1, Ubuntu 10.04 x86_64) self._writer.Write()
Python
class batchConverter: kits = ['vtk_kit', 'wx_kit'] cats = ['Readers','Writers','Converters'] keywords = ['batch','convert','read','write','vti','mha','gipl'] help = """Batch converts image volume files from one type to another. Source and target types can be VTK ImageData (.vti), MetaImage (.mha), or Guys Image Processing Lab (.gipl). All the files in the specified directory matching the given source extension are converted. The user may specify whether source files should be deleted or target files should be automatically overwritten (be careful with these settings!) Known bug: writing to GIPL (forced binary uchar) will result in a thrown exception. Circumvent this by first casting to binary uchar when writing to VTI, and then converting to GIPL in a second pass. (Module by Francois Malan)""" class cptBrepWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes polydata to disc in the format required by the Closest Point Transform (CPT) driver software. Input data is put through a triangle filter first, as that is what the CPT requires. See the <a href="http://www.acm.caltech.edu/~seanm/projects/cpt/cpt.html">CPT home page</a> for more information about the algorithm and the software. """ class DICOMWriter: kits = ['vtk_kit', 'gdcm_kit'] cats = ['Writers', 'Medical', 'DICOM'] help = """Writes image data to disc as DICOM images. This GDCM2-based module writes data to disc as one (multi-frame) or more DICOM files. As input, it requires a special DeVIDE datastructure containing the raw data, the medical image properties and direction cosines (indicating the orientation of the dataset in world / scanner space). You can create such a datastructure by making use of the DVMedicalImageData module. """ class ivWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """ivWRT is an Inventor Viewer polygonal data writer devide module. """ class metaImageWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK image data or structured points in MetaImage format. """ class pngWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes a volume as a series of PNG images. Set the file pattern by making use of the file browsing dialog. Replace the increasing index by a %d format specifier. %3d can be used for example, in which case %d will be replaced by an integer zero padded to 3 digits, i.e. 000, 001, 002 etc. %d starts from 0. Module by Joris van Zwieten. """ class MatlabPointsWriter: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes slice3dVWR world-points to an m-file. """ class points_writer: # BUG: empty kits list screws up dependency checking kits = ['vtk_kit'] cats = ['Writers'] help = """TBD """ class stlWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes STL format data. """ class vtiWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK image data or structured points in the VTK XML format. The data attribute is compressed. This is the preferred way of saving image data in DeVIDE. """ class vtkPolyDataWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Module for writing legacy VTK polydata. vtpWRT should be preferred for all VTK-compatible polydata storage. """ class vtkStructPtsWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Module for writing legacy VTK structured points data. vtiWRT should be preferred for all VTK-compatible image data storage. """ class vtpWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK PolyData in the VTK XML format. The data attribute is compressed. This is the preferred way of saving PolyData in DeVIDE. """
Python
# BatchConverter.py by Francois Malan - 2010-03-05. Updated 2011-12-11# import os.path from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import wx import os import vtk import itk class batchConverter( ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._config.source_folder = '' self._config.source_file_type = -1 self._config.source_forced_numerical_type = 0 self._config.source_numerical_type = 0 self._config.target_folder = '' self._config.target_file_type = -2 self._config.target_forced_numerical_type = 0 self._config.target_numerical_type = 0 self._config.overwrite = False self._config.delete_after_conversion = False #Make sure that the values below match the definitions in the config list! self._config.extensions = {0 : '.vti', 1 : '.mha', 2 : '.mhd', 3 : '.gipl'} self._vtk_data_types = (0, 1, 2) #The list of the above extensions which are VTK types #Make sure that these two dictionaries match the definitions in the config list! self._config.data_types_by_number = {0 : 'auto', 1 : 'float', 2 : 'short', 3 : 'unsigned char', 4 : 'binary (uchar)'} self._config.data_types_by_name = {'auto' : 0, 'float' : 1, 'short' : 2, 'unsigned char' : 3, 'binary (uchar)' : 4} config_list = [ ('Source Folder:', 'source_folder', 'base:str', 'dirbrowser', 'Select the source directory'), ('Source type:', 'source_file_type', 'base:int', 'choice', 'The source file type', ('VTK Imagedata (.vti)', 'MetaImage (.mha)', 'MetaImage: header + raw (.mhd, .raw)', 'Guys Image Processing Lab (.gipl)')), ('Read input as:', 'source_forced_numerical_type', 'base:int', 'choice', 'The data type we assume the input to be in', ('auto detect', 'float', 'signed int', 'unsigned char', 'binary (uchar)')), ('Delete source after conversion', 'delete_after_conversion', 'base:bool', 'checkbox', 'Do you want to delete the source files after conversion? (not recommended)'), ('Destination Folder:', 'target_folder', 'base:str', 'dirbrowser', 'Select the target directory'), ('Destination type:', 'target_file_type', 'base:int', 'choice', 'The destination file type', ('VTK Imagedata (.vti)', 'MetaImage (.mha)', 'MetaImage: header + raw (.mhd, .raw)', 'Guys Image Processing Lab (.gipl)')), ('Cast output to:', 'target_forced_numerical_type', 'base:int', 'choice', 'The data type we cast and write the output to', ('auto detect', 'float', 'signed int', 'unsigned char', 'binary (uchar)')), ('Automatically overwrite', 'overwrite', 'base:bool', 'checkbox', 'Do you want to automatically overwrite existing files?'), ] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) #for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of GUI ScriptedConfigModuleMixin.close(self) def set_input(self): pass def get_input_descriptions(self): return () def get_output_descriptions(self): return () # def get_output(self, idx): # return () def logic_to_config(self): pass def config_to_logic(self): pass def _read_input(self, source_file_path): """ Reads the input specified by the source file path, according to the parameters chosen by the user """ #We choose the correct reader for the job reader = None if self._config.source_file_type == 0: # VTI reader = vtk.vtkXMLImageDataReader() elif self._config.source_file_type == 1 or self._config.source_file_type == 2: # MHA or MHD reader = vtk.vtkMetaImageReader() elif self._config.source_file_type == 3: # GIPL. #GIPL needs an ITK reader, and that needs an explicit type if self._config.source_forced_numerical_type == 0: #auto # create ImageFileReader we'll be using for autotyping autotype_reader = itk.ImageFileReader[itk.Image.F3].New() #and the actual reader reader = itk.ImageFileReader[itk.Image.F3].New() reader_type_text_default = 'F3' autotype_reader.SetFileName(source_file_path) autotype_reader.UpdateOutputInformation() iio = autotype_reader.GetImageIO() comp_type = iio.GetComponentTypeAsString(iio.GetComponentType()) if comp_type == 'short': comp_type = 'signed_short' # lc will convert e.g. unsigned_char to UC short_type = ''.join([i[0].upper() for i in comp_type.split('_')]) dim = iio.GetNumberOfDimensions() num_comp = iio.GetNumberOfComponents() reader_type_text = '%s%d' % (short_type, dim) if num_comp > 1: # e.g. VF33 reader_type_text = 'V%s%d' % (reader_type_text, num_comp) # if things have changed, make a new reader, else re-use the old if reader_type_text != reader_type_text_default: # equivalent to e.g. itk.Image.UC3 reader = itk.ImageFileReader[ getattr(itk.Image, reader_type_text)].New() print '%s was auto-detected as ITK %s' % (source_file_path, reader_type_text) if reader_type_text == 'F3': self._config.source_numerical_type = 1 elif reader_type_text == 'SS3': self._config.source_numerical_type = 2 elif reader_type_text == 'UC3': self._config.source_numerical_type = 3 else: print "Warning: data of type '%s' is not explicitly supported. Reverting to IF3 (float)." % reader_type_text self._config.source_numerical_type = 1 reader = autotype_reader elif self._config.source_forced_numerical_type == 1: #float reader = itk.ImageFileReader.IF3.New() self._config.source_numerical_type = 1 elif self._config.source_forced_numerical_type == 2: #short reader = itk.ImageFileReader.ISS3.New() self._config.source_numerical_type = 2 elif self._config.source_forced_numerical_type == 3 or self._config.source_forced_numerical_type == 4: #unsigned char reader = itk.ImageFileReader.IUC3.New() self._config.source_numerical_type = 3 else: raise Exception('Undefined input data type with numerical index %d' % self._config.source_forced_numerical_type) else: raise Exception('Undefined file type with numerical index %d' % self._config.source_file_type) print "Reading %s ..." % source_file_path reader.SetFileName(source_file_path) reader.Update() return reader.GetOutput() def _convert_input(self, input_data): """ Converts the input data so that it can be sent to the writer. This includes VTK to ITK conversion as well as type casting. """ #These values will be used to determine if conversion is required source_is_vtk = self._config.source_file_type in self._vtk_data_types target_is_vtk = self._config.target_file_type in self._vtk_data_types #Set up the relevant data converter (e.g. VTK2ITK or ITK2VTK) converter = None caster = None output_data = None if source_is_vtk: #We autotype the VTK data, and compare it to the specified input type, if specified auto_data_type_as_string = input_data.GetPointData().GetArray(0).GetDataTypeAsString() auto_data_type_as_number = self._config.data_types_by_name[auto_data_type_as_string] if self._config.source_forced_numerical_type == 0: #auto self._config.source_numerical_type = auto_data_type_as_number else: set_data_type_as_string = self._config.data_types_by_number[self._config.source_forced_numerical_type] if auto_data_type_as_number == self._config.source_forced_numerical_type: self._config.source_numerical_type = self._config.source_forced_numerical_type else: raise Exception("Auto-detected data type (%s) doesn't match specified type (%s)" % (auto_data_type_as_string, set_data_type_as_string) ) #Perform type casting, if required if (self._config.source_numerical_type == self._config.target_forced_numerical_type) or (self._config.target_forced_numerical_type == 0): self._config.target_numerical_type = self._config.source_numerical_type else: self._config.target_numerical_type = self._config.target_forced_numerical_type print 'Type casting VTK data from (%s) to (%s)...' % (self._config.data_types_by_number[self._config.source_numerical_type], self._config.data_types_by_number[self._config.target_numerical_type]) caster = vtk.vtkImageCast() caster.SetInput(input_data) if self._config.target_numerical_type == 1: #float caster.SetOutputScalarTypeToFloat() elif self._config.target_numerical_type == 2: #short caster.SetOutputScalarTypeToShort() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster.SetOutputScalarTypeToUnsignedChar() if target_is_vtk: if caster == None: output_data = input_data else: caster.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(caster.GetOutput()) else: #target is ITK - requires vtk2itk print 'Converting from VTK to ITK... (%s)' % self._config.data_types_by_number[self._config.target_numerical_type] if self._config.target_numerical_type == 1: #float converter = itk.VTKImageToImageFilter[itk.Image.F3].New() elif self._config.target_numerical_type == 2: #short converter = itk.VTKImageToImageFilter[itk.Image.SS3].New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char converter = itk.VTKImageToImageFilter[itk.Image.UC3].New() else: raise Exception('Conversion of VTK %s to ITK not currently supported.' % data_types_by_number[self._config.source_file_type]) if caster == None: converter.SetInput(input_data) else: converter.SetInput(caster.GetOutput()) converter.Update() output_data = converter.GetOutput() else: #Source is ITK #The source type was already set when the data was read, so we don't need to autotype. #We don't know how to autotype ITK data anyway if self._config.source_numerical_type == 0: raise 'This should never happen - ITK data should be typed upon being read and not require autotyping' #Perform type casting, if required if (self._config.source_numerical_type == self._config.target_forced_numerical_type) or (self._config.target_forced_numerical_type == 0): self._config.target_numerical_type = self._config.source_numerical_type else: self._config.target_numerical_type = self._config.target_forced_numerical_type print 'Type casting ITK data from (%s) to (%s)...' % (self._config.data_types_by_number[self._config.source_numerical_type], self._config.data_types_by_number[self._config.target_numerical_type]) if self._config.source_numerical_type == 1: #float if self._config.target_numerical_type == 2: #short caster = itk.CastImageFilter.IF3ISS3() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster = itk.CastImageFilter.IF3IUC3() else: raise Exceception('Error - this case should not occur!') if self._config.source_numerical_type == 2: #short if self._config.target_numerical_type == 1: #float caster = itk.CastImageFilter.ISS3IF3() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster = itk.CastImageFilter.ISS3IUC3() else: raise Exceception('Error - this case should not occur!') if self._config.source_numerical_type == 3 or self._config.source_numerical_type == 4: #unsigned short if self._config.target_numerical_type == 1: #float caster = itk.CastImageFilter.IUC3IF3() elif self._config.target_numerical_type == 2: #short caster = itk.CastImageFilter.IUC3ISS3() else: raise Exceception('Error - this case should not occur!') caster.SetInput(input_data) if not target_is_vtk: if caster == None: output_data = input_data else: caster.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(caster.GetOutput()) else: #target is VTK - requires itk2vtk print 'Converting from ITK to VTK... (%s)' % self._config.data_types_by_number[self._config.target_numerical_type] if self._config.target_numerical_type == 1: #float converter = itk.ImageToVTKImageFilter[itk.Image.F3].New() elif self._config.target_numerical_type == 2: #short converter = itk.ImageToVTKImageFilter[itk.Image.SS3].New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char converter = itk.ImageToVTKImageFilter[itk.Image.UC3].New() else: raise Exception('Conversion of ITK %s to VTK not currently supported.' % self._config.data_types_by_number[self._config.target_numerical_type]) data_to_convert = None if caster == None: data_to_convert = input_data else: data_to_convert = caster.GetOutput() #These three lines are from DeVIDE's ITKtoVTK. Not clear why, but it's necessary data_to_convert.UpdateOutputInformation() data_to_convert.SetBufferedRegion(data_to_convert.GetLargestPossibleRegion()) data_to_convert.Update() converter.SetInput(data_to_convert) converter.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(converter.GetOutput()) return output_data 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 execute_module(self): if self._config.source_folder == '': dlg = wx.MessageDialog(self._view_frame, "No source folder specified", "No source folder",wx.OK) dlg.ShowModal() return elif self._config.target_folder == '': dlg = wx.MessageDialog(self._view_frame, "No destination folder specified", "No destination folder",wx.OK) dlg.ShowModal() return elif self._config.source_file_type < 0: dlg = wx.MessageDialog(self._view_frame, "No source type selected", "No source type",wx.OK) dlg.ShowModal() return elif self._config.target_file_type < 0: dlg = wx.MessageDialog(self._view_frame, "No destination type selected", "No destination type",wx.OK) dlg.ShowModal() return source_ext = self._config.extensions[self._config.source_file_type] target_ext = self._config.extensions[self._config.target_file_type] print 'Source type = %s, target type = %s' % (source_ext, target_ext) print 'source dir = %s' % (self._config.source_folder) print 'target dir = %s' % (self._config.target_folder) all_files = os.listdir(self._config.source_folder) #First we set up a list of files with the correct extension file_list = [] source_ext = self._config.extensions[self._config.source_file_type] for f in all_files: file_name = os.path.splitext(f) if file_name[1] == source_ext: file_list.append(file_name[0]) source_file_type_str = self._config.extensions[self._config.source_file_type] target_extension_str = self._config.extensions[self._config.target_file_type] #Iterate over all input files for file_prefix in file_list: #Read the input file source_file_name = '%s%s' % (file_prefix, source_file_type_str) source_file_path = os.path.join(self._config.source_folder, source_file_name) input_data = self._read_input(source_file_path) converted_data = self._convert_input(input_data) target_file_name = '%s%s' % (file_prefix, target_extension_str) target_file_path = os.path.join(self._config.target_folder, target_file_name) self._write_output(converted_data, target_file_path) #Now we delete the input IFF the check-box is checked, and only if source and destination names differ if self._config.delete_after_conversion: if source_file_path != target_file_path: print 'Deleting source %s' % source_file_path os.remove(source_file_path) else: print 'Source not deleted, since already overwritten by output: %s' % source_file_path print 'Done'
Python
# dumy __init__ so this directory can function as a package
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class cptBrepWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._triFilter = vtk.vtkTriangleFilter() module_utils.setup_vtk_object_progress( self, self._triFilter, 'Converting to triangles') # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'brep files (*.brep)|*.brep|All files (*)|*', {'Module (self)' : self, 'vtkTriangleFilter': self._triFilter}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._triFilter FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._triFilter.SetInput(inputStream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._config.filename) and self._triFilter.GetInput(): # make sure our input is up to date polyData = self._triFilter.GetOutput() polyData.Update() # this will throw an exception if something went wrong. # list of tuples, each tuple contains three indices into vertices # list constituting a triangle face faces = [] self._module_manager.setProgress(10,'Extracting triangles') # blaat. numCells = polyData.GetNumberOfCells() for cellIdx in xrange(numCells): c = polyData.GetCell(cellIdx) # make sure we're working with triangles if c.GetClassName() == 'vtkTriangle': pointIds = c.GetPointIds() if pointIds.GetNumberOfIds() == 3: faces.append((pointIds.GetId(0), pointIds.GetId(1), pointIds.GetId(2))) # now we can finally write f = file(self._config.filename, 'w') f.write('%d\n%d\n' % (polyData.GetNumberOfPoints(), len(faces))) numPoints = polyData.GetNumberOfPoints() for ptIdx in xrange(numPoints): # polyData.GetPoint() returns a 3-tuple f.write('%f %f %f\n' % polyData.GetPoint(ptIdx)) pp = ptIdx / numPoints * 100.0 if pp % 10 == 0: self._module_manager.setProgress( pp, 'Writing points') numFaces = len(faces) faceIdx = 0 for face in faces: f.write('%d %d %d\n' % face) # this is just for progress faceIdx += 1 pp = faceIdx / numFaces * 100.0 if pp % 10 == 0: self._module_manager.setProgress( pp, 'Writing triangles')
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class stlWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # need to make sure that we're all happy triangles and stuff self._cleaner = vtk.vtkCleanPolyData() self._tf = vtk.vtkTriangleFilter() self._tf.SetInput(self._cleaner.GetOutput()) self._writer = vtk.vtkSTLWriter() self._writer.SetInput(self._tf.GetOutput()) # sorry about this, but the files get REALLY big if we write them # in ASCII - I'll make this a gui option later. #self._writer.SetFileTypeToBinary() # following is the standard way of connecting up the devide progress # callback to a VTK object; you should do this for all objects in mm = self._module_manager for textobj in (('Cleaning data', self._cleaner), ('Converting to triangles', self._tf), ('Writing STL data', self._writer)): module_utils.setup_vtk_object_progress(self, textobj[1], textobj[0]) # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'STL data (*.stl)|*.stl|All files (*)|*', {'vtkSTLWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, input_stream): self._cleaner.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx # needs this for wx.OPEN, we need to make this constant available # elsewhere class pngWRT(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin # FilenameViewModuleMixin.__init__(self) self._shiftScale = vtk.vtkImageShiftScale() self._shiftScale.SetOutputScalarTypeToUnsignedShort() module_utils.setup_vtk_object_progress( self, self._shiftScale, 'Converting input to unsigned short.') self._writer = vtk.vtkPNGWriter() self._writer.SetFileDimensionality(3) self._writer.SetInput(self._shiftScale.GetOutput()) module_utils.setup_vtk_object_progress( self, self._writer, 'Writing PNG file(s)') self._config.filePattern = '%d.png' configList = [ ('File pattern:', 'filePattern', 'base:str', 'filebrowser', 'Filenames will be built with this. See module help.', {'fileMode' : wx.OPEN, 'fileMask' : 'PNG files (*.png)|*.png|All files (*.*)|*.*'})] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkPNGWriter' : self._writer}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._writer def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, input_stream): self._shiftScale.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): self._config.filePattern = self._writer.GetFilePattern() def config_to_logic(self): self._writer.SetFilePattern(self._config.filePattern) def execute_module(self): if len(self._writer.GetFilePattern()) and self._shiftScale.GetInput(): inp = self._shiftScale.GetInput() inp.Update() minv,maxv = inp.GetScalarRange() self._shiftScale.SetShift(-minv) self._shiftScale.SetScale(65535 / (maxv - minv)) self._shiftScale.Update() self._writer.Write() self._module_manager.setProgress( 100.0, "vtkPNGWriter: Writing PNG file(s). [DONE]")
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class nbhSeedConnect(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # floats self._config.lower = 128.0 self._config.upper = 255.0 # segmented pixels will be replaced with this value self._config.replaceValue = 1.0 # size of neighbourhood around candidate pixel self._config.radius = (1, 1, 1) configList = [ ('Lower threshold:', 'lower', 'base:float', 'text', 'Pixels have to have an intensity equal to or higher than ' 'this.'), ('Higher threshold:', 'upper', 'base:float', 'text', 'Pixels have to have an intensity equal to or lower than this.'), ('Replace value:', 'replaceValue', 'base:float', 'text', 'Segmented pixels will be assigned this value.'), ('Neighbourhood size:', 'radius', 'tuple:int,3', 'text', '3D integer radii of neighbourhood around candidate pixel.')] # this will contain our binding to the input points self._inputPoints = None # setup the pipeline if3 = itk.Image[itk.F, 3] self._nbhCIF = itk.NeighborhoodConnectedImageFilter[if3,if3].New() itk_kit.utils.setupITKObjectProgress( self, self._nbhCIF, 'itkNeighborhoodConnectedImageFilter', 'Region growing...') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkNeighborhoodConnectedImageFilter' : self._nbhCIF}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._nbhCIF def execute_module(self): self._transferPoints() self._nbhCIF.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: self._nbhCIF.SetInput(inputStream) else: if inputStream != self._inputPoints: self._inputPoints = inputStream def get_output_descriptions(self): return ('Segmented ITK Image (3D, float)',) def get_output(self, idx): return self._nbhCIF.GetOutput() def config_to_logic(self): self._nbhCIF.SetLower(self._config.lower) self._nbhCIF.SetUpper(self._config.upper) self._nbhCIF.SetReplaceValue(self._config.replaceValue) # now setup the radius sz = self._nbhCIF.GetRadius() sz.SetElement(0, self._config.radius[0]) sz.SetElement(1, self._config.radius[1]) sz.SetElement(2, self._config.radius[2]) self._nbhCIF.SetRadius(sz) def logic_to_config(self): self._config.lower = self._nbhCIF.GetLower() self._config.upper = self._nbhCIF.GetUpper() self._config.replaceValue = self._nbhCIF.GetReplaceValue() sz = self._nbhCIF.GetRadius() self._config.radius = tuple( (sz.GetElement(0), sz.GetElement(1), sz.GetElement(2))) def _transferPoints(self): """This will transfer all points from self._inputPoints to the nbhCIF instance. """ # SetSeed calls ClearSeeds and then AddSeed self._nbhCIF.ClearSeeds() if len(self._inputPoints) > 0: for ip in self._inputPoints: # bugger, it could be that our input dataset has an extent # that doesn't start at 0,0,0... ITK doesn't understand this # we have to cast these to int... they are discrete, # but the IPW seems to be returning them as floats x,y,z = [int(i) for i in ip['discrete']] idx = itk.Index[3]() idx.SetElement(0, x) idx.SetElement(1, y) idx.SetElement(2, z) self._nbhCIF.AddSeed(idx) print "Added %d,%d,%d" % (x,y,z)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class nbCurvesLevelSet(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup defaults self._config.propagationScaling = 1.0 self._config.advectionScaling = 1.0 self._config.curvatureScaling = 1.0 self._config.numberOfIterations = 500 configList = [ ('Propagation scaling:', 'propagationScaling', 'base:float', 'text', 'Weight factor for the propagation term'), ('Advection scaling:', 'advectionScaling', 'base:float', 'text', 'Weight factor for the advection term'), ('Curvature scaling:', 'curvatureScaling', 'base:float', 'text', 'Weight factor for the curvature term'), ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations that the algorithm should be run for')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) # create all pipeline thingies self._createITKPipeline() self.sync_module_logic_with_config() def close(self): self._destroyITKPipeline() ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def execute_module(self): self.get_output(0).Update() def get_input_descriptions(self): return ('Feature image (ITK)', 'Initial level set (ITK)' ) def set_input(self, idx, inputStream): if idx == 0: self._nbcLS.SetFeatureImage(inputStream) else: self._nbcLS.SetInput(inputStream) def get_output_descriptions(self): return ('Image Data (ITK)',) def get_output(self, idx): return self._nbcLS.GetOutput() def config_to_logic(self): self._nbcLS.SetPropagationScaling( self._config.propagationScaling) self._nbcLS.SetAdvectionScaling( self._config.advectionScaling) self._nbcLS.SetCurvatureScaling( self._config.curvatureScaling) def logic_to_config(self): self._config.propagationScaling = self._nbcLS.\ GetPropagationScaling() self._config.advectionScaling = self._nbcLS.GetAdvectionScaling() self._config.curvatureScaling = self._nbcLS.GetCurvatureScaling() # -------------------------------------------------------------------- # END OF API CALLS # -------------------------------------------------------------------- def _createITKPipeline(self): # input: smoothing.SetInput() # output: thresholder.GetOutput() if3 = itk.Image[itk.F, 3] self._nbcLS = itk.NarrowBandCurvesLevelSetImageFilter[if3,if3].New() #self._nbcLS.SetMaximumRMSError( 0.1 ); self._nbcLS.SetNumberOfIterations( 500 ); itk_kit.utils.setupITKObjectProgress( self, self._nbcLS, 'NarrowBandCurvesLevelSetImageFilter', 'Evolving level set') def _destroyITKPipeline(self): """Delete all bindings to components of the ITK pipeline. """ del self._nbcLS
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class curvatureFlowDenoising(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 3 self._config.timeStep = 0.05 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of update iterations that will be performed.'), ('Timestep:', 'timeStep', 'base:float', 'text', 'Timestep between update iterations.')] # setup the pipeline if3 = itk.Image[itk.F, 3] self._cfif = itk.CurvatureFlowImageFilter[if3, if3].New() itk_kit.utils.setupITKObjectProgress( self, self._cfif, 'itkCurvatureFlowImageFilter', 'Denoising data') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkCurvatureFlowImageFilter' : self._cfif}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._cfif def execute_module(self): self._cfif.Update() self._module_manager.setProgress(100, "Denoising data [DONE]") def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._cfif.SetInput(inputStream) def get_output_descriptions(self): return ('Denoised ITK Image (3D, float)',) def get_output(self, idx): return self._cfif.GetOutput() def config_to_logic(self): self._cfif.SetNumberOfIterations(self._config.numberOfIterations) self._cfif.SetTimeStep(self._config.timeStep) def logic_to_config(self): self._config.numberOfIterations = self._cfif.GetNumberOfIterations() self._config.timeStep = self._cfif.GetTimeStep()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class curvatureAnisotropicDiffusion(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 5 self._config.conductanceParameter = 3.0 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of time-step updates (iterations) the solver will ' 'perform.'), ('Conductance parameter:', 'conductanceParameter', 'base:float', 'text', 'Sensitivity of the conductance term. Lower == more ' 'preservation of image features.')] # setup the pipeline if3 = itk.Image[itk.F, 3] d = itk.CurvatureAnisotropicDiffusionImageFilter[if3, if3].New() d.SetTimeStep(0.0625) # standard for 3D self._diffuse = d itk_kit.utils.setupITKObjectProgress( self, self._diffuse, 'itkCurvatureAnisotropicDiffusionImageFilter', 'Smoothing data') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkCurvatureAnisotropicDiffusion' : self._diffuse}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._diffuse def execute_module(self): self._diffuse.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._diffuse.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._diffuse.GetOutput() def config_to_logic(self): self._diffuse.SetNumberOfIterations(self._config.numberOfIterations) self._diffuse.SetConductanceParameter( self._config.conductanceParameter) def logic_to_config(self): self._config.numberOfIterations = self._diffuse.GetNumberOfIterations() self._config.conductanceParameter = self._diffuse.\ GetConductanceParameter()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class confidenceSeedConnect(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config thingy self._config.multiplier = 2.5 self._config.numberOfIterations = 4 # segmented pixels will be replaced with this value self._config.replaceValue = 1 # size of neighbourhood around candidate pixel self._config.initialRadius = 1 configList = [ ('Multiplier (f):', 'multiplier', 'base:float', 'text', 'Multiplier for the standard deviation term.'), ('Initial neighbourhood:', 'initialRadius', 'base:int', 'text', 'The radius (in pixels) of the initial region.'), ('Number of Iterations:', 'numberOfIterations', 'base:int', 'text', 'The region will be expanded so many times.'), ('Replace value:', 'replaceValue', 'base:int', 'text', 'Segmented pixels will be assigned this value.')] # this will contain our binding to the input points self._inputPoints = None # and this will be our internal list self._seedPoints = [] # setup the pipeline if3 = itk.Image[itk.F, 3] iss3 = itk.Image[itk.SS, 3] self._cCIF = itk.ConfidenceConnectedImageFilter[if3, iss3].New() itk_kit.utils.setupITKObjectProgress( self, self._cCIF, 'itkConfidenceConnectedImageFilter', 'Region growing...') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._cCIF def execute_module(self): self._transferPoints() self._cCIF.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: try: self._cCIF.SetInput(inputStream) except TypeError, e: # deduce the type itku = module_kits.itk_kit.utils ss = itku.get_img_type_and_dim_shortstring(inputStream) try: c = itk.ConfidenceConnectedImageFilter[getattr(itk.Image,ss), itk.Image[itk.F, 3]].New() except KeyError, e: emsg = 'Could not create ConfidenceConnectedImageFilter with input type %s. '\ 'Please try a different input type.' % (ss,) raise TypeError, emsg # if we get here, we have a new filter # disconnect old one self._cCIF.SetInput(None) # replace with new one (old one should be garbage # collected) self._cCIF = c module_kits.itk_kit.utils.setupITKObjectProgress( self, self._cCIF, 'itkConfidenceConnectedImageFilter', 'Region growing') # re-apply config self.sync_module_logic_with_config() # connect input and hope it works. self._cCIF.SetInput(inputStream) else: if inputStream != self._inputPoints: # check that the inputStream is either None (meaning # disconnect) or a valid type try: if inputStream != None and \ inputStream.devideType != 'namedPoints': raise TypeError except (AttributeError, TypeError): raise TypeError, 'This input requires a points-type' self._inputPoints = inputStream def get_output_descriptions(self): return ('Segmented ITK Image (3D, float)',) def get_output(self, idx): return self._cCIF.GetOutput() def config_to_logic(self): self._cCIF.SetMultiplier(self._config.multiplier) self._cCIF.SetInitialNeighborhoodRadius(self._config.initialRadius) self._cCIF.SetNumberOfIterations(self._config.numberOfIterations) self._cCIF.SetReplaceValue(self._config.replaceValue) def logic_to_config(self): self._config.multiplier = self._cCIF.GetMultiplier() self._config.initialRadius = self._cCIF.GetInitialNeighborhoodRadius() self._config.numberOfIterations = self._cCIF.GetNumberOfIterations() self._config.replaceValue = self._cCIF.GetReplaceValue() def _transferPoints(self): """This will transfer all points from self._inputPoints to the nbhCIF instance. """ # extract a list from the input points tempList = [] if self._inputPoints: for i in self._inputPoints: tempList.append(i['discrete']) if tempList != self._seedPoints: self._seedPoints = tempList self._cCIF.ClearSeeds() # it seems that ClearSeeds() doesn't call Modified(), so we do this # this is important if the list of inputPoints is empty. self._cCIF.Modified() for ip in self._seedPoints: # bugger, it could be that our input dataset has an extent # that doesn't start at 0,0,0... ITK doesn't understand this x,y,z = [int(i) for i in ip] idx = itk.Index[3]() idx.SetElement(0, x) idx.SetElement(1, y) idx.SetElement(2, z) self._cCIF.AddSeed(idx) print "Added %d,%d,%d" % (x,y,z)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class fastMarching(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config thingy self._config.stoppingValue = 256 self._config.normalisationFactor = 1.0 self._config.initial_distance = 0 configList = [ ('Stopping value:', 'stoppingValue', 'base:float', 'text', 'When an arrival time is greater than the stopping value, the ' 'algorithm terminates.'), ('Normalisation factor:', 'normalisationFactor', 'base:float', 'text', 'Values in the speed image are divide by this factor.'), ('Initial distance:', 'initial_distance', 'base:int', 'text', 'Initial distance of fast marching seed points.')] # this will contain our binding to the input points self._inputPoints = None # setup the pipeline if3 = itk.Image.F3 self._fastMarching = itk.FastMarchingImageFilter[if3,if3].New() itk_kit.utils.setupITKObjectProgress( self, self._fastMarching, 'itkFastMarchingImageFilter', 'Propagating front.') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkFastMarchingImageFilter' : self._fastMarching}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._fastMarching def execute_module(self): self._transferPoints() self._fastMarching.Update() def get_input_descriptions(self): return ('Speed image (ITK, 3D, float)', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: self._fastMarching.SetInput(inputStream) else: if inputStream != self._inputPoints: # check that the inputStream is either None (meaning # disconnect) or a valid type try: if inputStream != None and \ inputStream.devideType != 'namedPoints': raise TypeError except (AttributeError, TypeError): raise TypeError, 'This input requires a points-type' self._inputPoints = inputStream def get_output_descriptions(self): return ('Front arrival times (ITK, 3D, float)',) def get_output(self, idx): return self._fastMarching.GetOutput() def config_to_logic(self): self._fastMarching.SetStoppingValue(self._config.stoppingValue) self._fastMarching.SetNormalizationFactor( self._config.normalisationFactor) def logic_to_config(self): self._config.stoppingValue = self._fastMarching.GetStoppingValue() self._config.normalisationFactor = self._fastMarching.\ GetNormalizationFactor() def _transferPoints(self): """This will transfer all points from self._inputPoints to the _fastMarching object. """ if len(self._inputPoints) > 0: # get list of discrete coordinates dcoords = [p['discrete'] for p in self._inputPoints] # use utility function to convert these to vector # container seeds = \ itk_kit.utils.coordinates_to_vector_container( dcoords, self._config.initial_distance) self._fastMarching.SetTrialPoints(seeds)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class sigmoid(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.alpha = - 0.5 self._config.beta = 3.0 self._config.min = 0.0 self._config.max = 1.0 configList = [ ('Alpha:', 'alpha', 'base:float', 'text', 'Alpha parameter for the sigmoid filter'), ('Beta:', 'beta', 'base:float', 'text', 'Beta parameter for the sigmoid filter'), ('Minimum:', 'min', 'base:float', 'text', 'Minimum output of sigmoid transform'), ('Maximum:', 'max', 'base:float', 'text', 'Maximum output of sigmoid transform')] if3 = itk.Image[itk.F, 3] self._sigmoid = itk.SigmoidImageFilter[if3,if3].New() itk_kit.utils.setupITKObjectProgress( self, self._sigmoid, 'itkSigmoidImageFilter', 'Performing sigmoid transformation') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkSigmoidImageFilter' : self._sigmoid}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._sigmoid def execute_module(self): self._sigmoid.Update() def get_input_descriptions(self): return ('Input Image (ITK Image 3D, float)',) def set_input(self, idx, inputStream): self._sigmoid.SetInput(inputStream) def get_output_descriptions(self): return ('Sigmoid Image (ITK Image, 3D, float)',) def get_output(self, idx): return self._sigmoid.GetOutput() def config_to_logic(self): self._sigmoid.SetAlpha(self._config.alpha) self._sigmoid.SetBeta(self._config.beta) self._sigmoid.SetOutputMinimum(self._config.min) self._sigmoid.SetOutputMaximum(self._config.max) def logic_to_config(self): # there're no getters for alpha, beta, min or max (itk 1.6) pass
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class symmetricDemonsRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 50 self._config.deformationSmoothingStd = 1.0 self._config.idiffThresh = 0.001 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations for the Demons registration to run.'), ('Standard deviation of vector smoothing:', 'deformationSmoothingStd', 'base:float', 'text', 'Standard deviation of Gaussian kernel used to smooth ' 'intermediate deformation field'), ('Intensity difference threshold:', 'idiffThresh', 'base:float', 'text', 'Voxels differing with less than this threshold are considered ' 'equal')] # input 1 is fixed, input 2 is moving # matcher.SetInput(moving) # matcher.SetReferenceImage(fixed) if3 = itk.Image.F3 self._matcher = itk.HistogramMatchingImageFilter[if3,if3].New() self._matcher.SetNumberOfHistogramLevels(1024) self._matcher.SetNumberOfMatchPoints(7) self._matcher.ThresholdAtMeanIntensityOn() self._demons = itk.SymmetricForcesDemonsRegistrationFilter[ itk.Image.F3, itk.Image.F3, itk.Image.VF33].New() self._demons.SetStandardDeviations(1.0) self._demons.SetMovingImage(self._matcher.GetOutput()) itk_kit.utils.setupITKObjectProgress( self, self._demons, 'itkSymmetricForcesDemonsRegistration', 'Performing registration, metric = %.2f', ('GetMetric()',)) ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkSymmetricForcesDemonsRegistrationFilter' : self._demons, 'itkHistogramMatchingImageFilter' : self._matcher}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._demons del self._matcher def execute_module(self): self.get_output(0).Update() def get_input_descriptions(self): return ('Fixed image (ITK 3D Float)', 'Moving image (ITK 3D Float)') def set_input(self, idx, inputStream): if idx == 0: self._matcher.SetReferenceImage(inputStream) self._demons.SetFixedImage(inputStream) else: self._matcher.SetInput(inputStream) def get_output_descriptions(self): return ('Deformation field (ITK 3D Float vectors)',) def get_output(self, idx): return self._demons.GetOutput() def config_to_logic(self): self._demons.SetNumberOfIterations(self._config.numberOfIterations) self._demons.SetStandardDeviations( self._config.deformationSmoothingStd) self._demons.SetIntensityDifferenceThreshold( self._config.idiffThresh) def logic_to_config(self): self._config.numberOfIterations = self._demons.GetNumberOfIterations() # we can't get the StandardDeviations back... self._config.idiffThresh = \ self._demons.GetIntensityDifferenceThreshold()
Python
# $Id$ from genMixins import subjectMixin, updateCallsExecuteModuleMixin class transformStackClass(list, subjectMixin, updateCallsExecuteModuleMixin): def __init__(self, d3Module): # call base ctors subjectMixin.__init__(self) updateCallsExecuteModuleMixin.__init__(self, d3Module) def close(self): subjectMixin.close(self) updateCallsExecuteModuleMixin.close(self)
Python
# dumy __init__ so this directory can function as a package
Python
# $Id$ from genMixins import subjectMixin, updateCallsExecuteModuleMixin class imageStackClass(list, subjectMixin, updateCallsExecuteModuleMixin): def __init__(self, d3Module): # call base ctors subjectMixin.__init__(self) updateCallsExecuteModuleMixin.__init__(self, d3Module) def close(self): subjectMixin.close(self) updateCallsExecuteModuleMixin.close(self)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk from module_base import ModuleBase import module_kits.itk_kit from module_mixins import ScriptedConfigModuleMixin class gradientAnisotropicDiffusion(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 5 self._config.conductanceParameter = 3.0 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of time-step updates (iterations) the solver will ' 'perform.'), ('Conductance parameter:', 'conductanceParameter', 'base:float', 'text', 'Sensitivity of the conductance term. Lower == more ' 'preservation of image features.')] # setup the pipeline if3 = itk.Image[itk.F, 3] d = itk.GradientAnisotropicDiffusionImageFilter[if3, if3].New() d.SetTimeStep(0.0625) # standard for 3D self._diffuse = d module_kits.itk_kit.utils.setupITKObjectProgress( self, self._diffuse, 'itkGradientAnisotropicDiffusionImageFilter', 'Smoothing data') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkGradientAnisotropicDiffusion' : self._diffuse}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._diffuse def execute_module(self): self._diffuse.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._diffuse.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._diffuse.GetOutput() def config_to_logic(self): self._diffuse.SetNumberOfIterations(self._config.numberOfIterations) self._diffuse.SetConductanceParameter( self._config.conductanceParameter) def logic_to_config(self): self._config.numberOfIterations = self._diffuse.GetNumberOfIterations() self._config.conductanceParameter = self._diffuse.\ GetConductanceParameter()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import vtk class VTKtoITK(ScriptedConfigModuleMixin, ModuleBase): 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) del self._image_cast del self._vtk2itk def execute_module(self): if self._input: # calculate input type try: self._input.Update() if self._input.IsA('vtkImageData'): input_type = self._input.GetScalarTypeAsString() except AttributeError: raise TypeError, 'VTKtoITK requires VTK image data as input.' # input_type is a text repr, e.g. 'float' or 'unsigned char' # now calculate output type if self._config.autotype: output_type = input_type else: # this is also just a text description output_type = self._config.type dims = self._input.GetDataDimension() # create shortstring (e.g. US3, SS2) short_string_type = ''.join([i[0].upper() for i in output_type.split()]) if short_string_type == 'S': short_string_type = 'SS' if short_string_type.startswith('V'): short_string = '%s%s%s' % (short_string_type, dims, dims) else: short_string = '%s%s' % (short_string_type, dims) # we could cache this as shown below, but experience shows # that the connection module often gets confused when its # input data remains the same w.r.t. type, but changes in # extent for instance. #if short_string != self._vtk2itk_short_string: self._vtk2itk = itk.VTKImageToImageFilter[ getattr(itk.Image, short_string)].New() self._vtk2itk_short_string = short_string if output_type == input_type: # we don't need the cast self._vtk2itk.SetInput(self._input) else: # we do need the cast self._image_cast.SetInput(self._input) # turn unsigned char into UnsignedChar, but signed # short into Short. # output_type is e.g. "signed short" # first break the list up, capitalise first letters captsl = ['%s%s' % (i[0].upper(), i[1:]) for i in output_type.split()] # however, VTK doesn't have the Signed bit! (so we # just want "Short") if captsl[0] == "Signed": del captsl[0] # then join them together vtk_type_string = ''.join(captsl) # cast function cast_function = getattr( self._image_cast, 'SetOutputScalarTypeTo%s' % (vtk_type_string,)) cast_function() # and connect it up self._vtk2itk.SetInput(self._image_cast.GetOutput()) self._vtk2itk.Update() def get_input_descriptions(self): return ('VTK Image Data',) def set_input(self, idx, input_stream): self._input = input_stream def get_output_descriptions(self): return ('ITK Image (3D',) def get_output(self, idx): if self._vtk2itk: return self._vtk2itk.GetOutput() else: return None def logic_to_config(self): return False def config_to_logic(self): # if the user has pressed on Apply, we change our state return True
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # TODO: # * this module is not sensitive to changes in its inputs... it should # register observers and run _createPipelines if/when they change. from imageStackRDR import imageStackClass from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import fixitk as itk from typeModules.transformStackClass import transformStackClass from typeModules.imageStackClass import imageStackClass import vtk import ConnectVTKITKPython as CVIPy class transform2D(NoConfigModuleMixin, ModuleBase): """This apply a stack of transforms to a stack of images in an accumulative fashion, i.e. imageN is transformed: Tn(Tn-1(...(T1(imageN))). The result of this filter is a vtkImageData, ready for using in your friendly neighbourhood visualisation pipeline. NOTE: this module was currently kludged to transform 1:N images (and not 0:N). 11/11/2004 (joris): kludge removed. """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageStack = None self._transformStack = None # self._itkExporterStack = [] self._imageAppend = vtk.vtkImageAppend() # stack of images should become volume self._imageAppend.SetAppendAxis(2) self._viewFrame = self._createViewFrame( {'Module (self)' : self}) self.config_to_logic() self.logic_to_config() self.config_to_view() def close(self): # just in case self.set_input(0, None) self.set_input(1, None) # take care of our refs so that things can disappear self._destroyPipelines() del self._itkExporterStack del self._imageAppend NoConfigModuleMixin.close(self) ModuleBase.close(self) def get_input_descriptions(self): return ('ITK Image Stack', '2D Transform Stack') def set_input(self, idx, inputStream): if idx == 0: if inputStream != self._imageStack: # if it's None, we have to take it if inputStream == None: # disconnect self._imageStack = None self._destroyPipelines() return # let's setup for a new stack! try: assert(inputStream.__class__.__name__ == 'imageStackClass') inputStream.Update() assert(len(inputStream) >= 2) except Exception: # if the Update call doesn't work or # if the input list is not long enough (or unsizable), # we don't do anything raise TypeError, \ "register2D requires an ITK Image Stack of minimum length 2 as input." # now check that the imageStack is the same size as the # transformStack if self._transformStack and \ len(inputStream) != len(self._transformStack): raise TypeError, \ "The Image Stack you are trying to connect has a\n" \ "different length than the connected Transform\n" \ "Stack." self._imageStack = inputStream self._createPipelines() else: # closes if idx == 0 block if inputStream != self._transformStack: if inputStream == None: self._transformStack = None self._destroyPipelines() return try: assert(inputStream.__class__.__name__ == \ 'transformStackClass') except Exception: raise TypeError, \ "register2D requires an ITK Transform Stack on " \ "this port." inputStream.Update() if len(inputStream) < 2: raise TypeError, \ "The input transform stack should be of minimum " \ "length 2." if self._imageStack and \ len(inputStream) != len(self._imageStack): raise TypeError, \ "The Transform Stack you are trying to connect\n" \ "has a different length than the connected\n" \ "Transform Stack" self._transformStack = inputStream self._createPipelines() # closes else def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageAppend.GetOutput() def execute_module(self): pass def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass # ---------------------------------------------------------------------- # non-API methods start here ------------------------------------------- # ---------------------------------------------------------------------- def _createPipelines(self): """Setup all necessary logic to transform, combine and convert all input images. Call this ONLY if things have changed, i.e. when your change observer is called or if the transform2D input ports are changed. """ if not self._imageStack or not self._transformStack: self._destroyPipelines() # in this case, we should break down the pipeline return # take care of all inputs self._imageAppend.RemoveAllInputs() #totalTrfm = itk.itkEuler2DTransform_New() totalTrfm = itk.itkCenteredRigid2DTransform_New() totalTrfm.SetIdentity() prevImage = self._imageStack[0] for trfm, img, i in zip(self._transformStack, self._imageStack, range(len(self._imageStack))): # accumulate with our totalTransform totalTrfm.Compose(trfm.GetPointer(), 0) # make a copy of the totalTransform that we can use on # THIS image # copyTotalTrfm = itk.itkEuler2DTransform_New() copyTotalTrfm = itk.itkCenteredRigid2DTransform_New() # this is a really kludge way to copy the total transform, # as concatenation doesn't update the Parameters member, so # getting and setting parameters is not the way to go copyTotalTrfm.SetIdentity() copyTotalTrfm.Compose(totalTrfm.GetPointer(),0) # this SHOULD have worked #pda = totalTrfm.GetParameters() #copyTotalTrfm.SetParameters(pda) # this actually increases the ref count of the transform! # resampler resampler = itk.itkResampleImageFilterF2F2_New() resampler.SetTransform(copyTotalTrfm.GetPointer()) resampler.SetInput(img) region = prevImage.GetLargestPossibleRegion() resampler.SetSize(region.GetSize()) resampler.SetOutputSpacing(prevImage.GetSpacing()) resampler.SetOutputOrigin(prevImage.GetOrigin()) resampler.SetDefaultPixelValue(0) # set up all the rescaler = itk.itkRescaleIntensityImageFilterF2US2_New() rescaler.SetOutputMinimum(0) rescaler.SetOutputMaximum(65535) rescaler.SetInput(resampler.GetOutput()) print "Resampling image %d" % (i,) rescaler.Update() # give ITK a chance to complain itkExporter = itk.itkVTKImageExportUS2_New() itkExporter.SetInput(rescaler.GetOutput()) # this is so the ref keeps hanging around self._itkExporterStack.append(itkExporter) vtkImporter = vtk.vtkImageImport() CVIPy.ConnectITKUS2ToVTK(itkExporter.GetPointer(), vtkImporter) # FIXME KLUDGE: we ignore image 0 (this is for joris) # if i > 0: # self._imageAppend.AddInput(vtkImporter.GetOutput()) # setup the previous Image for the next loop prevImage = img # things should now work *cough* def _destroyPipelines(self): if not self._imageStack or not self._transformStack: self._imageAppend.RemoveAllInputs() del self._itkExporterStack[:]
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class cannyEdgeDetection(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.variance = (0.7, 0.7, 0.7) self._config.maximum_error = (0.01, 0.01, 0.01) self._config.upper_threshold = 0.0 self._config.lower_threshold = 0.0 self._config.outside_value = 0.0 configList = [ ('Variance:', 'variance', 'tuple:float,3', 'text', 'Variance of Gaussian used for smoothing the input image (units: ' 'true spacing).'), ('Maximum error:', 'maximum_error', 'tuple:float,3', 'text', 'The discrete Gaussian kernel will be sized so that the ' 'truncation error is smaller than this.'), ('Upper threshold:', 'upper_threshold', 'base:float', 'text', 'Highest allowed value in the output image.'), ('Lower threshold:', 'lower_threshold', 'base:float', 'text', 'Lowest allowed value in the output image.'), ('Outside value:', 'outside_value', 'base:float', 'text', 'Pixels lower than threshold will be set to this.')] # setup the pipeline if3 = itk.Image[itk.F, 3] self._canny = itk.CannyEdgeDetectionImageFilter[if3, if3].New() itk_kit.utils.setupITKObjectProgress( self, self._canny, 'itkCannyEdgeDetectionImageFilter', 'Performing Canny edge detection') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._canny def execute_module(self): # create a new canny filter if3 = itk.Image.F3 c = itk.CannyEdgeDetectionImageFilter[if3, if3].New() c.SetInput(self._canny.GetInput()) # disconnect the old one self._canny.SetInput(None) # replace it with the new one self._canny = c # setup new progress handler itk_kit.utils.setupITKObjectProgress( self, self._canny, 'itkCannyEdgeDetectionImageFilter', 'Performing Canny edge detection') # apply our config self.sync_module_logic_with_config() # and go! self._canny.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._canny.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Edge Image (3D, float)',) def get_output(self, idx): return self._canny.GetOutput() def config_to_logic(self): # thanks to WrapITK, we can now set / get tuples / lists! # VARIANCE self._canny.SetVariance(self._config.variance) # MAXIMUM ERROR self._canny.SetMaximumError(self._config.maximum_error) # THRESHOLD self._canny.SetUpperThreshold(self._config.upper_threshold) self._canny.SetLowerThreshold(self._config.lower_threshold) # OUTSIDE VALUE self._canny.SetOutsideValue(self._config.outside_value) def logic_to_config(self): # VARIANCE self._config.variance = tuple(self._canny.GetVariance()) # MAXIMUM ERROR self._config.maximum_error = \ tuple(self._canny.GetMaximumError()) # THRESHOLDS self._config.upper_threshold = self._canny.GetUpperThreshold() self._config.lower_threshold = self._canny.GetLowerThreshold() # OUTSIDE VALUE self._config.outside_value = self._canny.GetOutsideValue()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class demonsRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 50 self._config.deformationSmoothingStd = 1.0 self._config.idiffThresh = 0.001 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations for the Demons registration to run.'), ('Standard deviation of vector smoothing:', 'deformationSmoothingStd', 'base:float', 'text', 'Standard deviation of Gaussian kernel used to smooth ' 'intermediate deformation field'), ('Intensity difference threshold:', 'idiffThresh', 'base:float', 'text', 'Voxels differing with less than this threshold are considered ' 'equal')] # input 1 is fixed, input 2 is moving # matcher.SetInput(moving) # matcher.SetReferenceImage(fixed) if3 = itk.Image.F3 self._matcher = itk.HistogramMatchingImageFilter[if3,if3].New() self._matcher.SetNumberOfHistogramLevels(1024) self._matcher.SetNumberOfMatchPoints(7) self._matcher.ThresholdAtMeanIntensityOn() self._demons = itk.DemonsRegistrationFilter[ itk.Image.F3, itk.Image.F3, itk.Image.VF33].New() self._demons.SetStandardDeviations(1.0) self._demons.SetMovingImage(self._matcher.GetOutput()) itk_kit.utils.setupITKObjectProgress( self, self._demons, 'itkDemonsRegistration', 'Performing registration, metric = %.2f', ('GetMetric()',)) ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkDemonsRegistrationFilter' : self._demons, 'itkHistogramMatchingImageFilter' : self._matcher}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._demons del self._matcher def execute_module(self): self.get_output(0).Update() def get_input_descriptions(self): return ('Fixed image (ITK 3D Float)', 'Moving image (ITK 3D Float)') def set_input(self, idx, inputStream): if idx == 0: self._matcher.SetReferenceImage(inputStream) self._demons.SetFixedImage(inputStream) else: self._matcher.SetInput(inputStream) def get_output_descriptions(self): return ('Deformation field (ITK 3D Float vectors)',) def get_output(self, idx): return self._demons.GetOutput() def config_to_logic(self): self._demons.SetNumberOfIterations(self._config.numberOfIterations) self._demons.SetStandardDeviations( self._config.deformationSmoothingStd) self._demons.SetIntensityDifferenceThreshold( self._config.idiffThresh) def logic_to_config(self): self._config.numberOfIterations = self._demons.GetNumberOfIterations() # we can't get the StandardDeviations back... self._config.idiffThresh = \ self._demons.GetIntensityDifferenceThreshold()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import copy import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import wx class ITKReader(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._config.filename = '' self._config.autotype = True self._config.type = 'float' self._config.dimensionality = '3' self._logic = copy.deepcopy(self._config) # we change this one ivar so that config_to_logic will return True # the first time self._logic.filename = None wild_card_string = 'Meta Image all-in-one (*.mha)|*.mha|' \ 'Meta Image separate header/data (*.mhd)|*.mhd|' \ 'Analyze separate header/data (*.hdr)|*.hdr|' \ 'NIfTI (*.nii)|*.nii|' \ 'NIfTI compressed (*.nii.gz)|*.nii.gz|' \ 'All files (*)|*' config_list = [ ('Filename:', 'filename', 'base:str', 'filebrowser', 'Name of file that will be loaded.', {'fileMode' : wx.OPEN, 'fileMask' : wild_card_string}), ('AutoType:', 'autotype', 'base:bool', 'checkbox', 'If activated, data type and dimensions will be determined ' 'automatically.'), ('Data type:', 'type', 'base:str', 'choice', 'Data will be cast to this type if AutoType is not used.', ['float', 'signed short', 'unsigned long']), ('Data dimensionality:', 'dimensionality', 'base:str', 'choice', 'Data will be read using this number of dimensions if AutoType ' 'is not used', ['2','3'])] # create ImageFileReader we'll be using for autotyping self._autotype_reader = itk.ImageFileReader[itk.Image.F3].New() itk_kit.utils.setupITKObjectProgress( self, self._autotype_reader, 'ImageFileReader', 'Determining type and dimensionality of file.') # and create default ImageFileReader we'll use for the actual lifting self._reader = itk.ImageFileReader[itk.Image.F3].New() self._reader_type_text = 'F3' itk_kit.utils.setupITKObjectProgress( self, self._reader, 'ImageFileReader', 'Reading file.') ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # and remove all bindings del self._autotype_reader del self._reader def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('ITK Image',) def get_output(self, idx): return self._reader.GetOutput() def logic_to_config(self): # important to return False: logic_to_config can't and # hasn't changed our config return False def config_to_logic(self): # if the user has performed an 'Apply', we want to invalidate return True def execute_module(self): if self._config.autotype: self._autotype_reader.SetFileName(self._config.filename) self._autotype_reader.UpdateOutputInformation() iio = self._autotype_reader.GetImageIO() comp_type = iio.GetComponentTypeAsString(iio.GetComponentType()) if comp_type == 'short': comp_type = 'signed_short' # lc will convert e.g. unsigned_char to UC short_type = ''.join([i[0].upper() for i in comp_type.split('_')]) dim = iio.GetNumberOfDimensions() num_comp = iio.GetNumberOfComponents() else: # lc will convert e.g. unsigned char to UC comp_type = self._config.type short_type = ''.join([i[0].upper() for i in comp_type.split(' ')]) if short_type == 'S': short_type = 'SS' dim = int(self._config.dimensionality) num_comp = 1 # e.g. F3 reader_type_text = '%s%d' % (short_type, dim) if num_comp > 1: # e.g. VF33 reader_type_text = 'V%s%d' % (reader_type_text, num_comp) # if things have changed, make a new reader, else re-use the old if reader_type_text != self._reader_type_text: # equivalent to e.g. itk.Image.UC3 self._reader = itk.ImageFileReader[ getattr(itk.Image, reader_type_text)].New() self._reader_type_text = reader_type_text print reader_type_text itk_kit.utils.setupITKObjectProgress( self, self._reader, 'ImageFileReader', 'Reading file.') # now do the actual reading self._reader.SetFileName(self._config.filename) self._reader.Update()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class gaussianConvolve(ScriptedConfigModuleMixin, ModuleBase): _orders = ['Zero', 'First', 'Second'] def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.direction = 0 self._config.sigma = 1.0 self._config.order = 'Zero' self._config.normaliseAcrossScale = False configList = [ ('Direction:', 'direction', 'base:int', 'choice', 'Direction in which the filter has to be applied.', ['0', '1', '2']), ('Sigma:', 'sigma', 'base:float', 'text', 'Sigma of Gaussian kernel in world coordinates.'), ('Order of Gaussian', 'order', 'base:str', 'choice', 'Convolve with Gaussian, or first or second derivative.', tuple(self._orders)), ('Normalise across scale', 'normaliseAcrossScale', 'base:bool', 'checkbox', 'Determine and use normalisation factor.')] # setup the pipeline if3 = itk.Image[itk.F, 3] self._gaussian = itk.RecursiveGaussianImageFilter[if3,if3].New() itk_kit.utils.setupITKObjectProgress( self, self._gaussian, 'itkRecursiveGaussianImageFilter', 'Convolving with Gaussian') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkRecursiveGaussianImageFilter' : self._gaussian}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gaussian def execute_module(self): self._gaussian.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._gaussian.SetInput(inputStream) def get_output_descriptions(self): return ('Blurred ITK Image (3D, float)',) def get_output(self, idx): return self._gaussian.GetOutput() def config_to_logic(self): self._gaussian.SetDirection(self._config.direction) # SIGMA self._gaussian.SetSigma(self._config.sigma) # ORDER if self._config.order == 'Zero': self._gaussian.SetZeroOrder() elif self._config.order == 'First': self._gaussian.SetFirstOrder() elif self._config.order == 'Second': self._gaussian.SetSecondOrder() else: self._config.order = 'Zero' self._gaussian.SetZeroOrder() # NORMALISEACROSSSCALE self._gaussian.SetNormalizeAcrossScale( self._config.normaliseAcrossScale) def logic_to_config(self): self._config.direction = self._gaussian.GetDirection() # SIGMA self._config.sigma = self._gaussian.GetSigma() # ORDER # FIMXE: dammit, we can't get the order. # NORMALISEACROSSSCALE self._config.normaliseAcrossScale = self._gaussian.\ GetNormalizeAcrossScale()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from typeModules.transformStackClass import transformStackClass import cPickle from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import wx import vtk class transformStackWRT(ModuleBase, FilenameViewModuleMixin): """Writes 2D Transform Stack to disc. Use this module to save the results of a register2D session. """ def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin FilenameViewModuleMixin.__init__(self) # this is the input self._transformStack = None # we now have a viewFrame in self._viewFrame self._createViewFrame( 'Select a filename', '2D Transform Stack file (*.2ts)|*.2ts|All files (*)|*', objectDict=None) # set up some defaults self._config.filename = '' self.configToLogic() # make sure these filter through from the bottom up self.logicToConfig() self.configToView() def close(self): # we should disconnect all inputs self.setInput(0, None) del self._transformStack FilenameViewModuleMixin.close(self) def getInputDescriptions(self): return ('2D Transform Stack',) def setInput(self, idx, inputStream): if inputStream != self._transformStack: if inputStream == None: # disconnect self._transformStack = None return if not inputStream.__class__.__name__ == 'transformStackClass': raise TypeError, \ 'transformStackWRT requires a transformStack at input' self._transformStack = inputStream def getOutputDescriptions(self): return () def getOutput(self, idx): raise Exception def logicToConfig(self): pass def configToLogic(self): pass def viewToConfig(self): self._config.filename = self._getViewFrameFilename() def configToView(self): self._setViewFrameFilename(self._config.filename) def executeModule(self): if len(self._config.filename): self._writeTransformStack(self._transformStack, self._config.filename) def view(self, parent_window=None): # if the frame is already visible, bring it to the top; this makes # it easier for the user to associate a frame with a glyph if not self._viewFrame.Show(True): self._viewFrame.Raise() def _writeTransformStack(self, transformStack, filename): if not transformStack: md = wx.MessageDialog( self._module_manager.get_module_view_parent_window(), 'Input transform Stack is empty or not connected, not saving.', "Information", wx.OK | wx.ICON_INFORMATION) md.ShowModal() return # let's try and open the file try: # opened for binary writing transformFile = file(filename, 'wb') except IOError, ioemsg: raise IOError, 'Could not open %s for writing:\n%s' % \ (filename, ioemsg) # convert transformStack to list of tuples pickleList = [] for transform in transformStack: name = transform.GetNameOfClass() nop = transform.GetNumberOfParameters() pda = transform.GetParameters() paramsTup = tuple([pda.GetElement(i) for i in range(nop)]) pickleList.append((name, paramsTup)) cPickle.dump(pickleList, transformFile, True)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # mini-changelog # * added work-around for empty input bug in ITK 3.20 from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import itk import module_kits.itk_kit as itk_kit class isolatedConnect(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._config.replace_value = 1.0 self._config.upper_threshold = False config_list = [ ('Replace value:', 'replace_value', 'base:float', 'text', 'Voxels touching the first set of seeds will be set to this ' 'value.'), ('Upper threshold:', 'upper_threshold', 'base:bool', 'checkbox', 'Derive upper threshold (for dark areas) or lower threshold ' '(for lighter areas).')] if3 = itk.Image.F3 self._isol_connect = \ itk.IsolatedConnectedImageFilter[if3,if3].New() # due to a bug in ITK, we can never have empty seed lists # http://code.google.com/p/devide/issues/detail?id=221 self._isol_connect.SetSeed1(itk.Index[3]([0,0,0])) self._isol_connect.SetSeed2(itk.Index[3]([0,0,0])) # this will be our internal list of points self._seeds1 = [] self._seeds2 = [] itk_kit.utils.setupITKObjectProgress( self, self._isol_connect, 'IsolatedConnectedImageFilter', 'Performing isolated connect') ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'IsolatedConnectedImageFilter' : self._isol_connect}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) del self._isol_connect def get_input_descriptions(self): return ('ITK Image data', 'Seed points 1', 'Seed points 2') def set_input(self, idx, input_stream): if idx == 0: self._isol_connect.SetInput(input_stream) else: seeds = [self._seeds1, self._seeds2] conn_map = {'ClearSeeds' : [self._isol_connect.ClearSeeds1, self._isol_connect.ClearSeeds2], 'AddSeeds' : [self._isol_connect.AddSeed1, self._isol_connect.AddSeed2], 'SetSeeds' : [self._isol_connect.SetSeed1, self._isol_connect.SetSeed2], 'seeds' : [self._seeds1, self._seeds2]} # list of seeds we already have for this input our_list = conn_map['seeds'][idx-1] if input_stream == None: # only clear seeds if not already the case if len(our_list) > 0: print "isolatedConnect: nuking list on input", idx-1 # this means we get to nuke all seeds # due to bug in ITK 3.20, we have to add a dummy seed. conn_map['SetSeeds'][idx-1](itk.Index[3]([0,0,0])) del our_list[:] elif hasattr(input_stream, 'devideType') and \ input_stream.devideType == 'namedPoints': dpoints = [i['discrete'] for i in input_stream] # if the new list differs from ours, copy it if dpoints != our_list: print "isolatedConnect: copying new list on input", idx-1 del our_list[:] our_list.extend(dpoints) conn_map['ClearSeeds'][idx-1]() for p in our_list: index = itk.Index[3](p) conn_map['AddSeeds'][idx-1](index) # work-around for bug in ITK 3.20. we can't have empty seed lists ever if len(our_list) == 0: conn_map['SetSeeds'][idx-1](itk.Index[3]([0,0,0])) else: raise TypeError, 'This input requires a named points type.' def get_output_descriptions(self): return ('Segmented ITK image', 'Derived threshold') def get_output(self, idx): if idx == 0: return self._isol_connect.GetOutput() else: return self._isol_connect.GetIsolatedValue() def logic_to_config(self): self._config.upper_threshold = \ self._isol_connect.GetFindUpperThreshold() self._config.replace_value = self._isol_connect.GetReplaceValue() def config_to_logic(self): self._isol_connect.SetFindUpperThreshold(self._config.upper_threshold) self._isol_connect.SetReplaceValue(self._config.replace_value) def execute_module(self): self._isol_connect.Update() def _inputPointsObserver(self, obj): # extract a list from the input points tempList = [] if self._inputPoints: for i in self._inputPoints: tempList.append(i['discrete']) if len(tempList) >= 2 and tempList != self._seedPoints: self._seedPoints = tempList #self._seedConnect.RemoveAllSeeds() idx1 = itk.itkIndex3() idx2 = itk.itkIndex3() for ei in range(3): idx1.SetElement(ei, self._seedPoints[0][ei]) idx2.SetElement(ei, self._seedPoints[1][ei]) self._isol_connect.SetSeed1(idx1) self._isol_connect.SetSeed2(idx2)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import vtk class ITKtoVTK(NoConfigModuleMixin, ModuleBase): """Convert ITK 3D float data to VTK. $Revision: 1.5 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._input = None self._itk2vtk = None NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'ImageToVTKImageFilter' : self._itk2vtk}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) del self._itk2vtk def execute_module(self): if self._input: try: shortstring = itk_kit.utils.get_img_type_and_dim_shortstring( self._input) except TypeError: raise TypeError, 'ITKtoVTK requires an ITK image as input.' witk_template = getattr(itk, 'ImageToVTKImageFilter') witk_type = getattr(itk.Image, shortstring) try: self._itk2vtk = witk_template[witk_type].New() except KeyError, e: raise RuntimeError, 'Unable to instantiate ITK to VTK ' \ 'converter with type %s.' % \ (shortstring,) else: self._input.UpdateOutputInformation() self._input.SetBufferedRegion( self._input.GetLargestPossibleRegion()) self._input.Update() itk_kit.utils.setupITKObjectProgress( self, self._itk2vtk, 'ImageToVTKImageFilter', 'Converting ITK image to VTK image.') self._itk2vtk.SetInput(self._input) self._itk2vtk.Update() def get_input_descriptions(self): return ('ITK Image',) def set_input(self, idx, input_stream): self._input = input_stream def get_output_descriptions(self): return ('VTK Image Data',) def get_output(self, idx): if self._itk2vtk is not None: return self._itk2vtk.GetOutput() else: return None def logic_to_config(self): # important so that ModuleManager doesn't think our state has changed return False def config_to_logic(self): # important so that ModuleManager doesn't think our state has changed return False def view_to_config(self): pass def config_to_view(self): pass
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import gen_utils import module_kits.itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class watershed(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # pre-processing on input image: it will be thresholded self._config.threshold = 0.1 # flood level: this will be the starting level of precipitation self._config.level = 0.1 configList = [ ('Threshold:', 'threshold', 'base:float', 'text', 'Pre-processing image threshold (0.0-1.0).'), ('Level:', 'level', 'base:float', 'text', 'Initial precipitation level (0.0-1.0).')] # setup the pipeline if3 = itk.Image[itk.F, 3] self._watershed = itk.WatershedImageFilter[if3].New() module_kits.itk_kit.utils.setupITKObjectProgress( self, self._watershed, 'itkWatershedImageFilter', 'Performing watershed') iul3 = itk.Image[itk.UL, 3] # change this to SI or UI when this becomes available in the # wrappings iss3 = itk.Image[itk.SS, 3] self._relabel_components = \ itk.RelabelComponentImageFilter[iul3, iss3].New() self._relabel_components.SetInput(self._watershed.GetOutput()) module_kits.itk_kit.utils.setupITKObjectProgress( self, self._relabel_components, 'itk.RelabelComponentImageFilter', 'Relabeling watershed output components') # self._watershed could be changed later, so we don't add it # to the introspection list. ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._watershed def execute_module(self): self._relabel_components.Update() # the watershed module is REALLY CRAP about setting progress to 100, # so we do it here. #self._module_manager.setProgress(100, "Watershed complete.") def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): try: self._watershed.SetInput(inputStream) except TypeError, e: # deduce the type itku = module_kits.itk_kit.utils ss = itku.get_img_type_and_dim_shortstring(inputStream) try: w = itk.WatershedImageFilter[getattr(itk.Image,ss)].New() except KeyError, e: emsg = 'Could not create Watershed with input type %s. '\ 'Please try a different input type.' % (ss,) raise TypeError, emsg # if we get here, we have a new filter # disconnect old one self._watershed.SetInput(None) # replace with new one (old one should be garbage # collected) self._watershed = w # reconnect it to the input of the relabeler self._relabel_components.SetInput(self._watershed.GetOutput()) # setup progress module_kits.itk_kit.utils.setupITKObjectProgress( self, self._watershed, 'itkWatershedImageFilter', 'Performing watershed') # re-apply config self.sync_module_logic_with_config() # connect input and hope it works. self._watershed.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, unsigned long)',) def get_output(self, idx): return self._relabel_components.GetOutput() def config_to_logic(self): self._config.threshold = gen_utils.clampVariable( self._config.threshold, 0.0, 1.0) self._watershed.SetThreshold(self._config.threshold) self._config.level = gen_utils.clampVariable( self._config.level, 0.0, 1.0) self._watershed.SetLevel(self._config.level) def logic_to_config(self): self._config.threshold = self._watershed.GetThreshold() self._config.level = self._watershed.GetLevel()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. class ITKtoVTK: kits = ['itk_kit'] cats = ['Insight'] help = """Use this module to convert from any ITK image type to the corresponding VTK type. """ class VTKtoITK: kits = ['itk_kit'] cats = ['Insight'] help = """Convert from a VTK image to an ITK image. By default (AutoType active), the output ITK image has the same pixel type as the input VTK image. However, if AutoType has been unchecked in the configuration, the output ITK image has 'Data type' as its type. """ class cannyEdgeDetection: kits = ['itk_kit'] cats = ['Insight'] help = """Performs 3D Canny edge detection on input image. A rule of thumb for the thersholds: lower threshold == 0.5 * upper threshold. NOTE: Due to a bug in ITK [1], the Canny filter gives invalid results when run more than once with different sets of parameters. To work around this, DeVIDE re-instantiates the canny filter at every execution. This means that only parameters that you see in the GUI are transferred to the new instance. [1] http://www.itk.org/pipermail/insight-users/2009-August/032018.html """ class confidenceSeedConnect: kits = ['itk_kit'] cats = ['Insight'] keywords = ['region growing', 'confidence', 'seed'] help = """Confidence-based 3D region growing. This module will perform a 3D region growing starting from the user-supplied points. The mean and standard deviation are calculated in a small initial region around the seed points. New contiguous points have to have intensities on the range [mean - f*stdDev, mean + f*stdDev] to be included. f is user-definable. After this initial growing iteration, if the user has specified a larger than 0 number of iterations, the mean and standard deviation are recalculated over all the currently selected points and the process is restarted. This process is repeated for the user-defined number of iterations, or until now new pixels are added. Due to weirdness in the underlying ITK filter, deleting all points won't quite work. In other words, the output of this module can only be trusted if there's at least a single seed point. """ class curvatureAnisotropicDiffusion: kits = ['itk_kit'] cats = ['Insight'] class curvatureFlowDenoising: kits = ['itk_kit'] cats = ['Insight', 'Level Sets'] help = """Curvature-driven image denoising. This uses curvature-based level set techniques to smooth homogeneous regions whilst retaining boundary information. """ class DanielssonDistance: kits = ['itk_kit'] cats = ['Insight'] help = """Calculates distance image of input image. The input image can either contain marked objects or binary objects. """ class demonsRegistration: kits = ['itk_kit'] cats = ['Insight', 'Registration', 'Optic Flow'] help = """Performs demons registration on fixed and moving input images, returns deformation field. The intensity difference threshold is absolute, so check the values in your datasets and adjust it accordingly. For example, if you find that two regions should match but you see intensity differences of 50 (e.g. in a CT dataset), the threshold should be approximately 60. NOTE: remember to update help w.r.t. inverse direction of vectors in deformation field. Also read this thread: http://public.kitware.com/pipermail/insight-users/2004-November/011002.html """ class discreteLaplacian: kits = ['itk_kit'] cats = ['Insight'] help = """Calculates Laplacian of input image. This makes use of a discrete implementation. Due to this, the input image should probably be pre-smoothed with e.g. a Gaussian as the Laplacian is very sensitive to noise. Note: One could also calculate the Laplacian by convolving with the second derivative of a Gaussian. Laplacian == secondPartialDerivative(f,x0) + ... + secondPartialDerivative(f,xn) """ # had to disable this one due to stupid itkLevelSetNode non-wrapping # in ITK-2-4-1 class fastMarching: kits = ['itk_kit'] cats = ['Insight', 'Level Sets'] help = """Given a set of seed points and a speed image, this module will propagate a moving front out from those points using the fast marching level set formulation. """ class gaussianConvolve: kits = ['itk_kit'] cats = ['Insight'] help = """Convolves input with Gaussian, or its first or second derivative. Only a single dimension is convolved (i.e. the filter is separated). Select which dimension in the View/Config window. The convolution is implemented as an IIR filter. $Revision: 1.4 $ """ class geodesicActiveContour: kits = ['itk_kit'] cats = ['Insight', 'Level Sets'] keywords = ['level set'] help = """Module for performing Geodesic Active Contour-based segmentation on 3D data. The input feature image is an edge potential map with values close to 0 in regions close to the edges and values close to 1 otherwise. The level set speed function is based on this. For example: smooth an input image, determine the gradient magnitude and then pass it through a sigmoid transformation to create an edge potential map. The initial level set is a volume with the initial surface embedded as the 0 level set, i.e. the 0-value iso-contour (more or less). Also see figure 9.18 in the ITK Software Guide. """ class gradientAnisotropicDiffusion: kits = ['itk_kit'] cats = ['Insight'] help = """Performs a gradient-based anisotropic diffusion. This will smooth homogeneous areas whilst preserving features (e.g. edges). """ class gradientMagnitudeGaussian: kits = ['itk_kit'] cats = ['Insight'] help = """Calculates gradient magnitude of an image by convolving with the derivative of a Gaussian. The ITK class that this is based on uses a recursive gaussian filter implementation. """ # isn't wrapped anymore, no idea why. #class gvfgac: # kits = ['itk_kit'] # cats = ['Insight'] # will fix when I rework the registration modules #class imageStackRDR: # kits = ['itk_kit'] # cats = ['Insight'] class isolatedConnect: kits = ['itk_kit'] cats = ['Insight'] keywords = ['segment'] help = """Voxels connected to the first group of seeds and NOT connected to the second group of seeds are segmented by optimising an upper or lower threshold. For example, to separate two non-touching light objects, you would do the following: <ul> <li>Select point(s) in the first object with slice3dVWR 1</li> <li>Select point(s) in the second object with slice3dVWR 2</li> <li>Connect up the three inputs of isolatedConnect as follows: input image, point(s) of object 1, point(s) of object 2</li> <li>isolatedConnect will now calculate a threshold so that when this threshold is applied to the image and a region growing is performed using the first set of points, only object 1 will be separated.</li> </il> </ul> """ class ITKReader: kits = ['itk_kit'] cats = ['Insight', 'Readers'] help = """Reads all the 3D formats supported by ITK. In its default configuration, this module will derive file type, data type and dimensionality from the file itself. You can manually set the data type and dimensionality, in which case ITK will attempt to cast the data. Keep in mind that DeVIDE mostly uses the float versions of ITK components. At least the following file formats are available (a choice is made based on the filename extension that you choose):<br> <ul> <li>.mha: MetaImage all-in-one file</li> <li>.mhd: MetaImage .mhd header file and .raw data file</li> <li>.hdr or .img: Analyze .hdr header and .img data</li> </ul> """ class ITKWriter: kits = ['itk_kit'] cats = ['Insight', 'Writers'] help = """Writes any of the image formats supported by ITK. At least the following file formats are available (a choice is made based on the filename extension that you choose):<br> <ul> <li>.mha: MetaImage all-in-one file</li> <li>.mhd: MetaImage .mhd header file and .raw data file</li> <li>.hdr or .img: Analyze .hdr header and .img data</li> </ul> """ # not wrapped by ITK-2-4-1 default wrappings class levelSetMotionRegistration: kits = ['itk_kit'] cats = ['Insight', 'Registration', 'Level Sets'] keywords = ['level set', 'registration', 'deformable', 'non-rigid'] help = """Performs deformable registration between two input volumes using level set motion. """ # not wrapped by WrapITK 20060710 # class nbCurvesLevelSet: # kits = ['itk_kit'] # cats = ['Insight', 'Level Set'] # keywords = ['level set'] # help = """Narrow band level set implementation. # The input feature image is an edge potential map with values close to 0 in # regions close to the edges and values close to 1 otherwise. The level set # speed function is based on this. For example: smooth an input image, # determine the gradient magnitude and then pass it through a sigmoid # transformation to create an edge potential map. # The initial level set is a volume with the initial surface embedded as the # 0 level set, i.e. the 0-value iso-contour (more or less). # """ class nbhSeedConnect: kits = ['itk_kit'] cats = ['Insight'] help = """Neighbourhood-based 3D region growing. This module will perform a 3D region growing starting from the user-supplied points. Only pixels with intensities between the user-configurable thresholds and with complete neighbourhoods where all pixels have intensities between the thresholds are considered valid candidates. The size of the neighbourhood can be set as well. """ # reactivate when I rework the registration modules #class register2D: # kits = ['itk_kit'] # cats = ['Insight'] class sigmoid: kits = ['itk_kit'] cats = ['Insight'] help = """Perform sigmoid transformation on all input voxels. f(x) = (max - min) frac{1}{1 + exp(- frac{x - beta}{alpha})} + min """ class symmetricDemonsRegistration: kits = ['itk_kit'] cats = ['Insight', 'Registration', 'Optic Flow'] help = """Performs symmetric forces demons registration on fixed and moving input images, returns deformation field. """ class tpgac: kits = ['itk_kit'] cats = ['Insight', 'Level Sets'] keywords = ['segment', 'level set'] help = """Module for performing topology-preserving Geodesic Active Contour-based segmentation on 3D data. This module requires a DeVIDE-specific ITK class. The input feature image is an edge potential map with values close to 0 in regions close to the edges and values close to 1 otherwise. The level set speed function is based on this. For example: smooth an input image, determine the gradient magnitude and then pass it through a sigmoid transformation to create an edge potential map. The initial level set is a volume with the initial surface embedded as the 0 level set, i.e. the 0-value iso-contour (more or less). Also see figure 9.18 in the ITK Software Guide. """ # will work on this when I rework the 2D registration #class transform2D: # kits = ['itk_kit'] # cats = ['Insight'] #class transformStackRDR: # kits = ['itk_kit'] # cats = ['Insight'] #class transformStackWRT: # kits = ['itk_kit'] # cats = ['Insight'] class watershed: kits = ['itk_kit'] cats = ['Insight'] help = """Perform watershed segmentation on input. Typically, the input will be the gradient magnitude image. Often, data is smoothed with one of the anisotropic diffusion filters and then the gradient magnitude image is calculated. This serves as input to the watershed module. """
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class DanielssonDistance(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.squared_distance = False self._config.binary_input = True self._config.image_spacing = True configList = [ ('Squared distance:', 'squared_distance', 'base:bool', 'checkbox', 'Should the distance output be squared (faster) or true.'), ('Use image spacing:', 'image_spacing', 'base:bool', 'checkbox', 'Use image spacing in distance calculation.'), ('Binary input:', 'binary_input', 'base:bool', 'checkbox', 'Does the input contain marked objects, or binary (yes/no) ' 'objects.')] # setup the pipeline imageF3 = itk.Image[itk.F, 3] self._dist_filter = None self._create_pipeline(imageF3) # THIS HAS TO BE ON. SO THERE. #self._dist_filter.SetUseImageSpacing(True) ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkDanielssonDistanceMapImageFilter' : self._dist_filter}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._dist_filter def execute_module(self): self._dist_filter.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): try: self._dist_filter.SetInput(inputStream) except TypeError, e: # deduce the type itku = itk_kit.utils ss = itku.get_img_type_and_dim_shortstring(inputStream) img_type = getattr(itk.Image,ss) # try to build a new pipeline (will throw exception if it # can't) self._create_pipeline(img_type) # re-apply config self.sync_module_logic_with_config() # connect input and hope it works. self._dist_filter.SetInput(inputStream) def get_output_descriptions(self): return ('Distance map (ITK 3D, float)', 'Voronoi map (ITK 3D float)') def get_output(self, idx): return self._dist_filter.GetOutput() def config_to_logic(self): self._dist_filter.SetInputIsBinary(self._config.binary_input) self._dist_filter.SetSquaredDistance(self._config.squared_distance) self._dist_filter.SetUseImageSpacing(self._config.image_spacing) def logic_to_config(self): self._config.binary_input = self._dist_filter.GetInputIsBinary() self._config.squared_distance = self._dist_filter.GetSquaredDistance() self._config._image_spacing = self._dist_filter.GetUseImageSpacing() def _create_pipeline(self, img_type): """Standard pattern to create ITK pipeline according to passed image type. """ try: d = itk.DanielssonDistanceMapImageFilter[ img_type, img_type].New() except KeyError, e: emsg = 'Could not create DanielssonDist with input type %s. '\ 'Please try a different input type.' % (ss,) raise TypeError, emsg # if successful, we can disconnect the old filter and store # the instance (needed for the progress call!) if self._dist_filter: self._dist_filter.SetInput(None) self._dist_filter = d # setup progress itku = itk_kit.utils itku.setupITKObjectProgress( self, self._dist_filter, 'DanielssonDistanceMapImageFilter', 'Calculating distance map.')
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import vtk class VTKtoITKF3(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup the pipeline self._imageCast = vtk.vtkImageCast() self._imageCast.SetOutputScalarTypeToFloat() self._vtk2itk = itk.VTKImageToImageFilter[itk.Image[itk.F, 3]].New() self._vtk2itk.SetInput(self._imageCast.GetOutput()) NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageCast' : self._imageCast, 'VTKImageToImageFilter' : self._vtk2itk}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) del self._imageCast del self._vtk2itk def execute_module(self): # the whole connectvtkitk thingy is quite shaky and was really # designed for demand-driven use. using it in an event-driven # environment, we have to make sure it does exactly what we want # it to do. one day, we'll implement contracts and do this # differently. #o = self._itkImporter.GetOutput() #o.UpdateOutputInformation() #o.SetRequestedRegionToLargestPossibleRegion() #o.Update() self._vtk2itk.Update() def get_input_descriptions(self): return ('VTK Image Data',) def set_input(self, idx, inputStream): self._imageCast.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._vtk2itk.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class geodesicActiveContour(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup defaults self._config.propagationScaling = 1.0 self._config.curvatureScaling = 1.0 self._config.advectionScaling = 1.0 self._config.numberOfIterations = 100 configList = [ ('Propagation scaling:', 'propagationScaling', 'base:float', 'text', 'Propagation scaling parameter for the geodesic active ' 'contour, ' 'i.e. balloon force. Positive for outwards, negative for ' 'inwards.'), ('Curvature scaling:', 'curvatureScaling', 'base:float', 'text', 'Curvature scaling term weighting.'), ('Advection scaling:', 'advectionScaling', 'base:float', 'text', 'Advection scaling term weighting.'), ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations that the algorithm should be run for')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) # create all pipeline thingies self._geodesicActiveContour = None self._create_pipeline(itk.Image.F3) self.sync_module_logic_with_config() def close(self): self._destroyITKPipeline() ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def execute_module(self): self.get_output(0).Update() self._module_manager.setProgress( 100, "Geodesic active contour complete.") def get_input_descriptions(self): return ('Feature image (ITK)', 'Initial level set (ITK)' ) def set_input(self, idx, inputStream): try: if idx == 0: self._geodesicActiveContour.SetFeatureImage(inputStream) else: self._geodesicActiveContour.SetInput(inputStream) except TypeError, e: feat = self._geodesicActiveContour.GetFeatureImage() inp_img = self._geodesicActiveContour.GetInput() # deduce the type itku = itk_kit.utils ss = itku.get_img_type_and_dim_shortstring(inputStream) # either the other input has to be None, or match the type of the new input if idx == 0: if inp_img is not None: other_ss = itku.get_img_type_and_dim_shortstring(inp_img) if other_ss != ss: raise TypeError('Types of feature image and initial level set have to match.') else: if feat is not None: other_ss = itku.get_img_type_and_dim_shortstring(feat) if other_ss != ss: raise TypeError('Types of feature image and initial level set have to match.') img_type = getattr(itk.Image,ss) # try to build a new pipeline (will throw exception if it # can't) self._create_pipeline(img_type) # re-apply config self.sync_module_logic_with_config() # connect everything up if idx == 0: self._geodesicActiveContour.SetFeatureImage(inputStream) self._geodesicActiveContour.SetInput(inp_img) else: self._geodesicActiveContour.SetFeatureImage(feat) self._geodesicActiveContour.SetInput(inputStream) def get_output_descriptions(self): return ('Final level set (ITK Float 3D)',) def get_output(self, idx): return self._geodesicActiveContour.GetOutput() def config_to_logic(self): self._geodesicActiveContour.SetPropagationScaling( self._config.propagationScaling) self._geodesicActiveContour.SetCurvatureScaling( self._config.curvatureScaling) self._geodesicActiveContour.SetAdvectionScaling( self._config.advectionScaling) self._geodesicActiveContour.SetNumberOfIterations( self._config.numberOfIterations) def logic_to_config(self): self._config.propagationScaling = self._geodesicActiveContour.\ GetPropagationScaling() self._config.curvatureScaling = self._geodesicActiveContour.\ GetCurvatureScaling() self._config.advectionScaling = self._geodesicActiveContour.\ GetAdvectionScaling() self._config.numberOfIterations = self._geodesicActiveContour.\ GetNumberOfIterations() # -------------------------------------------------------------------- # END OF API CALLS # -------------------------------------------------------------------- def _create_pipeline(self, img_type): try: g = \ itk.GeodesicActiveContourLevelSetImageFilter[ img_type,img_type,itk.F].New() except KeyError, e: emsg = 'Could not create GAC filter with input type %s. '\ 'Please try a different input type.' % (ss,) raise TypeError, emsg # if successful, we can disconnect the old filter and store # the instance (needed for the progress call!) if self._geodesicActiveContour: self._geodesicActiveContour.SetInput(None) self._geodesicActiveContour = g itk_kit.utils.setupITKObjectProgress( self, self._geodesicActiveContour, 'GeodesicActiveContourLevelSetImageFilter', 'Growing active contour') def _destroyITKPipeline(self): """Delete all bindings to components of the ITK pipeline. """ del self._geodesicActiveContour
Python
# dumy __init__ so this directory can function as a package
Python
# dumy __init__ so this directory can function as a package
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class gradientMagnitudeGaussian(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.gaussianSigma = 0.7 self._config.normaliseAcrossScale = False configList = [ ('Gaussian sigma', 'gaussianSigma', 'base:float', 'text', 'Sigma in terms of image spacing.'), ('Normalise across scale', 'normaliseAcrossScale', 'base:bool', 'checkbox', 'Determine normalisation factor.')] # setup the pipeline self._gradientMagnitude = None img_type = itk.Image.F3 self._create_pipeline(img_type) ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'itkGradientMagnitudeRecursiveGaussianImageFilter' : self._gradientMagnitude}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gradientMagnitude def execute_module(self): self._gradientMagnitude.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): try: self._gradientMagnitude.SetInput(inputStream) except TypeError, e: # deduce the type itku = itk_kit.utils ss = itku.get_img_type_and_dim_shortstring(inputStream) img_type = getattr(itk.Image,ss) # try to build a new pipeline (will throw exception if it # can't) self._create_pipeline(img_type) # re-apply config self.sync_module_logic_with_config() # connect input and hope it works. self._gradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image',) def get_output(self, idx): return self._gradientMagnitude.GetOutput() def config_to_logic(self): self._gradientMagnitude.SetSigma(self._config.gaussianSigma) self._gradientMagnitude.SetNormalizeAcrossScale( self._config.normaliseAcrossScale) def logic_to_config(self): # durnit, there's no GetSigma(). Doh. self._config.normaliseAcrossScale = self._gradientMagnitude.\ GetNormalizeAcrossScale() def _create_pipeline(self, img_type): """Standard pattern to create ITK pipeline according to passed image type. """ c = itk.GradientMagnitudeRecursiveGaussianImageFilter try: g = c[img_type, img_type].New() except KeyError, e: emsg = 'Could not create GradMag with input type %s. '\ 'Please try a different input type.' % (ss,) raise TypeError, emsg # if successful, we can disconnect the old filter and store # the instance (needed for the progress call!) if self._gradientMagnitude: self._gradientMagnitude.SetInput(None) self._gradientMagnitude = g itk_kit.utils.setupITKObjectProgress( self, self._gradientMagnitude, 'itkGradientMagnitudeRecursiveGaussianImageFilter', 'Calculating gradient image')
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class levelSetMotionRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.numberOfIterations = 50 self._config.gradSmoothStd = 1.0 self._config.alpha = 0.1 self._config.idiffThresh = 0.001 configList = [ ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations for the Demons registration to run.'), ('Gradient smoothing standard deviation:', 'gradSmoothStd', 'base:float', 'text', 'The standard deviation of the Gaussian kernel in physical ' 'units that will be ' 'used to smooth the images before calculating gradients.'), ('Stability parameter alpha:', 'alpha', 'base:float', 'text', 'Used to stabilise small gradient magnitude values. Set to ' 'approximately 0.04% of intensity range of input images.'), ('Intensity difference threshold:', 'idiffThresh', 'base:float', 'text', 'Voxels differing with less than this threshold are considered ' 'equal')] # input 1 is fixed, input 2 is moving # matcher.SetInput(moving) # matcher.SetReferenceImage(fixed) if3 = itk.Image.F3 self._matcher = itk.HistogramMatchingImageFilter[if3,if3].New() self._matcher.SetNumberOfHistogramLevels(1024) self._matcher.SetNumberOfMatchPoints(7) self._matcher.ThresholdAtMeanIntensityOn() ivf3 = itk.Image.VF33 ls = itk.LevelSetMotionRegistrationFilter[if3, if3, ivf3].New() self._levelSetMotion = ls self._levelSetMotion.SetMovingImage(self._matcher.GetOutput()) # we should get a hold of GetElapsedIterations... # DenseFiniteDifference -> PDEDeformableRegistration -> LevelSetMotion # Dense still has it, PDE onwards doesn't. Dense is templated on # input and output, PDE on two image types and a deformation field... itk_kit.utils.setupITKObjectProgress( self, self._levelSetMotion, 'LevelSetMotionRegistrationFilter', 'Performing registration, metric = %.2f', ('GetMetric()',)) ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'LevelSetMotionRegistrationFilter' : self._levelSetMotion, 'itkHistogramMatchingImageFilter' : self._matcher}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._levelSetMotion del self._matcher def execute_module(self): self.get_output(0).Update() def get_input_descriptions(self): return ('Fixed image (ITK 3D Float)', 'Moving image (ITK 3D Float)') def set_input(self, idx, inputStream): if idx == 0: self._matcher.SetReferenceImage(inputStream) self._levelSetMotion.SetFixedImage(inputStream) else: self._matcher.SetInput(inputStream) def get_output_descriptions(self): return ('Deformation field (ITK 3D Float vectors)',) def get_output(self, idx): return self._levelSetMotion.GetOutput() def config_to_logic(self): self._levelSetMotion.SetNumberOfIterations( self._config.numberOfIterations) self._levelSetMotion.SetGradientSmoothingStandardDeviations( self._config.gradSmoothStd) self._levelSetMotion.SetAlpha(self._config.alpha) self._levelSetMotion.SetIntensityDifferenceThreshold( self._config.idiffThresh) def logic_to_config(self): self._config.numberOfIterations = self._levelSetMotion.\ GetNumberOfIterations() self._config.gradSmoothStd = \ self._levelSetMotion.\ GetGradientSmoothingStandardDeviations() self._config.alpha = \ self._levelSetMotion.GetAlpha() self._config.idiffThresh = \ self._levelSetMotion.\ GetIntensityDifferenceThreshold()
Python
# dumy __init__ so this directory can function as a package
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from typeModules.transformStackClass import transformStackClass import cPickle import fixitk as itk import md5 from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import wx import vtk class transformStackRDR(ModuleBase, FilenameViewModuleMixin): """Reads 2D Transform Stack from disc. This module can be used to feed a register2D or a transform2D module. It reads the files that are written by transformStackWRT, but you knew that. """ def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin FilenameViewModuleMixin.__init__(self) # this is the output self._transformStack = transformStackClass(self) # we're going to use this to know when to actually read the data self._md5HexDigest = '' # we now have a viewFrame in self._viewFrame self._createViewFrame( 'Select a filename to load', '2D Transform Stack file (*.2ts)|*.2ts|All files (*)|*', objectDict=None) # set up some defaults self._config.filename = '' self.config_to_logic() # make sure these filter through from the bottom up self.logic_to_config() self.config_to_view() def close(self): del self._transformStack FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return () def set_input(self, idx, inputStream): raise Exception def get_output_descriptions(self): return ('2D Transform Stack',) def get_output(self, idx): return self._transformStack def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._config.filename): self._readTransformStack(self._config.filename) def view(self, parent_window=None): # if the frame is already visible, bring it to the top; this makes # it easier for the user to associate a frame with a glyph if not self._viewFrame.Show(True): self._viewFrame.Raise() def _readTransformStack(self, filename): try: # binary mode transformFile = file(filename, 'rb') except IOError, ioemsg: raise IOError, 'Could not open %s for reading:\n%s' % \ (filename, ioemsg) tBuffer = transformFile.read() m = md5.new() m.update(tBuffer) newHexDigest = m.hexdigest() if newHexDigest != self._md5HexDigest: # this means the file has changed and we should update # first take care of the current one del self._transformStack[:] # we have to rewind to the beginning of the file, else # the load will break transformFile.seek(0) pickleList = cPickle.load(transformFile) for name, paramsTup in pickleList: # instantiate transform trfm = eval('itk.itk%s_New()' % (name,)) # set the correct parameters pda = trfm.GetParameters() i = 0 for p in paramsTup: # FIXME: make sure i is within range with GetNOParameters pda.SetElement(i, p) i+=1 trfm.SetParameters(pda) self._transformStack.append(trfm) self._md5HexDigest = newHexDigest
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class gvfgac(ScriptedConfigModuleMixin, ModuleBase): """Module for performing Gradient Vector Flow-driven Geodesic Active Contour-based segmentation on 3D data. This module requires a DeVIDE-specific ITK class. The input feature image is an edge potential map with values close to 0 in regions close to the edges and values close to 1 otherwise. The level set speed function is based on this. For example: smooth an input image, determine the gradient magnitude and then pass it through a sigmoid transformation to create an edge potential map. The initial level set is a volume with the initial surface embedded as the 0 level set, i.e. the 0-value iso-contour (more or less). The inside of the volume is indicated by negative values and the outside with positive values. Also see figure 9.18 in the ITK Software Guide. $Revision: 1.2 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup defaults self._config.propagationScaling = 1.0 self._config.curvatureScaling = 1.0 self._config.advectionScaling = 1.0 self._config.numberOfIterations = 100 configList = [ ('Propagation scaling:', 'propagationScaling', 'base:float', 'text', 'Propagation scaling parameter for the geodesic active ' 'contour, ' 'i.e. balloon force. Positive for outwards, negative for ' 'inwards.'), ('Curvature scaling:', 'curvatureScaling', 'base:float', 'text', 'Curvature scaling term weighting.'), ('Advection scaling:', 'advectionScaling', 'base:float', 'text', 'Advection scaling term weighting.'), ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations that the algorithm should be run for')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) # create all pipeline thingies self._createITKPipeline() self.sync_module_logic_with_config() def close(self): self._destroyITKPipeline() ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def execute_module(self): self.get_output(0).Update() self._module_manager.setProgress( 100, "Geodesic active contour complete.") def get_input_descriptions(self): return ('Feature image (ITK)', 'Initial level set (ITK)' ) def set_input(self, idx, inputStream): if idx == 0: self._gvfgac.SetFeatureImage(inputStream) else: self._gvfgac.SetInput(inputStream) def get_output_descriptions(self): return ('Final level set (ITK Float 3D)',) def get_output(self, idx): return self._gvfgac.GetOutput() def config_to_logic(self): self._gvfgac.SetPropagationScaling( self._config.propagationScaling) self._gvfgac.SetCurvatureScaling( self._config.curvatureScaling) self._gvfgac.SetAdvectionScaling( self._config.advectionScaling) self._gvfgac.SetNumberOfIterations( self._config.numberOfIterations) def logic_to_config(self): self._config.propagationScaling = self._gvfgac.\ GetPropagationScaling() self._config.curvatureScaling = self._gvfgac.\ GetCurvatureScaling() self._config.advectionScaling = self._gvfgac.\ GetAdvectionScaling() self._config.numberOfIterations = self._gvfgac.\ GetNumberOfIterations() # -------------------------------------------------------------------- # END OF API CALLS # -------------------------------------------------------------------- def _createITKPipeline(self): # input: smoothing.SetInput() # output: thresholder.GetOutput() self._gvfgac = itk.itkGVFGACLevelSetImageFilterF3F3_New() #geodesicActiveContour.SetMaximumRMSError( 0.1 ); itk_kit.utils.setupITKObjectProgress( self, self._gvfgac, 'GVFGACLevelSetImageFilter', 'Growing active contour') def _destroyITKPipeline(self): """Delete all bindings to components of the ITK pipeline. """ del self._gvfgac
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import NoConfigModuleMixin class discreteLaplacian(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup the pipeline if3 = itk.Image[itk.F, 3] self._laplacian = itk.LaplacianImageFilter[if3,if3].New() itk_kit.utils.setupITKObjectProgress( self, self._laplacian, 'itkLaplacianImageFilter', 'Calculating Laplacian') NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'itkLaplacianImageFilter' : self._laplacian}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._laplacian def execute_module(self): self._laplacian.Update() def get_input_descriptions(self): return ('Image (ITK, 3D, float)',) def set_input(self, idx, inputStream): self._laplacian.SetInput(inputStream) def get_output_descriptions(self): return ('Laplacian image (ITK, 3D, float)',) def get_output(self, idx): return self._laplacian.GetOutput()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # TODO: # * if the input imageStackRDR is reconfigured to read a different stack # by the user, then things will break. We probably have to add an observer # and adapt to the new situation. # * ditto for the input transformStackRDR # * an observer which internally disconnects in the case of a screwup would # be good enough; the user can be warned that he should reconnect import gen_utils from typeModules.imageStackClass import imageStackClass from typeModules.transformStackClass import transformStackClass from module_base import ModuleBase import module_utils import operator import fixitk as itk import ConnectVTKITKPython as CVIPy import vtk import wx class register2D(ModuleBase): """Registers a stack of 2D images and generates a list of transforms. This is BAD-ASSED CODE(tm) and can crash the whole of DeVIDE without even saying sorry afterwards. You have been warned. """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._createLogic() self._createViewFrames() self._bindEvents() # FIXME: add current transforms to config stuff def close(self): # we do this just in case... self.set_input(0, None) self.set_input(1, None) ModuleBase.close(self) # take care of the IPWs self._destroyIPWs() # take care of pipeline thingies del self._rescaler1 del self._itkExporter1 del self._vtkImporter1 del self._resampler2 del self._rescaler2 del self._itkExporter2 del self._vtkImporter2 # also take care of our output! del self._transformStack # nasty trick to take care of RenderWindow self._threedRenderer.RemoveAllProps() del self._threedRenderer self.viewerFrame.threedRWI.GetRenderWindow().WindowRemap() self.viewerFrame.Destroy() del self.viewerFrame # then do the controlFrame self.controlFrame.Destroy() del self.controlFrame def get_input_descriptions(self): return ('ITK Image Stack', '2D Transform Stack') def set_input(self, idx, inputStream): if idx == 0: if inputStream != self._imageStack: # if it's None, we have to take it if inputStream == None: # disconnect del self._transformStack[:] self._destroyIPWs() self._imageStack = None self._pairNumber = -1 return # let's setup for a new stack! try: assert(inputStream.__class__.__name__ == 'imageStackClass') inputStream.Update() assert(len(inputStream) >= 2) except Exception: # if the Update call doesn't work or # if the input list is not long enough (or unsizable), # we don't do anything raise TypeError, \ "register2D requires an ITK Image Stack of minimum length 2 as input." # now check that the imageStack is the same size as the # transformStack if self._inputTransformStack and \ len(inputStream) != len(self._inputTransformStack): raise TypeError, \ "The Image Stack you are trying to connect has a\n" \ "different length than the connected Transform\n" \ "Stack." self._imageStack = inputStream if self._inputTransformStack: self._copyInputTransformStack() else: # create a new transformStack del self._transformStack[:] # the first transform is always identity for dummy in self._imageStack: self._transformStack.append( itk.itkEuler2DTransform_New()) self._transformStack[-1].SetIdentity() self._showImagePair(1) else: # closes if idx == 0 block if inputStream != self._inputTransformStack: if inputStream == None: # we disconnect, but we keep the transforms we have self._inputTransformStack = None return try: assert(inputStream.__class__.__name__ == \ 'transformStackClass') except Exception: raise TypeError, \ "register2D requires an ITK Transform Stack on " \ "this port." inputStream.Update() if len(inputStream) < 2: raise TypeError, \ "The input transform stack should be of minimum " \ "length 2." if self._imageStack and \ len(inputStream) != len(self._imageStack): raise TypeError, \ "The Transform Stack you are trying to connect\n" \ "has a different length than the connected\n" \ "Transform Stack" self._inputTransformStack = inputStream if self._imageStack: self._copyInputTransformStack() self._showImagePair(self._pairNumber) def get_output_descriptions(self): return ('2D Transform Stack',) def get_output(self, idx): return self._transformStack def execute_module(self): pass def view(self, parent_window=None): # if the window is already visible, raise it if not self.viewerFrame.Show(True): self.viewerFrame.Raise() if not self.controlFrame.Show(True): self.controlFrame.Raise() # ---------------------------------------------------------------------- # non-API methods start here ------------------------------------------- # ---------------------------------------------------------------------- def _bindEvents(self): wx.EVT_BUTTON(self.viewerFrame, self.viewerFrame.showControlsButtonId, self._handlerShowControls) wx.EVT_BUTTON(self.viewerFrame, self.viewerFrame.resetCameraButtonId, lambda e: self._resetCamera()) wx.EVT_SPINCTRL(self.controlFrame, self.controlFrame.pairNumberSpinCtrlId, self._handlerPairNumberSpinCtrl) wx.EVT_BUTTON(self.controlFrame, self.controlFrame.transformButtonId, self._handlerTransformButton) wx.EVT_BUTTON(self.controlFrame, self.controlFrame.registerButtonId, self._handlerRegisterButton) def _copyInputTransformStack(self): """Copy the contents of the inputTransformStack to the internal transform stack. """ # take care of the current ones del self._transformStack[:] # then copy for trfm in self._inputTransformStack: # FIXME: do we need to take out a ref? self._transformStack.append(trfm) def _createLogic(self): # input self._imageStack = None # optional input self._inputTransformStack = None # output is a transform stack self._transformStack = transformStackClass(self) self._ipw1 = None self._ipw2 = None # some control variables self._pairNumber = -1 # we need to have two converters from itk::Image to vtkImageData, # hmmmm kay? self._transform1 = itk.itkEuler2DTransform_New() self._transform1.SetIdentity() print self._transform1.GetParameters() self._rescaler1 = itk.itkRescaleIntensityImageFilterF2F2_New() self._rescaler1.SetOutputMinimum(0) self._rescaler1.SetOutputMaximum(255) self._itkExporter1 = itk.itkVTKImageExportF2_New() self._itkExporter1.SetInput(self._rescaler1.GetOutput()) self._vtkImporter1 = vtk.vtkImageImport() CVIPy.ConnectITKF2ToVTK(self._itkExporter1.GetPointer(), self._vtkImporter1) self._resampler2 = None self._rescaler2 = itk.itkRescaleIntensityImageFilterF2F2_New() self._rescaler2.SetOutputMinimum(0) self._rescaler2.SetOutputMaximum(255) self._itkExporter2 = itk.itkVTKImageExportF2_New() self._itkExporter2.SetInput(self._rescaler2.GetOutput()) self._vtkImporter2 = vtk.vtkImageImport() CVIPy.ConnectITKF2ToVTK(self._itkExporter2.GetPointer(), self._vtkImporter2) def _createViewFrames(self): import modules.Insight.resources.python.register2DViewFrames reload(modules.Insight.resources.python.register2DViewFrames) viewerFrame = modules.Insight.resources.python.register2DViewFrames.\ viewerFrame self.viewerFrame = module_utils.instantiate_module_view_frame( self, self._module_manager, viewerFrame) self._threedRenderer = vtk.vtkRenderer() self._threedRenderer.SetBackground(0.5, 0.5, 0.5) self.viewerFrame.threedRWI.GetRenderWindow().AddRenderer( self._threedRenderer) istyle = vtk.vtkInteractorStyleImage() self.viewerFrame.threedRWI.SetInteractorStyle(istyle) # controlFrame creation controlFrame = modules.Insight.resources.python.\ register2DViewFrames.controlFrame self.controlFrame = module_utils.instantiate_module_view_frame( self, self._module_manager, controlFrame) # display self.viewerFrame.Show(True) self.controlFrame.Show(True) def _createIPWs(self): self._ipw1 = vtk.vtkImagePlaneWidget() self._ipw2 = vtk.vtkImagePlaneWidget() for ipw, vtkImporter in ((self._ipw1, self._vtkImporter1), (self._ipw2, self._vtkImporter2)): vtkImporter.Update() ipw.SetInput(vtkImporter.GetOutput()) ipw.SetPlaneOrientation(2) ipw.SetInteractor(self.viewerFrame.threedRWI) ipw.On() ipw.InteractionOff() self._setModeRedGreen() def _destroyIPWs(self): """If the two IPWs exist, remove them completely and remove all bindings that we have. """ for ipw in (self._ipw1, self._ipw2): if ipw: # switch off ipw.Off() # disconnect from interactor ipw.SetInteractor(None) # disconnect from its input ipw.SetInput(None) self._ipw1 = None self._ipw2 = None def _handlerPairNumberSpinCtrl(self, event): self._showImagePair(self.controlFrame.pairNumberSpinCtrl.GetValue()) def _handlerRegisterButton(self, event): maxIterations = gen_utils.textToFloat( self.controlFrame.maxIterationsTextCtrl.GetValue(), 50) if not maxIterations > 0: maxIterations = 50 self._registerCurrentPair(maxIterations) self.controlFrame.maxIterationsTextCtrl.SetValue(str(maxIterations)) def _handlerShowControls(self, event): # make sure the window is visible and raised self.controlFrame.Show(True) self.controlFrame.Raise() def _handlerTransformButton(self, event): # take xtranslate, ytranslate, rotate and work it into the current # transform (if that exists) if self._pairNumber > 0: pda = self._transformStack[self._pairNumber].GetParameters() rot = gen_utils.textToFloat( self.controlFrame.rotationTextCtrl.GetValue(), pda.GetElement(0)) xt = gen_utils.textToFloat( self.controlFrame.xTranslationTextCtrl.GetValue(), pda.GetElement(1)) yt = gen_utils.textToFloat( self.controlFrame.yTranslationTextCtrl.GetValue(), pda.GetElement(2)) pda.SetElement(0, rot) pda.SetElement(1, xt) pda.SetElement(2, yt) self._transformStack[self._pairNumber].SetParameters(pda) # we have to do this manually self._transformStack[self._pairNumber].Modified() self._rescaler2.Update() # give ITK a chance to complain self.viewerFrame.threedRWI.GetRenderWindow().Render() def _registerCurrentPair(self, maxIterations): if not self._pairNumber > 0: # no data, return return currentTransform = self._transformStack[self._pairNumber] fixedImage = self._imageStack[self._pairNumber - 1] movingImage = self._imageStack[self._pairNumber] registration = itk.itkImageRegistrationMethodF2F2_New() # sum of squared differences imageMetric = itk.itkMeanSquaresImageToImageMetricF2F2_New() #imageMetric = itk.itkNormalizedCorrelationImageToImageMetricF2F2_New() optimizer = itk.itkRegularStepGradientDescentOptimizer_New() #optimizer = itk.itkConjugateGradientOptimizer_New() interpolator = itk.itkLinearInterpolateImageFunctionF2D_New() registration.SetOptimizer(optimizer.GetPointer()) registration.SetTransform(currentTransform.GetPointer() ) registration.SetInterpolator(interpolator.GetPointer()) registration.SetMetric(imageMetric.GetPointer()) registration.SetFixedImage(fixedImage) registration.SetMovingImage(movingImage) registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) initialParameters = currentTransform.GetParameters() registration.SetInitialTransformParameters( initialParameters ) # # Define optimizer parameters # optimizer.SetMaximumStepLength( 1 ) optimizer.SetMinimumStepLength( 0.01 ) optimizer.SetNumberOfIterations( maxIterations ) # velly impoltant: the scales # the larger a scale, the smaller the impact of that parameter on # the calculated gradient scalesDA = itk.itkArrayD(3) scalesDA.SetElement(0, 1e-01) scalesDA.SetElement(1, 1e-05) scalesDA.SetElement(2, 1e-05) optimizer.SetScales(scalesDA) # # Start the registration process # def iterationEvent(): pm = "register2D optimizer value: %f stepsize: %f" % \ (optimizer.GetValue(), optimizer.GetCurrentStepLength()) p = (optimizer.GetCurrentIteration() + 1) / maxIterations * 100.0 self._module_manager.setProgress(p, pm) pc2 = itk.itkPyCommand_New() pc2.SetCommandCallable(iterationEvent) optimizer.AddObserver(itk.itkIterationEvent(), pc2.GetPointer()) # FIXME: if this throws an exception, reset transform! registration.StartRegistration() fpm = 'register2D registration done (final value: %0.2f).' % \ optimizer.GetValue() self._module_manager.setProgress(100.0, fpm) print registration.GetLastTransformParameters().GetElement(0) print registration.GetLastTransformParameters().GetElement(1) print registration.GetLastTransformParameters().GetElement(2) self._syncGUIToCurrentPair() currentTransform.Modified() self._rescaler2.Update() # give ITK a chance to complain self.viewerFrame.threedRWI.GetRenderWindow().Render() def _resetCamera(self): """If an IPW is available (i.e. there's some data), this method will setup the camera to be nice and orthogonal to the IPW. """ if self._ipw1: # VTK5 vs old-style VTK try: planeSource = self._ipw1.GetPolyDataAlgorithm() except AttributeError: planeSource = self._ipw1.GetPolyDataSource() cam = self._threedRenderer.GetActiveCamera() cam.SetPosition(planeSource.GetCenter()[0], planeSource.GetCenter()[1], 10) cam.SetFocalPoint(planeSource.GetCenter()) cam.OrthogonalizeViewUp() cam.SetViewUp(0,1,0) cam.SetClippingRange(1, 11) v2 = map(operator.sub, planeSource.GetPoint2(), planeSource.GetOrigin()) n2 = vtk.vtkMath.Normalize(v2) cam.SetParallelScale(n2 / 2.0) cam.ParallelProjectionOn() self.viewerFrame.threedRWI.GetRenderWindow().Render() def _setModeCheckerboard(self): pass def _setModeRedGreen(self): """Set visualisation mode to RedGreen. The second image is always green. """ #for ipw, col in ((self._ipw1, 0.0), (self._ipw2, 0.3)): for ipw, col in ((self._ipw2, 0.3),): inputData = ipw.GetInput() inputData.Update() # make sure the metadata is up to date minv, maxv = inputData.GetScalarRange() lut = vtk.vtkLookupTable() lut.SetTableRange((minv, maxv)) lut.SetHueRange((col, col)) # keep it green! lut.SetSaturationRange((1.0, 1.0)) lut.SetValueRange((0.0, 1.0)) lut.SetAlphaRange((0.5, 0.5)) lut.Build() ipw.SetLookupTable(lut) def _showImagePair(self, pairNumber): """Set everything up to have the user interact with image pair pairNumber. pairNumber is 1 based, i.e. pairNumber 1 implies the registration between image 1 and image 0. """ # FIXME: do sanity checking on pairNumber self._pairNumber = pairNumber # connect up ITK pipelines with the correct images and transforms fixedImage = self._imageStack[pairNumber - 1] self._rescaler1.SetInput(fixedImage) self._rescaler1.Update() # give ITK a chance to complain... self._resampler2 = itk.itkResampleImageFilterF2F2_New() self._resampler2.SetTransform( self._transformStack[pairNumber].GetPointer()) self._resampler2.SetInput(self._imageStack[pairNumber]) region = fixedImage.GetLargestPossibleRegion() self._resampler2.SetSize(region.GetSize()) self._resampler2.SetOutputSpacing(fixedImage.GetSpacing()) self._resampler2.SetOutputOrigin(fixedImage.GetOrigin()) self._resampler2.SetDefaultPixelValue(0) self._rescaler2.SetInput(self._resampler2.GetOutput()) self._rescaler2.Update() # give ITK a chance to complain... self._syncGUIToCurrentPair() # we're going to create new ones, so take care of the old ones self._destroyIPWs() self._createIPWs() self._resetCamera() def _syncGUIToCurrentPair(self): # update GUI ##################################################### self.controlFrame.pairNumberSpinCtrl.SetRange(1, len(self._imageStack)-1) self.controlFrame.pairNumberSpinCtrl.SetValue(self._pairNumber) pda = self._transformStack[self._pairNumber].GetParameters() self.controlFrame.rotationTextCtrl.SetValue( '%.8f' % (pda.GetElement(0),)) self.controlFrame.xTranslationTextCtrl.SetValue( '%.8f' % (pda.GetElement(1),)) self.controlFrame.yTranslationTextCtrl.SetValue( '%.8f' % (pda.GetElement(2),)) # default self.controlFrame.maxIterationsTextCtrl.SetValue('50')
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import re class ITKWriter(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._input = None self._writer = None self._writer_type = None wildCardString = 'Meta Image all-in-one (*.mha)|*.mha|' \ 'Meta Image separate header/data (*.mhd)|*.mhd|' \ 'Analyze separate header/data (*.hdr)|*.hdr|' \ 'NIfTI (*.nii)|*.nii|' \ 'NIfTI compressed (*.nii.gz)|*.nii.gz|' \ 'All files (*)|*' # we now have a viewFrame in self._viewFrame FilenameViewModuleMixin.__init__( self, 'Select a filename', wildCardString, {'Module (self)': self}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('ITK Image',) def set_input(self, idx, inputStream): # should we take an explicit ref? if inputStream == None: # this is a disconnect self._input = inputStream else: try: if inputStream.GetNameOfClass() != 'Image': raise AttributeError except AttributeError, e: raise TypeError, \ 'This module requires an ITK Image Type (%s).' \ % (str(e),) else: self._input = inputStream def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): return False def config_to_logic(self): # if the user has Applied, we assume that things have changed # we could check for a change in the filename... (it's only that) return True def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._config.filename) and self._input: shortstring = itk_kit.utils.get_img_type_and_dim_shortstring( self._input) if shortstring != self._writer_type: print "ITKWriter: creating new writer instance." witk_template = getattr(itk, 'ImageFileWriter') witk_type = getattr(itk.Image, shortstring) try: self._writer = witk_template[witk_type].New() except Exception, e: if vectorString == 'V': vType = 'vector' else: vType = '' raise RuntimeError, \ 'Unable to instantiate ITK writer with' \ 'type %s.' % (shortstring,) else: itk_kit.utils.setupITKObjectProgress( self, self._writer, 'itkImageFileWriter', 'Writing ITK image to disc.') self._writer_type = shortstring self._input.UpdateOutputInformation() self._input.SetBufferedRegion( self._input.GetLargestPossibleRegion()) self._input.Update() self._writer.SetInput(self._input) # filename is unicode, ITK bombs out with: # Unable to execute part 0 of module dvm2 (ITKWriter): invalid null reference in method 'itkImageFileWriterIF3_SetFileName', argument 2 of type 'std::string const &' # so we have to down-convert. # see bug report http://code.google.com/p/devide/issues/detail?id=203 self._writer.SetFileName(str(self._config.filename)) # activating this crashes DeVIDE *BOOM* #self._writer.GetImageIO().SetUseCompression(True) self._writer.Write()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class tpgac(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup defaults self._config.propagationScaling = 1.0 self._config.curvatureScaling = 1.0 self._config.advectionScaling = 1.0 self._config.numberOfIterations = 100 configList = [ ('Propagation scaling:', 'propagationScaling', 'base:float', 'text', 'Propagation scaling parameter for the geodesic active ' 'contour, ' 'i.e. balloon force. Positive for outwards, negative for ' 'inwards.'), ('Curvature scaling:', 'curvatureScaling', 'base:float', 'text', 'Curvature scaling term weighting.'), ('Advection scaling:', 'advectionScaling', 'base:float', 'text', 'Advection scaling term weighting.'), ('Number of iterations:', 'numberOfIterations', 'base:int', 'text', 'Number of iterations that the algorithm should be run for')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) # create all pipeline thingies self._createITKPipeline() self.sync_module_logic_with_config() def close(self): self._destroyITKPipeline() ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def execute_module(self): self.get_output(0).Update() self._module_manager.setProgress( 100, "Geodesic active contour complete.") def get_input_descriptions(self): return ('Feature image (ITK)', 'Initial level set (ITK)' ) def set_input(self, idx, inputStream): if idx == 0: self._tpgac.SetFeatureImage(inputStream) else: self._tpgac.SetInput(inputStream) def get_output_descriptions(self): return ('Final level set (ITK Float 3D)',) def get_output(self, idx): return self._tpgac.GetOutput() def config_to_logic(self): self._tpgac.SetPropagationScaling( self._config.propagationScaling) self._tpgac.SetCurvatureScaling( self._config.curvatureScaling) self._tpgac.SetAdvectionScaling( self._config.advectionScaling) self._tpgac.SetNumberOfIterations( self._config.numberOfIterations) def logic_to_config(self): self._config.propagationScaling = self._tpgac.\ GetPropagationScaling() self._config.curvatureScaling = self._tpgac.\ GetCurvatureScaling() self._config.advectionScaling = self._tpgac.\ GetAdvectionScaling() self._config.numberOfIterations = self._tpgac.\ GetNumberOfIterations() # -------------------------------------------------------------------- # END OF API CALLS # -------------------------------------------------------------------- def _createITKPipeline(self): # input: smoothing.SetInput() # output: thresholder.GetOutput() if3 = itk.Image.F3 self._tpgac = itk.TPGACLevelSetImageFilter[if3, if3, itk.F].New() #geodesicActiveContour.SetMaximumRMSError( 0.1 ); itk_kit.utils.setupITKObjectProgress( self, self._tpgac, 'TPGACLevelSetImageFilter', 'Growing active contour') def _destroyITKPipeline(self): """Delete all bindings to components of the ITK pipeline. """ del self._tpgac
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from typeModules.imageStackClass import imageStackClass import fixitk as itk from module_base import ModuleBase from module_mixins import FileOpenDialogModuleMixin import module_utils import wx class imageStackRDR(ModuleBase, FileOpenDialogModuleMixin): """Loads a list of images as ITK Images. This list can e.g. be used as input to the 2D registration module. """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # list of ACTUAL itk images self._imageStack = imageStackClass(self) self._viewFrame = None self._createViewFrame() # list of names that are to be loaded self._config._imageFileNames = [] # we'll use this variable to check when we need to reload # filenames. self._imageFileNamesChanged = True # self.config_to_logic() self.logic_to_config() self.config_to_view() def close(self): # we took out explicit ITK references, let them go! for img in self._imageStack: img.UnRegister() # take care of other refs to all the loaded images self._imageStack.close() self._imageStack = [] # destroy GUI self._viewFrame.Destroy() # base classes taken care of ModuleBase.close(self) def get_input_descriptions(self): return () def set_input(self, idx, inputStream): raise Exception def get_output_descriptions(self): return ('ITK Image Stack',) def get_output(self, idx): return self._imageStack def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): count = self._viewFrame.fileNamesListBox.GetCount() tempList = [] for n in range(count): tempList.append(self._viewFrame.fileNamesListBox.GetString(n)) if tempList != self._config._imageFileNames: # this is a new list self._imageFileNamesChanged = True # copy... self._config._imageFileNames = tempList def config_to_view(self): # clear wxListBox self._viewFrame.fileNamesListBox.Clear() for fileName in self._config._imageFileNames: self._viewFrame.fileNamesListBox.Append(fileName) def execute_module(self): if self._imageFileNamesChanged: # only if things have changed do we do our thing # first take care of old refs del self._imageStack[:] # setup for progress counter currentProgress = 0.0 if len(self._config._imageFileNames) > 0: progressStep = 100.0 / len(self._config._imageFileNames) else: progressStep = 100.0 for imageFileName in self._config._imageFileNames: self._module_manager.setProgress( currentProgress, "Loading %s" % (imageFileName,)) currentProgress += progressStep reader = itk.itkImageFileReaderF2_New() reader.SetFileName(imageFileName) reader.Update() self._imageStack.append(reader.GetOutput()) # velly important; with ITK wrappings, ref count doesn't # increase if there's a coincidental python binding # it does if there was an explicit New() self._imageStack[-1].Register() self._module_manager.setProgress(100.0, "Done loading images.") # make sure all observers know about the changes self._imageStack.notify() # indicate that we're in sync now self._imageFileNamesChanged = False def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise() def _bindEvents(self): wx.EVT_BUTTON(self._viewFrame, self._viewFrame.addButtonId, self._handlerAddButton) def _createViewFrame(self): self._module_manager.import_reload( 'modules.Insight.resources.python.imageStackRDRViewFrame') import modules.Insight.resources.python.imageStackRDRViewFrame self._viewFrame = module_utils.instantiate_module_view_frame( self, self._module_manager, modules.Insight.resources.python.imageStackRDRViewFrame.\ imageStackRDRViewFrame) module_utils.create_eoca_buttons(self, self._viewFrame, self._viewFrame.viewFramePanel) self._bindEvents() def _handlerAddButton(self, event): fres = self.filenameBrowse(self._viewFrame, "Select files to add to stack", "*", wx.OPEN | wx.MULTIPLE) if fres: for fileName in fres: self._viewFrame.fileNamesListBox.Append(fileName)
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageEigenvectors(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageEigenvectors = vtktud.vtkImageEigenvectors() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageEigenvectors' : self._imageEigenvectors}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageEigenvectors def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageEigenvectors.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData','vtkImageData','vtkImageData') def get_output(self, idx): return self._imageEigenvectors.GetOutput(idx) def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageEigenvectors.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin from wxPython import wx class VTKtoPRTools(ScriptedConfigModuleMixin, ModuleBase): """Module to convert multi-component VTK image data to PRTools-compatible dataset. $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.filename = '' configList = [ ('Output filename:', 'filename', 'base:str', 'filebrowser', 'Type filename or click "browse" button to choose.', {'fileMode' : wx.wxSAVE, 'fileMask' : 'Matlab text file (*.txt)|*.txt|All files (*.*)|*.*'}) ] ScriptedConfigModuleMixin.__init__(self, configList) self._createViewFrame( {'Module (self)' : self}) self._inputData = None def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) del self._inputData def execute_module(self): # this is where the good stuff happens... if len(self._config.filename) == 0: raise RuntimeError, 'No filename has been set.' if self._inputData == None: raise RuntimeError, 'No input data to convert.' # now let's start going through the data outfile = file(self._config.filename, 'w') self._inputData.Update() nop = self._inputData.GetNumberOfPoints() noc = self._inputData.GetNumberOfScalarComponents() pd = self._inputData.GetPointData() curList = [''] * noc for i in xrange(nop): for j in range(noc): curList[j] = str(pd.GetComponent(i, j)) outfile.write('%s\n' % (' '.join(curList),)) self._module_manager.setProgress((float(i) / (nop - 1)) * 100.0, 'Exporting PRTools data.') self._module_manager.setProgress(100.0, 'Exporting PRTools data [DONE].') def get_input_descriptions(self): return ('VTK Image Data (multiple components)',) def set_input(self, idx, inputStream): try: if inputStream == None or inputStream.IsA('vtkImageData'): self._inputData = inputStream else: raise AttributeError except AttributeError: raise TypeError, 'This module requires a vtkImageData as input.' def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def config_to_logic(self): pass def logic_to_config(self): pass
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageGradientStructureTensor = vtktud.vtkImageGradientStructureTensor() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageGradientStructureTensor' : self._imageGradientStructureTensor}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageGradientStructureTensor def get_input_descriptions(self): return ('vtkImageData', 'vtkImageData', 'vtkImageData') def set_input(self, idx, inputStream): self._imageGradientStructureTensor.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageGradientStructureTensor.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageGradientStructureTensor.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class testModule(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # we'll be playing around with some vtk objects, this could # be anything self._triangleFilter = vtk.vtkTriangleFilter() self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMaximum() self._curvatures.SetInput(self._triangleFilter.GetOutput()) # initialise any mixins we might have NoConfigModuleMixin.__init__(self, {'Module (self)' : self, 'vtkTriangleFilter' : self._triangleFilter, 'vtkCurvatures' : self._curvatures}) module_utils.setup_vtk_object_progress(self, self._triangleFilter, 'Triangle filtering...') module_utils.setup_vtk_object_progress(self, self._curvatures, 'Calculating curvatures...') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._triangleFilter del self._curvatures def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._triangleFilter.SetInput(inputStream) def get_output_descriptions(self): return (self._curvatures.GetOutput().GetClassName(),) def get_output(self, idx): return self._curvatures.GetOutput() def execute_module(self): self._curvatures.Update() def streaming_execute_module(self): self._curvatures.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageCurvature(ModuleBase, NoConfigModuleMixin): """Calculates image curvature with VTKTUD vtkImageCurvature filter. You need 8 inputs, and in the following sequence: dx, dy, dz, dxx, dyy, dzz, dxy, dxz, dyz. This will output some curvature measure. The underlying filter will be adapted to make the raw curvature data (principal curvatures and directions of the isophote surface) available as well. All code by Joris van Zwieten. This bit of documentation by cpbotha. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageCurvature = vtktud.vtkImageCurvature() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageCurvature' : self._imageCurvature}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageCurvature def get_input_descriptions(self): return ('dx', 'dy', 'dz', 'dxx', 'dyy', 'dzz', 'dxy', 'dxz', 'dyz') def set_input(self, idx, inputStream): self._imageCurvature.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageCurvature.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageCurvature.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import wx import vtk import vtkdevide class modifyHomotopySlow(NoConfigModuleMixin, ModuleBase): """ WARNING, WARNING, DANGER WILL ROBINSON: this filter exists purely for experimental purposes. If you really want to use modifyHomotopy, use the module in modules.Filters (also part of 'Morphology'). This filter implements the modification according to very basic math and is dog-slow. In addition, it's throw-away code. Modifies homotopy of input image I so that the only minima will be at the user-specified seed-points or marker image, all other minima will be suppressed and ridge lines separating minima will be preserved. Either the seed-points or the marker image (or both) can be used. The marker image has to be >1 at the minima that are to be enforced and 0 otherwise. This module is often used as a pre-processing step to ensure that the watershed doesn't over-segment. $Revision: 1.1 $ """ 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # self._imageThreshold.RemoveObserver(self._imageThresholdObserverID) # get rid of our reference del self._markerSource del self._maskSource del self._imageThreshold del self._sup del self._imageErode def get_input_descriptions(self): return ('VTK Image Data', 'Minima points', 'Minima image') def set_input(self, idx, inputStream): if idx == 0: if inputStream != self._inputImage: # if we have a different image input, the seeds will have to # be rebuilt! self._markerSource.Modified() # and obviously the masksource has to know that its "input" # has changed self._maskSource.Modified() if inputStream: # we have to add an observer s = inputStream.GetSource() if s: self._inputImageObserverID = s.AddObserver( 'EndEvent', self._observerInputImage) else: # if we had an observer, remove it if self._inputImage: s = self._inputImage.GetSource() if s and self._inputImageObserverID: s.RemoveObserver( self._inputImageObserverID) self._inputImageObserverID = None # finally store the new data self._inputImage = inputStream elif idx == 1: if inputStream != self._inputPoints: # check that the inputStream is either None (meaning # disconnect) or a valid type try: if inputStream != None and \ inputStream.devideType != 'namedPoints': raise TypeError except (AttributeError, TypeError): raise TypeError, 'This input requires a points-type' if self._inputPoints: self._inputPoints.removeObserver( self._observerInputPoints) self._inputPoints = inputStream if self._inputPoints: self._inputPoints.addObserver(self._observerInputPoints) # the input points situation has changed, make sure # the marker source knows this... self._markerSource.Modified() # as well as the mask source of course self._maskSource.Modified() else: if inputStream != self._imageThreshold.GetInput(): self._imageThreshold.SetInput(inputStream) # we have a different inputMarkerImage... have to recalc self._markerSource.Modified() self._maskSource.Modified() def get_output_descriptions(self): return ('Modified VTK Image Data', 'I input', 'J input') def get_output(self, idx): if idx == 0: return self._sup.GetOutput() elif idx == 1: return self._maskSource.GetStructuredPointsOutput() else: return self._markerSource.GetStructuredPointsOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): # FIXME: if this module ever becomes anything other than an experiment, build # this logic into yet another ProgrammableSource # make sure marker is up to date self._markerSource.GetStructuredPointsOutput().Update() self._maskSource.GetStructuredPointsOutput().Update() tempJ = vtk.vtkStructuredPoints() tempJ.DeepCopy(self._markerSource.GetStructuredPointsOutput()) self._imageErode.SetInput(tempJ) self._diff = vtk.vtkImageMathematics() self._diff.SetOperationToSubtract() self._accum = vtk.vtkImageAccumulate() self._accum.SetInput(self._diff.GetOutput()) # now begin our loop stable = False while not stable: # do erosion, get supremum of erosion and mask I self._sup.GetOutput().Update() # compare this result with tempJ self._diff.SetInput1(tempJ) self._diff.SetInput2(self._sup.GetOutput()) self._accum.Update() print "%f == %f ?" % (self._accum.GetMin()[0], self._accum.GetMax()[0]) if abs(self._accum.GetMin()[0] - self._accum.GetMax()[0]) < 0.0001: stable = True else: # not stable yet... print "Trying again..." tempJ.DeepCopy(self._sup.GetOutput()) def _markerSourceExecute(self): imageI = self._inputImage if imageI: imageI.Update() # setup and allocate J output outputJ = self._markerSource.GetStructuredPointsOutput() # _dualGreyReconstruct wants inputs the same with regards to # dimensions, origin and type, so this is okay. outputJ.CopyStructure(imageI) outputJ.AllocateScalars() # we need this to build up J minI, maxI = imageI.GetScalarRange() mi = self._imageThreshold.GetInput() if mi: if mi.GetOrigin() == outputJ.GetOrigin() and \ mi.GetExtent() == outputJ.GetExtent(): self._imageThreshold.SetInValue(minI) self._imageThreshold.SetOutValue(maxI) self._imageThreshold.SetOutputScalarType(imageI.GetScalarType()) self._imageThreshold.GetOutput().SetUpdateExtentToWholeExtent() self._imageThreshold.Update() outputJ.DeepCopy(self._imageThreshold.GetOutput()) else: vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: marker input should be same dimensions as image input!') # we can continue as if we only had seeds scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) else: # initialise all scalars to maxI scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) # now go through all seed points and set those positions in # the scalars to minI if self._inputPoints: for ip in self._inputPoints: x,y,z = ip['discrete'] outputJ.SetScalarComponentFromDouble(x, y, z, 0, minI) def _maskSourceExecute(self): inputI = self._inputImage if inputI: inputI.Update() self._markerSource.Update() outputJ = self._markerSource.GetStructuredPointsOutput() # we now have an outputJ if not inputI.GetScalarPointer() or \ not outputJ.GetScalarPointer() or \ not inputI.GetDimensions() > (0,0,0): vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: Input is empty.') return iMath = vtk.vtkImageMathematics() iMath.SetOperationToMin() iMath.SetInput1(outputJ) iMath.SetInput2(inputI) iMath.GetOutput().SetUpdateExtentToWholeExtent() iMath.Update() outputI = self._maskSource.GetStructuredPointsOutput() outputI.DeepCopy(iMath.GetOutput()) def _observerInputPoints(self, obj): # this will be called if anything happens to the points # simply make sure our markerSource knows that it's now invalid self._markerSource.Modified() self._maskSource.Modified() def _observerInputImage(self, obj, eventName): # the inputImage has changed, so the marker will have to change too self._markerSource.Modified() # logical, input image has changed self._maskSource.Modified() def _observerImageThreshold(self, obj, eventName): # if anything in the threshold has changed, (e.g. the input) we # have to invalidate everything else after it self._markerSource.Modified() self._maskSource.Modified()
Python
from module_mixins import simpleVTKClassModuleBase import vtk import vtkdevide class imageBorderMask(simpleVTKClassModuleBase): def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtkdevide.vtkImageBorderMask(), 'Creating border mask.', ('VTK Image Data',), ('Border Mask (vtkImageData)',))
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk import vtkdevide class imageBacktracker(NoConfigModuleMixin, ModuleBase): """JORIK'S STUFF. """ def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageBacktracker = vtkdevide.vtkImageBacktracker() module_utils.setup_vtk_object_progress(self, self._imageBacktracker, 'Backtracking...') # we'll use this to keep a binding (reference) to the passed object self._inputPoints = None # inputPoints observer ID self._inputPointsOID = None # this will be our internal list of points self._seedPoints = [] self._viewFrame = None self._createViewFrame({'Module (self)' : self, 'vtkImageBacktracker' : self._imageBacktracker}) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) self.set_input(1, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # take out our view interface del self._imageBacktracker ModuleBase.close(self) def get_input_descriptions(self): return ('vtkImageData', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: # will work for None and not-None self._imageBacktracker.SetInput(inputStream) else: if inputStream is not self._inputPoints: if self._inputPoints: self._inputPoints.removeObserver(self._inputPointsObserver) if inputStream: inputStream.addObserver(self._inputPointsObserver) self._inputPoints = inputStream # initial update self._inputPointsObserver(None) def get_output_descriptions(self): return ('Backtracked polylines (vtkPolyData)',) def get_output(self, idx): return self._imageBacktracker.GetOutput() def execute_module(self): self._imageBacktracker.Update() def _inputPointsObserver(self, obj): # extract a list from the input points tempList = [] if self._inputPoints: for i in self._inputPoints: tempList.append(i['discrete']) if tempList != self._seedPoints: self._seedPoints = tempList self._imageBacktracker.RemoveAllSeeds() for seedPoint in self._seedPoints: self._imageBacktracker.AddSeed(seedPoint[0], seedPoint[1], seedPoint[2]) print "adding %s" % (str(seedPoint))
Python
# $Id: pngWRT.py 2401 2006-12-20 20:29:15Z cpbotha $ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils WX_OPEN = 1 WX_SAVE = 2 class isolated_points_check(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin # FilenameViewModuleMixin.__init__(self) self._input_image = None self._foreground_points = None self._background_points = None self._config.filename = '' configList = [ ('Result file name:', 'filename', 'base:str', 'filebrowser', 'Y/N result will be written to this file.', {'fileMode' : WX_SAVE, 'fileMask' : 'All files (*.*)|*.*'})] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def get_input_descriptions(self): return ('Segmented image', 'Foreground points', 'Background points') def set_input(self, idx, input_stream): if idx == 0: self._input_image = input_stream elif idx == 1: self._foreground_points = input_stream else: self._background_points = input_stream def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def execute_module(self): if not hasattr(self._input_image, 'GetClassName'): raise RuntimeError('Input image has wrong type') if not hasattr(self._foreground_points, 'devideType'): raise RuntimeError('Wrong type foreground points') if not hasattr(self._background_points, 'devideType'): raise RuntimeError('Wrong type background points') if not self._config.filename: raise RuntimeError('Result filename not specified') check = True for j in [i['discrete'] for i in self._foreground_points]: v = self._input_image.GetScalarComponentAsFloat( * list(j + (0,))) if v - 0.0 < 0.0000001: check = False break if check: for j in [i['discrete'] for i in self._background_points]: v = self._input_image.GetScalarComponentAsFloat( * list(j + (0,))) if v - 0.0 > 0.0000001: check = False break check_string = ['n', 'y'][int(check)] rf = file(self._config.filename, 'w') rf.write('%s\n' % (check_string,)) rf.close()
Python
# $Id$ import fixitk as itk import gen_utils from module_base import ModuleBase import module_utils import module_utilsITK from module_mixins import ScriptedConfigModuleMixin class hessianDoG(ScriptedConfigModuleMixin, ModuleBase): """Calculates Hessian matrix of volume by convolution with second and cross derivatives of Gaussian kernel. $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.gaussianSigma = 0.7 self._config.normaliseAcrossScale = False configList = [ ('Gaussian sigma', 'gaussianSigma', 'base:float', 'text', 'Sigma in terms of image spacing.'), ('Normalise across scale', 'normaliseAcrossScale', 'base:bool', 'checkbox', 'Determine normalisation factor.')] ScriptedConfigModuleMixin.__init__(self, configList) # setup the pipeline g = itk.itkGradientMagnitudeRecursiveGaussianImageFilterF3F3_New() self._gradientMagnitude = g module_utilsITK.setupITKObjectProgress( self, g, 'itkGradientMagnitudeRecursiveGaussianImageFilter', 'Calculating gradient image') self._createWindow( {'Module (self)' : self, 'itkGradientMagnitudeRecursiveGaussianImageFilter' : self._gradientMagnitude}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gradientMagnitude def execute_module(self): self._gradientMagnitude.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._gradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._gradientMagnitude.GetOutput() def config_to_logic(self): self._gradientMagnitude.SetSigma(self._config.gaussianSigma) self._gradientMagnitude.SetNormalizeAcrossScale( self._config.normaliseAcrossScale) def logic_to_config(self): # durnit, there's no GetSigma(). Doh. self._config.normaliseAcrossScale = self._gradientMagnitude.\ GetNormalizeAcrossScale()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class testModule2(NoConfigModuleMixin, ModuleBase): """Resample volume according to 4x4 homogeneous transform. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) self._imageReslice = vtk.vtkImageReslice() self._imageReslice.SetInterpolationModeToCubic() self._matrixToHT = vtk.vtkMatrixToHomogeneousTransform() self._matrixToHT.Inverse() module_utils.setup_vtk_object_progress(self, self._imageReslice, 'Resampling volume') self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageReslice' : self._imageReslice}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._imageReslice def get_input_descriptions(self): return ('VTK Image Data', 'VTK Transform') def set_input(self, idx, inputStream): if idx == 0: self._imageReslice.SetInput(inputStream) else: try: self._matrixToHT.SetInput(inputStream.GetMatrix()) except AttributeError: # this means the inputStream has no GetMatrix() # i.e. it could be None or just the wrong type # if it's none, we just have to disconnect if inputStream == None: self._matrixToHT.SetInput(None) self._imageReslice.SetResliceTransform(None) # if not, we have to complain else: raise TypeError, \ "transformVolume input 2 requires a transform." else: self._imageReslice.SetResliceTransform(self._matrixToHT) def get_output_descriptions(self): return ('Transformed VTK Image Data',) def get_output(self, idx): return self._imageReslice.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageReslice.Update()
Python
# EmphysemaViewerFrame by Corine Slagboom & Noeska Smit # Description # # Based on SkeletonAUIViewerFrame: # Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. import cStringIO from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx # wxPython 2.8.8.1 wx.aui bugs severely on GTK. See: # http://trac.wxwidgets.org/ticket/9716 # Until this is fixed, use this PyAUI to which I've added a # wx.aui compatibility layer. if wx.Platform == "__WXGTK__": from external import PyAUI wx.aui = PyAUI else: import wx.aui # one could have loaded a wxGlade created resource like this: #from resources.python import DICOMBrowserPanels #reload(DICOMBrowserPanels) class EmphysemaViewerFrame(wx.Frame): """wx.Frame child class used by Emphysemaviewer for its interface. This is an AUI-managed window, so we create the top-level frame, and then populate it with AUI panes. """ def __init__(self, parent, id=-1, title="", name=""): """Populates the menu and adds all required panels """ wx.Frame.__init__(self, parent, id=id, title=title, pos=wx.DefaultPosition, size=(1000,875), name=name) self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) file_menu = wx.Menu() self.id_file_open = wx.NewId() self.id_mask_open = wx.NewId() file_menu.Append(self.id_file_open, "&Open Volume\tCtrl-O", "Open a volume", wx.ITEM_NORMAL) file_menu.Append(self.id_mask_open, "&Open Mask\tCtrl-M", "Open a mask", wx.ITEM_NORMAL) self.id_mask_save = wx.NewId() file_menu.Append(self.id_mask_save, "&Save\tCtrl-S", "Save file", wx.ITEM_NORMAL) self.menubar.Append(file_menu, "&File") views_menu = wx.Menu() views_default_id = wx.NewId() views_menu.Append(views_default_id, "&Default\tCtrl-0", "Activate default view layout.", wx.ITEM_NORMAL) views_max_image_id = wx.NewId() views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1", "Activate maximum image view size layout.", wx.ITEM_NORMAL) self.menubar.Append(views_menu, "&Views") # tell FrameManager to manage this frame self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) self._mgr.AddPane(self._create_rwi_pane(), wx.aui.AuiPaneInfo(). Name("rwi").Caption("3D Renderer"). Center(). BestSize(wx.Size(600,800)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_controls_pane(), wx.aui.AuiPaneInfo(). Name("controls").Caption("Controls"). Top(). BestSize(wx.Size(1000,75)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_overlay_slices_pane(), wx.aui.AuiPaneInfo(). Name("overlay").Caption("Emphysema Overlay"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_original_slices_pane(), wx.aui.AuiPaneInfo(). Name("original").Caption("Original Scan"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self.SetMinSize(wx.Size(400, 300)) # first we save this default perspective with all panes # visible self._perspectives = {} self._perspectives['default'] = self._mgr.SavePerspective() # then we hide all of the panes except the renderer self._mgr.GetPane("controls").Hide() self._mgr.GetPane("overlay").Hide() self._mgr.GetPane("original").Hide() # save the perspective again self._perspectives['max_image'] = self._mgr.SavePerspective() # and put back the default perspective / view self._mgr.LoadPerspective(self._perspectives['default']) # finally tell the AUI manager to do everything that we've # asked self._mgr.Update() # we bind the views events here, because the functionality is # completely encapsulated in the frame and does not need to # round-trip to the DICOMBrowser main module. self.Bind(wx.EVT_MENU, self._handler_default_view, id=views_default_id) self.Bind(wx.EVT_MENU, self._handler_max_image_view, id=views_max_image_id) self.CreateStatusBar() self.SetStatusText("This is the statusbar ^^") def close(self): """Selfdestruct :) """ self.Destroy() def _create_rwi_pane(self): """Create a RenderWindowInteractor panel """ panel = wx.Panel(self, -1) self.rwi = wxVTKRenderWindowInteractor(panel, -1, (600,800)) self.button1 = wx.Button(panel, -1, "Reset Camera") self.button2 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button1) button_sizer.Add(self.button2) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.rwi, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_controls_pane(self): """Create a pane for the controls (containing the threshold sliders and buttons for setting default or calculated values) """ panel = wx.Panel(self, -1) self.upper_slider = wx.Slider(panel, -1, -950, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label = wx.StaticText(panel, -1, "Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label.SetForegroundColour(wx.Colour(127,0,255)) self.lower_slider = wx.Slider(panel, -1, -970, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label2 = wx.StaticText(panel, -1, "Severe Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label2.SetForegroundColour(wx.Colour(255,0,0)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.upper_slider) sizer.Add(self.label) sizer2 = wx.BoxSizer(wx.VERTICAL) sizer2.Add(self.lower_slider) sizer2.Add(self.label2) self.button5 = wx.Button(panel, -1, "-950 / -970 HU",pos=(8, 8), size=(175, 28)) self.button6 = wx.Button(panel, -1, "12% / 10% Lowest HU",pos=(8, 8), size=(175, 28)) button_sizer = wx.BoxSizer(wx.VERTICAL) button_sizer.Add(self.button5) button_sizer.Add(self.button6) slider_sizer = wx.BoxSizer(wx.HORIZONTAL) slider_sizer.Add(sizer) slider_sizer.Add(sizer2) slider_sizer.Add(button_sizer) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(slider_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_overlay_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.overlay = wxVTKRenderWindowInteractor(panel, -1, (400,400)) self.button3 = wx.Button(panel, -1, "Reset Camera") self.button4 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button3) button_sizer.Add(self.button4) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.overlay, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_original_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.original = wxVTKRenderWindowInteractor(panel, -1, (400,400)) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.original, 1, wx.EXPAND|wx.BOTTOM, 7) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def render(self): """Update embedded RWI, i.e. update the image. """ self.rwi.Render() self.overlay.Render() self.original.Render() def _handler_default_view(self, event): """Event handler for when the user selects View | Default from the main menu. """ self._mgr.LoadPerspective( self._perspectives['default']) def _handler_max_image_view(self, event): """Event handler for when the user selects View | Max Image from the main menu. """ self._mgr.LoadPerspective( self._perspectives['max_image'])
Python
class EmphysemaViewer: kits = ['vtk_kit'] cats = ['Viewers'] help = """Module to visualize lungemphysema from a CT-thorax scan and a lung mask. EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The volume rendering shows 3 contours: the lungedges and 2 different contours of emphysema; a normal one and a severe one. There are two ways of setting the emphysema values. - The first way is choosing the 'default' values, which are literature-based. They are set on -950 HU (emphysema) and -970 HU (severe). - The other way is a computational way: The lowest 11% values, that are present in the data are marked as emphysema, the lowest 8,5% values are marked as severe emphysema. The theory behind this is the hypothesis that the histograms of emphysema patients differ from healthy people in a way that in emphysema patients there are relatively more lower values present. In both ways you can finetune the values, or completely change them (if you want to). After loading your image data and mask data, you can inspect the data and examine the severity of the emphysema of the patient. Controls:\n LMB: The left mouse button can be used to rotate objects in the 3D scene, or to poll Houndsfield Units in areas of interest (click and hold to see the values)\n RMB: For the slice viewers, you can set the window and level values by clicking and holding the right mouse button in a slice and moving your mouse. You can see the current window and level values in the bottom of the viewer. Outside of the slice, this zooms the camera in and out\n MMB: The middle mouse button enables stepping through the slices if clicked and held in the center of the slice. When clicking on de edges of a slice, this re-orients the entire slice. Outside of the slice, this pans the camera\n Scrollwheel: The scrollwheel can be used for zooming in and out of a scene, but also for sliceviewing if used with the CTRL- or SHIFT-key\n SHIFT: By holding the SHIFT-key, it is possible to use the mouse scrollwheel to scroll through the slices.\n CTRL: Holding the CTRL-key does the same, but enables stepping through the data in steps of 10 slices.\n """
Python
# EmphysemaViewer by Corine Slagboom & Noeska Smit # # # Based on SkeletonAUIViewer: # Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # skeleton of an AUI-based viewer module # copy and modify for your own purposes. # set to False for 3D viewer, True for 2D image viewer IMAGE_VIEWER = True # import the frame, i.e. the wx window containing everything import EmphysemaViewerFrame # and do a reload, so that the GUI is also updated at reloads of this # module. reload(EmphysemaViewerFrame) from module_kits.misc_kit import misc_utils from module_base import ModuleBase from module_mixins import IntrospectModuleMixin from comedi_utils import CMSliceViewer from comedi_utils import SyncSliceViewers import module_utils import os import sys import traceback import vtk import wx class EmphysemaViewer(IntrospectModuleMixin, ModuleBase): """Module to visualize lungemphysema in a CT scan. A lung mask is also needed. EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The volume rendering shows 3 contours: the lungedges and 2 different contours of emphysema; a normal one and a severe one. There are two ways of setting the emphysema values. - The first way is choosing the 'default' values, which are literature-based. They are set on -950 HU (emphysema) and -970 HU (severe). - The other way is a computational way: The lowest 11% values, that are present in the data are marked as emphysema, the lowest 8,5% values are marked as severe emphysema. The theory behind this is the hypothesis that the histograms of emphysema patients differ from healthy people in a way that in emphysema patients there are relatively more lower values present. In both ways you can finetune the values, or completely change them (if you want to). After loading your image data and mask data, you can inspect the data and examine the severity of the emphysema of the patient. Controls: LMB: The left mouse button can be used to rotate objects in the 3D scene, or to poll Houndsfield Units in areas of interest (click and hold to see the values)\n RMB: For the slice viewers, you can set the window and level values by clicking and holding the right mouse button in a slice and moving your mouse. You can see the current window and level values in the bottom of the viewer. Outside of the slice, this zooms the camera in and out\n MMB: The middle mouse button enables stepping through the slices if clicked and held in the center of the slice. When clicking on de edges of a slice, this re-orients the entire slice. Outside of the slice, this pans the camera\n Scrollwheel: The scrollwheel can be used for zooming in and out of a scene, but also for sliceviewing if used with the CTRL- or SHIFT-key\n SHIFT: By holding the SHIFT-key, it is possible to use the mouse scrollwheel to scroll through the slices.\n CTRL: Holding the CTRL-key does the same, but enables stepping through the data in steps of 10 slices.\n """ def __init__(self, module_manager): """Standard constructor. All DeVIDE modules have these, we do the required setup actions. """ # we record the setting here, in case the user changes it # during the lifetime of this model, leading to different # states at init and shutdown. self.IMAGE_VIEWER = IMAGE_VIEWER # we need all this for our contours self.mask_data = None self.image_data = None self.lungVolume = None self.contour_severe_actor = vtk.vtkActor() self.contour_moderate_actor = vtk.vtkActor() self.contour_lungedge_actor = vtk.vtkActor() self.severe_mapper = vtk.vtkPolyDataMapper() self.severe_mapper.ScalarVisibilityOff() self.moderate_mapper = vtk.vtkPolyDataMapper() self.moderate_mapper.ScalarVisibilityOff() self.lung_mapper = vtk.vtkPolyDataMapper() self.lung_mapper.ScalarVisibilityOff() self.contour_severe_actor.SetMapper(self.severe_mapper) self.contour_severe_actor.GetProperty().SetColor(1,0,0) self.contour_severe_actor.GetProperty().SetOpacity(0.5) self.contour_moderate_actor.SetMapper(self.moderate_mapper) self.contour_moderate_actor.GetProperty().SetColor(0.5,0,1) self.contour_moderate_actor.GetProperty().SetOpacity(0.25) self.contour_lungedge_actor.SetMapper(self.lung_mapper) self.contour_lungedge_actor.GetProperty().SetColor(0.9,0.9,0.9) self.contour_lungedge_actor.GetProperty().SetOpacity(0.1) ModuleBase.__init__(self, module_manager) # create the view frame self._view_frame = module_utils.instantiate_module_view_frame( self, self._module_manager, EmphysemaViewerFrame.EmphysemaViewerFrame) # change the title to something more spectacular (or at least something non-default) self._view_frame.SetTitle('EmphysemaViewer') # create the necessary VTK objects: we only need a renderer, # the RenderWindowInteractor in the view_frame has the rest. self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.5,0.5,0.5) self._view_frame.rwi.GetRenderWindow().AddRenderer(self.ren) self.ren.AddActor(self.contour_severe_actor) self.ren.AddActor(self.contour_moderate_actor) self.ren.AddActor(self.contour_lungedge_actor) self.ren2 = vtk.vtkRenderer() self.ren2.SetBackground(0.5,0.5,0.5) self._view_frame.overlay.GetRenderWindow().AddRenderer(self.ren2) self.slice_viewer1 = CMSliceViewer(self._view_frame.overlay, self.ren2) self.ren3 = vtk.vtkRenderer() self.ren3.SetBackground(0.5,0.5,0.5) self._view_frame.original.GetRenderWindow().AddRenderer(self.ren3) self.slice_viewer2 = CMSliceViewer(self._view_frame.original, self.ren3) self.slice_viewer3 = CMSliceViewer(self._view_frame.rwi, self.ren) self.sync = SyncSliceViewers() self.sync.add_slice_viewer(self.slice_viewer1) self.sync.add_slice_viewer(self.slice_viewer2) self.sync.add_slice_viewer2(self.slice_viewer3) # hook up all event handlers self._bind_events() # anything you stuff into self._config will be saved self._config.last_used_dir = '' # make our window appear (this is a viewer after all) self.view() # all modules should toggle this once they have shown their # views. self.view_initialised = True # apply config information to underlying logic self.sync_module_logic_with_config() # then bring it all the way up again to the view self.sync_module_view_with_logic() def close(self): """Clean-up method called on all DeVIDE modules when they are deleted. FIXME: Still get a nasty X error :( """ # with this complicated de-init, we make sure that VTK is # properly taken care of self.ren.RemoveAllViewProps() self.ren2.RemoveAllViewProps() self.ren3.RemoveAllViewProps() # this finalize makes sure we don't get any strange X # errors when we kill the module. self.slice_viewer1.close() self.slice_viewer2.close() self.slice_viewer3.close() self._view_frame.rwi.GetRenderWindow().Finalize() self._view_frame.rwi.SetRenderWindow(None) self._view_frame.overlay.GetRenderWindow().Finalize() self._view_frame.overlay.SetRenderWindow(None) self._view_frame.original.GetRenderWindow().Finalize() self._view_frame.original.SetRenderWindow(None) del self._view_frame.rwi del self._view_frame.overlay del self._view_frame.original del self.slice_viewer3 del self.slice_viewer2 del self.slice_viewer1 # done with VTK de-init # now take care of the wx window self._view_frame.close() # then shutdown our introspection mixin IntrospectModuleMixin.close(self) def get_input_descriptions(self): # define this as a tuple of input descriptions if you want to # take input data e.g. return ('vtkPolyData', 'my kind of # data') return () def get_output_descriptions(self): # define this as a tuple of output descriptions if you want to # generate output data. return () def set_input(self, idx, input_stream): # this gets called right before you get executed. take the # input_stream and store it so that it's available during # execute_module() pass def get_output(self, idx): # this can get called at any time when a consumer module wants # you output data. pass def execute_module(self): # when it's you turn to execute as part of a network # execution, this gets called. pass def logic_to_config(self): pass def config_to_logic(self): pass def config_to_view(self): pass def view_to_config(self): pass def view(self): self._view_frame.Show() self._view_frame.Raise() # because we have an RWI involved, we have to do this # SafeYield, so that the window does actually appear before we # call the render. If we don't do this, we get an initial # empty renderwindow. wx.SafeYield() self.render() def create_volumerender(self, contourValueModerate, contourValueSevere): """Creates a volumerender of the masked data using iso-contour surfaces created by the Marching Cubes algorithm at the specified contourvalues. """ self._view_frame.SetStatusText("Creating Volumerender...") self.image_data mask = vtk.vtkImageMask() severeFraction = 0.10 moderateFraction = 0.12 # We only want to contour the lungs, so mask it mask.SetMaskInput(self.mask_data) mask.SetInput(self.image_data) mask.Update() self.lungVolume = mask.GetOutput() if contourValueModerate == 0 and contourValueSevere == 0: # This means we get to calculate the percentual values ourselves! scalars = self.lungVolume.GetScalarRange() range = scalars[1]-scalars[0] contourValueSevere = scalars[0]+range*severeFraction contourValueModerate = scalars[0]+range*moderateFraction self._view_frame.upper_slider.SetValue(contourValueModerate) self._view_frame.lower_slider.SetValue(contourValueSevere) self.create_overlay(contourValueModerate,contourValueSevere) # Create the contours self.adjust_contour(self.lungVolume, contourValueSevere, self.severe_mapper) self.adjust_contour(self.lungVolume, contourValueModerate, self.moderate_mapper) #self.adjust_contour(self.mask_data, 0.5, self.lung_mapper) self.create_lungcontour() # Set the camera to a nice view cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() self.render() self._view_frame.SetStatusText("Created Volumerender") def adjust_contour(self, volume, contourValue, mapper): """Adjust or create an isocontour using the Marching Cubes surface at the given value using the given mapper """ self._view_frame.SetStatusText("Calculating new volumerender...") contour = vtk.vtkMarchingCubes() contour.SetValue(0,contourValue) contour.SetInput(volume) mapper.SetInput(contour.GetOutput()) mapper.Update() self.render() self._view_frame.SetStatusText("Calculated new volumerender") def create_lungcontour(self): """Create a lungcontour using the Marching Cubes algorithm and smooth the surface """ self._view_frame.SetStatusText("Calculating lungcontour...") contourLung = vtk.vtkMarchingCubes() contourLung.SetValue(0,1) contourLung.SetInput(self.mask_data) smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInput(contourLung.GetOutput()) smoother.BoundarySmoothingOn() smoother.SetNumberOfIterations(40) smoother.Update() self.lung_mapper.SetInput(smoother.GetOutput()) self.lung_mapper.Update() self._view_frame.SetStatusText("Calculated lungcontour") 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 load_data_from_file(self, file_path): """Loads scanvolume data from file. Also sets the volume as input for the sliceviewers """ self._view_frame.SetStatusText("Opening file: %s..." % (file_path)) filename = os.path.split(file_path)[1] fileBaseName =os.path.splitext(filename)[0] reader = vtk.vtkMetaImageReader() reader.SetFileName(file_path) reader.Update() self.image_data = reader.GetOutput() self.slice_viewer1.set_input(self.image_data) self.slice_viewer1.reset_camera() self.slice_viewer1.render() self.slice_viewer2.set_input(self.image_data) self.slice_viewer2.reset_camera() self.slice_viewer2.render() self.slice_viewer3.set_input(self.image_data) self.slice_viewer3.render() self.slice_viewer3.set_opacity(0.1) cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() if (self.mask_data) is not None: # We can start calculating the volumerender self.create_volumerender(0,0) else: self._view_frame.SetStatusText("Opened file") def load_mask_from_file(self, file_path): """Loads mask file """ self._view_frame.SetStatusText( "Opening mask: %s..." % (file_path)) filename = os.path.split(file_path)[1] fileBaseName =os.path.splitext(filename)[0] reader = vtk.vtkMetaImageReader() reader.SetFileName(file_path) reader.Update() self.mask_data = reader.GetOutput() if (self.image_data) is not None: self.create_volumerender(0,0) else: self._view_frame.SetStatusText("Opened mask file") def save_to_file(self, file_path): """Save data from main renderwindow (the contour one) to a PNG-file """ w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(self._view_frame.rwi.GetRenderWindow()); w2i.Update() writer = vtk.vtkPNGWriter() writer.SetInput(w2i.GetOutput()) writer.SetFileName(file_path) writer.Update() result = writer.Write() if result == 0: self._view_frame.SetStatusText( "Saved file") else: self._view_frame.SetStatusText( "Saved file to: %s..." % (file_path)) def _bind_events(self): """Bind wx events to Python callable object event handlers. """ vf = self._view_frame vf.Bind(wx.EVT_MENU, self._handler_file_open, id = vf.id_file_open) vf.Bind(wx.EVT_MENU, self._handler_mask_open, id = vf.id_mask_open) vf.Bind(wx.EVT_MENU, self._handler_file_save, id = vf.id_mask_save) self._view_frame.button1.Bind(wx.EVT_BUTTON, self._handler_button1) self._view_frame.button2.Bind(wx.EVT_BUTTON, self._handler_button2) self._view_frame.button3.Bind(wx.EVT_BUTTON, self._handler_button3) self._view_frame.button4.Bind(wx.EVT_BUTTON, self._handler_button4) self._view_frame.button5.Bind(wx.EVT_BUTTON, self._handler_button5) self._view_frame.button6.Bind(wx.EVT_BUTTON, self._handler_button6) self._view_frame.upper_slider.Bind(wx.EVT_SCROLL_CHANGED, self._handler_slider1) self._view_frame.lower_slider.Bind(wx.EVT_SCROLL_CHANGED, self._handler_slider2) def _handler_button1(self, event): """Reset the camera of the main render window """ self.ren.ResetCamera() self.render() def _handler_button2(self, event): """Reset all for the main render window """ cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() self.render() def _handler_button3(self, event): """Reset the camera for the sliceviewers """ self.slice_viewer1.reset_camera() self.slice_viewer2.reset_camera() self.render() def _handler_button4(self, event): """Reset all for the sliceviewers """ self.slice_viewer1.reset_to_default_view(2) self.slice_viewer2.reset_to_default_view(2) orientations = [2, 0, 1] for i, ipw in enumerate(self.slice_viewer1.ipws): ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) self.render() for i, ipw in enumerate(self.slice_viewer2.ipws): ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) self.render() def _handler_button5(self, event): """Adjust the contourvalues to values recommended in literature """ if self.lungVolume == None: return else: self._view_frame.upper_slider.SetValue(-950) self._view_frame.lower_slider.SetValue(-970) self.adjust_contour(self.lungVolume, -950, self.moderate_mapper) self.adjust_contour(self.lungVolume, -970, self.severe_mapper) self.create_overlay(-950,-970) def _handler_button6(self, event): """Adjust the contourvalues to values calculated from data """ if self.lungVolume == None: return else: self.create_volumerender(0, 0) def _handler_file_open(self, event): """Handler for file opening """ filters = 'Volume files (*.mhd)|*.mhd;' dlg = wx.FileDialog(self._view_frame, "Please choose a CT-thorax file", self._config.last_used_dir, "", filters, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() full_file_path = "%s/%s" % (self._config.last_used_dir, filename) self.load_data_from_file(full_file_path) dlg.Destroy() def _handler_mask_open(self, event): """Handler for mask opening """ filters = 'Mask files (*.mhd;#.mha)|*.mhd;*mha;' dlg = wx.FileDialog(self._view_frame, "Please choose a CT-thorax mask file", self._config.last_used_dir, "", filters, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() full_file_path = "%s/%s" % (self._config.last_used_dir, filename) self.load_mask_from_file(full_file_path) dlg.Destroy() def _handler_file_save(self, event): """Handler for filesaving """ self._view_frame.SetStatusText( "Saving file...") filters = 'png file (*.png)|*.png' dlg = wx.FileDialog(self._view_frame, "Choose a destination", self._config.last_used_dir, "", filters, wx.SAVE) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() file_path = "%s/%s" % (self._config.last_used_dir, filename) self.save_to_file(file_path) dlg.Destroy() self._view_frame.SetStatusText( "Saved file") def _handler_slider1(self, event): """Handler for slider adjustment (Severe emphysema) """ if self.lungVolume == None: return else: contourValue = self._view_frame.upper_slider.GetValue() self.adjust_contour(self.lungVolume, contourValue, self.moderate_mapper) self.create_overlay(contourValue, self._view_frame.lower_slider.GetValue()) def _handler_slider2(self, event): """Handler for slider adjustment (Moderate emphysema) """ if self.lungVolume == None: return else: contourValue = self._view_frame.lower_slider.GetValue() self.adjust_contour(self.lungVolume, contourValue, self.severe_mapper) self.create_overlay(self._view_frame.upper_slider.GetValue(),contourValue) def render(self): """Method that calls Render() on the embedded RenderWindow. Use this after having made changes to the scene. """ self._view_frame.render() self.slice_viewer1.render()
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # --------------------------------------- # Edited by Corine Slagboom & Noeska Smit to add possibility of adding overlay to the sliceviewer and some special synching. # And by edited we mean mutilated :) from module_kits.vtk_kit.utils import DVOrientationWidget import operator import vtk import wx class SyncSliceViewers: """Class to link a number of CMSliceViewer instances w.r.t. camera. FIXME: consider adding option to block certain slice viewers from participation. Is this better than just removing them? """ def __init__(self): # store all slice viewer instances that are being synced self.slice_viewers = [] # edit nnsmit self.slice_viewers2 = [] # end edit self.observer_tags = {} # if set to False, no syncing is done. # user is responsible for doing the initial sync with sync_all # after this variable is toggled from False to True self.sync = True def add_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this one only gets called for camera interaction (of course) t['istyle InteractionEvent'] = \ istyle.AddObserver('InteractionEvent', lambda o,e: self._observer_camera(slice_viewer)) # this gets call for all interaction with the slice # (cursoring, slice pushing, perhaps WL) for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) t['ipw%d WindowLevelEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('WindowLevelEvent', lambda o,e,i=idx: self._observer_window_level(slice_viewer,i)) self.slice_viewers.append(slice_viewer) # edit nnsmit # not the prettiest 'fix' in the book, but unfortunately short on time def add_slice_viewer2(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this gets call for all interaction with the slice for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) self.slice_viewers2.append(slice_viewer) #end edit def close(self): for sv in self.slice_viewers: self.remove_slice_viewer(sv) def _observer_camera(self, sv): """This observer will keep the cameras of all the participating slice viewers synched. It's only called when the camera is moved. """ if not self.sync: return cc = self.sync_cameras(sv) [sv.render() for sv in cc] def _observer_mousewheel_forward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelForward() vtk_o.InvokeEvent('InteractionEvent') def _observer_mousewheel_backward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelBackward() vtk_o.InvokeEvent('InteractionEvent') def _observer_ipw(self, slice_viewer, idx=0): """This is called whenever the user does ANYTHING with the IPW. """ if not self.sync: return cc = self.sync_ipws(slice_viewer, idx) [sv.render() for sv in cc] def _observer_window_level(self, slice_viewer, idx=0): """This is called whenever the window/level is changed. We don't have to render, because the SetWindowLevel() call does that already. """ if not self.sync: return self.sync_window_level(slice_viewer, idx) def remove_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: # first remove all observers that we might have added t = self.observer_tags[slice_viewer] istyle = slice_viewer.rwi.GetInteractorStyle() istyle.RemoveObserver( t['istyle InteractionEvent']) istyle.RemoveObserver( t['istyle MouseWheelForwardEvent']) istyle.RemoveObserver( t['istyle MouseWheelBackwardEvent']) for idx in range(3): ipw = slice_viewer.ipws[idx] ipw.RemoveObserver( t['ipw%d InteractionEvent' % (idx,)]) ipw.RemoveObserver( t['ipw%d WindowLevelEvent' % (idx,)]) # then delete our record of these observer tags del self.observer_tags[slice_viewer] # then delete our record of the slice_viewer altogether idx = self.slice_viewers.index(slice_viewer) del self.slice_viewers[idx] def sync_cameras(self, sv, dest_svs=None): """Sync all cameras to that of sv. Returns a list of changed SVs (so that you know which ones to render). """ cam = sv.renderer.GetActiveCamera() pos = cam.GetPosition() fp = cam.GetFocalPoint() vu = cam.GetViewUp() ps = cam.GetParallelScale() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if not other_sv is sv: other_ren = other_sv.renderer other_cam = other_ren.GetActiveCamera() other_cam.SetPosition(pos) other_cam.SetFocalPoint(fp) other_cam.SetViewUp(vu) # you need this too, else the parallel mode does not # synchronise. other_cam.SetParallelScale(ps) other_ren.UpdateLightsGeometryToFollowCamera() other_ren.ResetCameraClippingRange() changed_svs.append(other_sv) return changed_svs def sync_ipws(self, sv, idx=0, dest_svs=None): """Sync all slice positions to that of sv. Returns a list of changed SVs so that you know on which to call render. """ ipw = sv.ipws[idx] o,p1,p2 = ipw.GetOrigin(), \ ipw.GetPoint1(), ipw.GetPoint2() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: # nnsmit edit if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) # end edit other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() changed_svs.append(other_sv) # edit nnsmit # This fix is so nasty it makes me want to cry # TODO fix it properly :) if len(self.slice_viewers2) != 0: for other_sv in self.slice_viewers2: if other_sv is not sv: if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() other_sv.render() # end edit return changed_svs def sync_window_level(self, sv, idx=0, dest_svs=None): """Sync all window level settings with that of SV. Returns list of changed SVs: due to the SetWindowLevel call, these have already been rendered! """ ipw = sv.ipws[idx] w,l = ipw.GetWindow(), ipw.GetLevel() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: other_ipw = other_sv.ipws[idx] if w != other_ipw.GetWindow() or \ l != other_ipw.GetLevel(): other_ipw.SetWindowLevel(w,l,0) changed_svs.append(other_sv) return changed_svs def sync_all(self, sv, dest_svs=None): """Convenience function that performs all syncing possible of dest_svs to sv. It also take care of making only the necessary render calls. """ # FIXME: take into account all other slices too. c1 = set(self.sync_cameras(sv, dest_svs)) c2 = set(self.sync_ipws(sv, 0, dest_svs)) c3 = set(self.sync_window_level(sv, 0, dest_svs)) # we only need to call render on SVs that are in c1 or c2, but # NOT in c3, because WindowLevel syncing already does a # render. Use set operations for this: c4 = (c1 | c2) - c3 [isv.render() for isv in c4] ########################################################################### class CMSliceViewer: """Simple class for enabling 1 or 3 ortho slices in a 3D scene. """ def __init__(self, rwi, renderer): # nnsmit-edit self.overlay_active = 0; # end edit self.rwi = rwi self.renderer = renderer istyle = vtk.vtkInteractorStyleTrackballCamera() rwi.SetInteractorStyle(istyle) # we unbind the existing mousewheel handler so it doesn't # interfere rwi.Unbind(wx.EVT_MOUSEWHEEL) rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel) self.ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut = self.ipws[0].GetLookupTable() for ipw in self.ipws: ipw.SetInteractor(rwi) ipw.SetLookupTable(lut) # nnsmit-edit self.overlay_ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut2 = self.overlay_ipws[0].GetLookupTable() lut2.SetNumberOfTableValues(3) lut2.SetTableValue(0,0,0,0,0) lut2.SetTableValue(1,0.5,0,1,1) lut2.SetTableValue(2,1,0,0,1) lut2.Build() for ipw_overlay in self.overlay_ipws: ipw_overlay.SetInteractor(rwi) ipw_overlay.SetLookupTable(lut2) ipw_overlay.AddObserver('InteractionEvent', wx.EVT_MOUSEWHEEL) # now actually connect the sync_overlay observer for i,ipw in enumerate(self.ipws): ipw.AddObserver('InteractionEvent',lambda vtk_o, vtk_e, i=i: self.observer_sync_overlay(self.ipws,i)) # end edit # we only set the picker on the visible IPW, else the # invisible IPWs block picking! self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self.ipws[0].SetPicker(self.picker) self.outline_source = vtk.vtkOutlineCornerFilter() m = vtk.vtkPolyDataMapper() m.SetInput(self.outline_source.GetOutput()) a = vtk.vtkActor() a.SetMapper(m) a.PickableOff() self.outline_actor = a self.dv_orientation_widget = DVOrientationWidget(rwi) # this can be used by clients to store the current world # position self.current_world_pos = (0,0,0) self.current_index_pos = (0,0,0) # nnsmit-edit def observer_sync_overlay(self,ipws,ipw_idx): # get the primary IPW pipw = ipws[ipw_idx] # get the overlay IPW oipw = self.overlay_ipws[ipw_idx] # get plane geometry from primary o,p1,p2 = pipw.GetOrigin(),pipw.GetPoint1(),pipw.GetPoint2() # and apply to the overlay oipw.SetOrigin(o) oipw.SetPoint1(p1) oipw.SetPoint2(p2) oipw.UpdatePlacement() # end edit def close(self): self.set_input(None) self.dv_orientation_widget.close() self.set_overlay_input(None) def activate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(1) self.ipws[idx].SetPicker(self.picker) def deactivate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(0) self.ipws[idx].SetPicker(None) def get_input(self): return self.ipws[0].GetInput() def get_world_pos(self, image_pos): """Given image coordinates, return the corresponding world position. """ idata = self.get_input() if not idata: return None ispacing = idata.GetSpacing() iorigin = idata.GetOrigin() # calculate real coords world = map(operator.add, iorigin, map(operator.mul, ispacing, image_pos[0:3])) def set_perspective(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOff() def set_parallel(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOn() # nnsmit edit def set_opacity(self,opacity): lut = self.ipws[0].GetLookupTable() lut.SetAlphaRange(opacity, opacity) lut.Build() self.ipws[0].SetLookupTable(lut) # end edit def _handler_mousewheel(self, event): # event.GetWheelRotation() is + or - 120 depending on # direction of turning. if event.ControlDown(): delta = 10 elif event.ShiftDown(): delta = 1 else: # if user is NOT doing shift / control, we pass on to the # default handling which will give control to the VTK # mousewheel handlers. self.rwi.OnMouseWheel(event) return if event.GetWheelRotation() > 0: self._ipw1_delta_slice(+delta) else: self._ipw1_delta_slice(-delta) self.render() self.ipws[0].InvokeEvent('InteractionEvent') def _ipw1_delta_slice(self, delta): """Move to the delta slices fw/bw, IF the IPW is currently aligned with one of the axes. """ ipw = self.ipws[0] if ipw.GetPlaneOrientation() < 3: ci = ipw.GetSliceIndex() ipw.SetSliceIndex(ci + delta) def render(self): self.rwi.GetRenderWindow().Render() # nnsmit edit # synch those overlays: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) # end edit def reset_camera(self): self.renderer.ResetCamera() cam = self.renderer.GetActiveCamera() cam.SetViewUp(0,-1,0) def reset_to_default_view(self, view_index): """ @param view_index 2 for XY """ if view_index == 2: cam = self.renderer.GetActiveCamera() # then make sure it's up is the right way cam.SetViewUp(0,-1,0) # just set the X,Y of the camera equal to the X,Y of the # focal point. fp = cam.GetFocalPoint() cp = cam.GetPosition() if cp[2] < fp[2]: z = fp[2] + (fp[2] - cp[2]) else: z = cp[2] cam.SetPosition(fp[0], fp[1], z) # first reset the camera self.renderer.ResetCamera() # nnsmit edit # synch overlays as well: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): ipw_overlay.SetSliceIndex(0) for i, ipw in enumerate(self.ipws): ipw.SetWindowLevel(500,-800,0) self.render() # end edit def set_input(self, input): ipw = self.ipws[0] ipw.DisplayTextOn() if input == ipw.GetInput(): return if input is None: # remove outline actor, else this will cause errors when # we disable the IPWs (they call a render!) self.renderer.RemoveViewProp(self.outline_actor) self.outline_source.SetInput(None) self.dv_orientation_widget.set_input(None) for ipw in self.ipws: # argh, this disable causes a render ipw.SetEnabled(0) ipw.SetInput(None) else: self.outline_source.SetInput(input) self.renderer.AddViewProp(self.outline_actor) orientations = [2, 0, 1] active = [1, 0, 0] for i, ipw in enumerate(self.ipws): ipw.SetInput(input) ipw.SetWindowLevel(500,-800,0) ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) ipw.SetEnabled(active[i]) self.dv_orientation_widget.set_input(input) # nnsmit-edit # FIXME: Create pretty fix for this codeclone. def set_overlay_input(self, input): self.overlay_active = 1 ipw = self.overlay_ipws[0] if input == ipw.GetInput(): return if input is None: self.overlay_active = 0; for ipw_overlay in self.overlay_ipws: ipw_overlay.SetEnabled(0) ipw_overlay.SetInput(None) else: active = [1, 0, 0] orientations = [2, 0, 1] for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) ipw_overlay.SetInput(input) ipw_overlay.SetPlaneOrientation(orientations[i]) # axial ipw_overlay.SetEnabled(active[i]) self.render() # end edit
Python
from module_mixins import simpleVTKClassModuleBase import vtktud class imageKnutssonMapping(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageKnutssonMapping(), 'Image Knutsson Mapping.', ('vtkImageData',), ('vtkImageData',))
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import vtktud class MyGlyph3D(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._glyph3d = vtktud.vtkMyGlyph3D() module_utils.setup_vtk_object_progress(self, self._glyph3d, 'Making 3D glyphs') self._config.scaling = 1.0 self._config.scalemode = 1.0 configList = [ ('Scaling:', 'scaling', 'base:float', 'text', 'Glyphs will be scaled by this factor.'), ('Scalemode:', 'scalemode', 'base:int', 'text', 'Scaling will occur by scalar, vector direction or magnitude.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkMyGlyph3D' : self._glyph3d}) # 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.logic_to_config() self.config_to_view() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._glyph3d def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._glyph3d.SetInput(inputStream) def get_output_descriptions(self): return ('Glyphs (vtkPolyData)', ) def get_output(self, idx): return self._glyph3d.GetOutput() def logic_to_config(self): self._config.scaling = self._glyph3d.GetScaling() self._config.scalemode = self._glyph3d.GetScaleMode() def config_to_logic(self): self._glyph3d.SetScaling(self._config.scaling) self._glyph3d.SetScaleMode(self._config.scalemode) def execute_module(self): self._glyph3d.Update()
Python
# $Id: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $ class MyGaussian: kits = ['vtk_kit'] cats = ['User','Optic Flow'] keywords = ['gaussian', 'source']
Python
# dummy __init__ so that this dir will be seen as package.
Python
# muscleLinesToSurface copyright (c) 2003 Charl P. Botha http://cpbotha.net/ # $Id$ from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class muscleLinesToSurface(ModuleBase, NoConfigModuleMixin): """Given muscle centre lines marked with 0-valued voxels, calculate a continuous surface through these marked lines. Make sure that ONLY the desired voxels have 0 value. You can do this with for instance the doubleThreshold DeVIDE module. This module calculates a 3D distance field, processes this field to yield a signed distance field, extracts an isosurface and then clips off extraneous surfaces. NOTE: there should be SOME voxels on ALL slices, i.e. black slices are not allowed. Handling this graciously would add far too much complexity to this code. We're already handling breaks in the x-y plane. $Revision: 1.1 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) self._distance = vtk.vtkImageEuclideanDistance() # this seems to yield more accurate results in this case # it would probably be better to calculate only 2d distance fields self._distance.ConsiderAnisotropyOff() self._xEndPoints = [] self._noFlipXes = [] self._pf1 = vtk.vtkProgrammableFilter() # yeah self._pf1.SetInput(self._distance.GetOutput()) self._pf1.SetExecuteMethod(self.pf1Execute) self._pf2 = vtk.vtkProgrammableFilter() self._pf2.SetInput(self._pf1.GetOutput()) self._pf2.SetExecuteMethod(self.pf2Execute) self._mc = vtk.vtkMarchingCubes() self._mc.SetInput(self._pf1.GetOutput()) self._mc.SetValue(0,0.1) self._iv = vtk.vtkImplicitVolume() self._iv.SetVolume(self._pf2.GetOutput()) self._cpd = vtk.vtkClipPolyData() self._cpd.SetClipFunction(self._iv) self._cpd.SetInput(self._mc.GetOutput()) #self._cpd.InsideOutOn() module_utils.setup_vtk_object_progress(self, self._distance, 'Calculating distance field...') module_utils.setup_vtk_object_progress(self, self._pf1, 'Signing distance field...') module_utils.setup_vtk_object_progress(self, self._pf2, 'Creating implicit volume...') module_utils.setup_vtk_object_progress(self, self._mc, 'Extracting isosurface...') module_utils.setup_vtk_object_progress(self, self._cpd, 'Clipping isosurface...') self._iObj = self._distance self._oObj = self._cpd #self._oObj = self._pf2 self._viewFrame = self._createViewFrame({'distance' : self._distance, 'pf1' : self._pf1, 'pf2' : self._pf2, 'mc' : self._mc, 'cpd' : self._cpd}) def pf1Execute(self): inputData = self._pf1.GetStructuredPointsInput() outputData = self._pf1.GetOutput() # we would like to operate on the WHOLE shebang inputData.UpdateInformation() # SetUpdateExtentToWholeExtent precond inputData.SetUpdateExtentToWholeExtent() inputData.Update() #print "Extent: %s" % (inputData.GetUpdateExtent(),) dimx, dimy, dimz = inputData.GetDimensions() #print "Dimensions: %s" % ((dimx, dimy, dimz),) if dimx == 0 or dimy == 0 or dimz == 0: # FIXME: say something about what went wrong outputData.SetExtent(0, -1, 0, -1, 0, -1) outputData.SetUpdateExtent(0, -1, 0, -1, 0, -1) outputData.SetWholeExtent(0, -1, 0, -1, 0, -1) outputData.AllocateScalars() return outputData.DeepCopy(inputData) xdim = inputData.GetWholeExtent()[1] ydim = inputData.GetWholeExtent()[3] zdim = inputData.GetWholeExtent()[5] self._xEndPoints = [[] for dummy in range(zdim + 1)] self._noFlipXes = [{} for dummy in range(zdim + 1)] for z in xrange(zdim + 1): x = 0 startPointFound = False while not startPointFound and x != xdim + 1: for y in xrange(ydim + 1): val = inputData.GetScalarComponentAsDouble(x,y,z,0) if val == 0: startPointFound = True self._xEndPoints[z].append((x,y)) # this will break out of the for loop (no else clause # will be executed) break x += 1 if not startPointFound: wx.LogError("ERROR: startPoint not found on slice %d." % (z,)) return x = xdim endPointFound = False while not endPointFound and x != -1: for y in xrange(ydim + 1): val = inputData.GetScalarComponentAsDouble(x,y,z,0) if val == 0: endPointFound = True self._xEndPoints[z].append((x,y)) break x -= 1 if not endPointFound: wx.LogError("ERROR: endPoint not found on slice %d." % (z,)) return prevFlipy = -1 for x in xrange(self._xEndPoints[z][0][0], self._xEndPoints[z][1][0] + 1): signFlip = False signFlipped = False prevVal = -1 for y in xrange(ydim + 1): val = inputData.GetScalarComponentAsDouble(x,y,z,0) if val == 0 and prevVal != 0: signFlip = not signFlip signFlipped = True prevFlipy = y if signFlip: outputData.SetScalarComponentFromDouble(x,y,z,0,-val) else: # this is necessary (CopyStructure doesn't do it) outputData.SetScalarComponentFromDouble(x,y,z,0,val) prevVal = val if not signFlipped: # if we went right through without striking a voxel, # note the x position - we should not correct it in # our correction step! self._noFlipXes[z][x] = prevFlipy elif x - 1 in self._noFlipXes[z]: # the sign has flipped again, the previous col was a # noflip, # so adjust the LAST flipped X's y coord (for the masking # in the implicitVolume) self._noFlipXes[z][x-1] = prevFlipy # now check the bottom row of the distance field! for x in xrange(self._xEndPoints[z][0][0], self._xEndPoints[z][1][0] + 1): val = outputData.GetScalarComponentAsDouble(x,ydim,z,0) if val > 0 and x not in self._noFlipXes[z]: # this means it's screwed, we have to redo from bottom up # first make all positive until we reach 0 again y = ydim while val != 0 and y != -1: val = outputData.GetScalarComponentAsDouble(x,y,z,0) if val > 0: outputData.SetScalarComponentFromDouble( x,y,z,0,-val) y -= 1 # FIXME: continue here... past the first 0, we have to # check for each voxel whether it's inside or outside self._pf1.UpdateProgress(z / float(zdim)) # end for z def pf2Execute(self): """Mask unwanted surface out with negative numbers. I'm evil. """ inputData = self._pf2.GetStructuredPointsInput() outputData = self._pf2.GetOutput() # we would like to operate on the WHOLE shebang inputData.UpdateInformation() inputData.SetUpdateExtentToWholeExtent() inputData.Update() dimx, dimy, dimz = inputData.GetDimensions() if dimx == 0 or dimy == 0 or dimz == 0: # FIXME: say something about what went wrong outputData.SetExtent(0, -1, 0, -1, 0, -1) outputData.SetUpdateExtent(0, -1, 0, -1, 0, -1) outputData.SetWholeExtent(0, -1, 0, -1, 0, -1) outputData.AllocateScalars() return outputData.DeepCopy(inputData) xdim = inputData.GetWholeExtent()[1] ydim = inputData.GetWholeExtent()[3] zdim = inputData.GetWholeExtent()[5] for z in xrange(zdim + 1): x0 = self._xEndPoints[z][0][0] y0 = self._xEndPoints[z][0][1] for y in xrange(y0, ydim + 1): for x in xrange(0, x0): val = inputData.GetScalarComponentAsDouble(x,y,z,0) # make this negative as well, so that the surface will # get nuked by this implicitvolume outputData.SetScalarComponentFromDouble(x,y,z,0,-val) x1 = self._xEndPoints[z][1][0] y1 = self._xEndPoints[z][1][1] for y in xrange(y1, ydim + 1): for x in xrange(x1 + 1, xdim + 1): val = inputData.GetScalarComponentAsDouble(x,y,z,0) # make this negative as well, so that the surface will # get nuked by this implicitvolume outputData.SetScalarComponentFromDouble(x,y,z,0,-val) self._pf2.UpdateProgress(z / float(zdim)) for xf,yf in self._noFlipXes[z].items(): for y in xrange(yf, ydim + 1): val = inputData.GetScalarComponentAsDouble(xf,y,z,0) # this was noflip data, so it used to be positive # we now make it negative, to get rid of all # surfaces that so originated outputData.SetScalarComponentFromDouble(xf,y,z,0,-val) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._distance del self._mc del self._iv del self._cpd del self._pf1 del self._pf2 del self._iObj del self._oObj def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._iObj.SetInput(inputStream) if inputStream: # we need the poor old doubleThreshold to give us # everything that it has. It's quite stingy with # its UpdateExtent inputStream.SetUpdateExtentToWholeExtent() def get_output_descriptions(self): return (self._oObj.GetOutput().GetClassName(),) def get_output(self, idx): return self._oObj.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._oObj.GetOutput().Update() #print str(self._pf2.GetOutput().GetPointData().GetScalars()) def view(self, parent_window=None): self._viewFrame.Show(True) self._viewFrame.Raise()
Python
from module_mixins import simpleVTKClassModuleBase import vtktud class imageExtentUnionizer(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageExtentUnionizer(), 'Image Extent Unionizer.', ('vtkImageData',), ('vtkImageData',))
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class gaussianKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a gaussian implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.standardDeviation = 1.0 self._config.support = 3.0 * self._config.standardDeviation # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the gaussian kernel (0-2).'), ('Standard deviation: ', 'standardDeviation', 'base:float', 'text', 'The standard deviation (width) of the gaussian kernel.'), ('Support: ', 'support', 'base:float', 'text', 'The support of the gaussian kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._gaussianKernel = vtktud.vtkGaussianKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkGaussianKernel' : self._gaussianKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gaussianKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._gaussianKernel def config_to_logic(self): # sanity check if self._config.standardDeviation < 0.0: self._config.standardDeviation = 0.0 if self._config.support < 0.0: self._config.support = 0.0 self._gaussianKernel.SetOrder( self._config.order ) self._gaussianKernel.SetStandardDeviation( self._config.standardDeviation ) self._gaussianKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._gaussianKernel.GetOrder() self._config.standardDeviation = self._gaussianKernel.GetStandardDeviation() self._config.support = self._gaussianKernel.GetSupport()
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx class myImageClip(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._clipper = vtk.vtkImageClip() module_utils.setup_vtk_object_progress(self, self._clipper, 'Reading PNG images.') self._config.outputWholeExtent = (0,-1,0,-1,0,-1) configList = [ ('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text', 'The size of the clip volume.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageClip' : self._clipper}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._clipper def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): if idx == 0: self._clipper.SetInput(inputStream) else: raise Exception def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._clipper.GetOutput() def logic_to_config(self): self._config.outputWholeExtent = self._clipper.GetOutputWholeExtent() def config_to_logic(self): self._clipper.SetOutputWholeExtent( self._config.outputWholeExtent, None ) def execute_module(self): self._clipper.Update()
Python
# $Id$ class simplestVTKExample: kits = ['vtk_kit'] cats = ['User'] class isolated_points_check: kits = ['vtk_kit'] cats = ['User'] class testModule: kits = ['vtk_kit'] cats = ['User']
Python
from module_mixins import simpleVTKClassModuleBase import vtktud class imageCopyPad(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageCopyPad(), 'Extending image by copying border voxels.', ('vtkImageData',), ('vtkImageData',))
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class reconstructSurface(ModuleBase, NoConfigModuleMixin): """Given a binary volume, fit a surface through the marked points. A doubleThreshold could be used to extract points of interest from a volume. By passing it through this module, a surface will be fit through those points of interest. The points of interest have to be of value 1 or greater. This is not to be confused with traditional iso-surface extraction. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) # we'll be playing around with some vtk objects, this could # be anything self._thresh = vtk.vtkThresholdPoints() # this is wacked syntax! self._thresh.ThresholdByUpper(1) self._reconstructionFilter = vtk.vtkSurfaceReconstructionFilter() self._reconstructionFilter.SetInput(self._thresh.GetOutput()) self._mc = vtk.vtkMarchingCubes() self._mc.SetInput(self._reconstructionFilter.GetOutput()) self._mc.SetValue(0, 0.0) module_utils.setup_vtk_object_progress(self, self._thresh, 'Extracting points...') module_utils.setup_vtk_object_progress(self, self._reconstructionFilter, 'Reconstructing...') module_utils.setup_vtk_object_progress(self, self._mc, 'Extracting surface...') self._iObj = self._thresh self._oObj = self._mc self._viewFrame = self._createViewFrame({'threshold' : self._thresh, 'reconstructionFilter' : self._reconstructionFilter, 'marchingCubes' : self._mc}) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._thresh del self._reconstructionFilter del self._mc del self._iObj del self._oObj def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._iObj.SetInput(inputStream) def get_output_descriptions(self): return (self._oObj.GetOutput().GetClassName(),) def get_output(self, idx): return self._oObj.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._oObj.Update() def view(self, parent_window=None): self._viewFrame.Show(True) self._viewFrame.Raise()
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud import wx class imageSepConvolution(ScriptedConfigModuleMixin, ModuleBase): """ lksajflksjdf """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageSepConvolution = vtktud.vtkImageSepConvolution() # module_utils.setup_vtk_object_progress(self, self._clipper, # 'Reading PNG images.') # set information for ScriptedConfigModuleMixin self._config.axis = 0 # FIXME: include options for kernel normalisation? configList = [ ('Axis:', 'axis', 'base:int', 'choice', 'Axis over which convolution is to be performed.', ("X", "Y", "Z") ) ] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageSepConvolution' : self._imageSepConvolution}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageSepConvolution def get_input_descriptions(self): return ('vtkImageData', 'vtkSeparableKernel') def set_input(self, idx, inputStream): if idx == 0: self._imageSepConvolution.SetInput(inputStream) else: self._imageSepConvolution.SetKernel(inputStream) def get_output_descriptions(self): return (self._imageSepConvolution.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageSepConvolution.GetOutput() def logic_to_config(self): self._config.axis = self._imageSepConvolution.GetAxis() def config_to_logic(self): self._imageSepConvolution.SetAxis( self._config.axis ) def execute_module(self): self._imageSepConvolution.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageCurvatureMagnitude(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageCurvatureMagnitude = vtktud.vtkImageCurvatureMagnitude() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageCurvatureMagnitude' : self._imageCurvatureMagnitude}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageCurvatureMagnitude def get_input_descriptions(self): return ('vtkImageData', 'vtkImageData', 'vtkImageData','vtkImageData', 'vtkImageData') def set_input(self, idx, inputStream): self._imageCurvatureMagnitude.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageCurvatureMagnitude.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageCurvatureMagnitude.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class DilateExample(ScriptedConfigModuleMixin, ModuleBase): """Performs a greyscale 3D dilation on the input. $Revision: 1.2 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() module_utils.setup_vtk_object_progress(self, self._imageDilate, 'Performing greyscale 3D dilation') self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkImageContinuousDilate3D' : self._imageDilate}) # 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.logic_to_config() self.config_to_view() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageDilate def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return (self._imageDilate.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageDilate.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageDilate.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageDilate.Update() #def view(self, parent_window=None): # # if the window was visible already. just raise it # self._viewFrame.Show(True) # self._viewFrame.Raise()
Python
# $Id: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $ class DilateExample: kits = ['vtk_kit'] cats = ['User','Cartilage3D']
Python
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class simplestVTKExample(SimpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkStripper(), 'Stripping polydata.', ('vtkPolyData',), ('Stripped vtkPolyData',))
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class cubicBCSplineKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a cubic B-Spline implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.support = 4.0 self._config.B = 0.0; self._config.C = 0.5; # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the cubic B-Spline kernel (0-2).'), ('B: ', 'B', 'base:float', 'text', 'B'), ('C: ', 'C', 'base:float', 'text', 'C'), ('Support: ', 'support', 'base:float', 'text', 'The support of the cubic B-Spline kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._cubicBCSplineKernel = vtktud.vtkCubicBCSplineKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkCubicBCSplineKernel' : self._cubicBCSplineKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._cubicBCSplineKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._cubicBCSplineKernel def config_to_logic(self): # sanity check if self._config.support < 0.0: self._config.support = 0.0 self._cubicBCSplineKernel.SetOrder( self._config.order ) self._cubicBCSplineKernel.SetB( self._config.B ) self._cubicBCSplineKernel.SetC( self._config.C ) self._cubicBCSplineKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._cubicBCSplineKernel.GetOrder() self._config.B = self._cubicBCSplineKernel.GetB() self._config.C = self._cubicBCSplineKernel.GetC() self._config.support = self._cubicBCSplineKernel.GetSupport()
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import wx import vtk class myTubeFilter(ScriptedConfigModuleMixin, ModuleBase): """Simple demonstration of ScriptedConfigModuleMixin-based wrapping of a single VTK object. It would of course be even easier using simpleVTKClassModuleBase. $Revision: 1.1 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._tubeFilter = vtk.vtkTubeFilter() module_utils.setup_vtk_object_progress(self, self._tubeFilter, 'Generating tubes.') self._config.NumberOfSides = 3 self._config.Radius = 0.01 configList = [ ('Number of sides:', 'NumberOfSides', 'base:int', 'text', 'Number of sides that the tube should have.'), ('Tube radius:', 'Radius', 'base:float', 'text', 'Radius of the generated tube.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkTubeFilter' : self._tubeFilter}) # 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._tubeFilter def get_input_descriptions(self): return ('vtkPolyData lines',) def set_input(self, idx, inputStream): self._tubeFilter.SetInput(inputStream) def get_output_descriptions(self): return ('vtkPolyData tubes', ) def get_output(self, idx): return self._tubeFilter.GetOutput() def logic_to_config(self): self._config.NumberOfSides = self._tubeFilter.GetNumberOfSides() self._config.Radius = self._tubeFilter.GetRadius() def config_to_logic(self): self._tubeFilter.SetNumberOfSides(self._config.NumberOfSides) self._tubeFilter.SetRadius(self._config.Radius) def execute_module(self): self._tubeFilter.GetOutput().Update()
Python
# $Id$ # workaround to use adodbapi and other modules not # included with DeVIDE #import sys #sys.path = sys.path + ['', 'H:\\bld\\bin\\Wrapping\\CSwig\\Python\\RelWithDebInfo', 'H:\\opt\\python23\\Lib\\site-packages\\adodbapi', 'C:\\WINNT\\System32\\python23.zip', 'H:\\', 'H:\\opt\\python23\\DLLs', 'H:\\opt\\python23\\lib', 'H:\\opt\\python23\\lib\\plat-win', 'H:\\opt\\python23\\lib\\lib-tk', 'H:\\opt\\python23', 'H:\\opt\\python23\\Lib\\site-packages\\win32', 'H:\\opt\\python23\\Lib\\site-packages\\win32\\lib', 'H:\\opt\\python23\\Lib\\site-packages\\Pythonwin', 'H:\\opt\\python23\\lib\\site-packages\\adodbapi'] from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import fixitk as itk import wx from datetime import date from adodbapi import * from modules.Insight.typeModules.transformStackClass import transformStackClass class reconstructionRDR(ScriptedConfigModuleMixin, ModuleBase): """Fetches a transform stack from an MS Access database $Revision: 1.1 $ """ def __init__(self, module_manager): # call the parent constructor ModuleBase.__init__(self, module_manager) # this is our output self._transformStack = transformStackClass( self ) # module_utils.setup_vtk_object_progress(self, self._reader, # 'Fetching transformStack from database...') self._config.databaseFile = "" self._config.reconstructionName = "--- select a value ---" configList = [ ('Database:', 'databaseFile', 'base:str', 'filebrowser', 'Database from which to fetch a reconstruction''s transformStack.', {'fileMode' : wx.OPEN, 'fileMask' : 'MDB files (*.mdb)|*.mdb|All files (*.*)|*.*'}), ('Reconstruction:', 'reconstructionName', 'base:str', 'choice', 'Specific reconstruction to use.', ("--- select a value ---",) ) ] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame({'Module (self)' : self}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) # for input_idx in range(len(self.get_input_descriptions())): # self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference # del self._reader def get_input_descriptions(self): return () def set_input(self, idx, inputStream): raise Exception def get_output_descriptions(self): return ('2D Transform Stack',) def get_output(self, idx): return self._transformStack def logic_to_config(self): #self._config.filePrefix = self._reader.GetFilePrefix() #self._config.filePattern = self._reader.GetFilePattern() #self._config.firstSlice = self._reader.GetFileNameSliceOffset() #e = self._reader.GetDataExtent() #self._config.lastSlice = self._config.firstSlice + e[5] - e[4] #self._config.spacing = self._reader.GetDataSpacing() #self._config.fileLowerLeft = bool(self._reader.GetFileLowerLeft()) pass def config_to_logic(self): # get choice widget binding choiceBind = self._widgets[self._configList[1][0:5]] # abuse choiceBind.Clear() choiceBind.Append( "--- select a value ---" ) reconstructionName = "--- select a value ---" # attempt to append a list at once if len( self._config.databaseFile ): for e in self._getAvailableReconstructions(): choiceBind.Append( e ) def execute_module(self): if len( self._config.databaseFile ): self._fetchTransformStack() def _getAvailableReconstructions( self ): # connect to the database connectString = r"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + self._config.databaseFile + ";" try: connection = adodbapi.connect( connectString ) except adodbapi.Error: raise IOError, "Could not open database." cursor = connection.cursor() cursor.execute( "SELECT name FROM reconstruction ORDER BY run_date" ) reconstruction_list = cursor.fetchall() cursor.close() connection.close() # cast list of 1-tuples to list return [ e[ 0 ] for e in reconstruction_list ] def _fetchTransformStack( self ): # connect to the database connectString = r"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + self._config.databaseFile + ";" try: connection = adodbapi.connect( connectString ) except adodbapi.Error: raise IOError, "Could not open database." # try to figure out reconstruction ID from recontruction name print "NAME: " + self._config.reconstructionName cursor = connection.cursor() cursor.execute( "SELECT id FROM reconstruction WHERE name=?", [ self._config.reconstructionName ] ) row = cursor.fetchone() if row == None: raise IOError, "Reconstruction not found." print "reconstructionID: %i" % row[ 0 ] # build transformStack cursor.execute( "SELECT angle, centerx, centery, tx, ty FROM centeredRigid2DTransform WHERE reconstruction_id=? ORDER BY seq_nr", [ row[ 0 ] ] ) for row in cursor.fetchall(): trfm = itk.itkCenteredRigid2DTransform_New() params = trfm.GetParameters() for i in range(0,5): params.SetElement( i, row[ i ] ) trfm.SetParameters( params ) self._transformStack.append( trfm ) cursor.close() connection.close()
Python
# this is (possibly broken) code to perform a marker-based watershed # segmentation on a mesh by making use of a pre-segmentation # modification of curvature homotopy # test this on some synthetic data (cube with markers on all six faces) # before you use it for anything serious. # IDEA: # use vtkPolyDataConnectivityFilter with minima as seed points from module_base import ModuleBase from module_mixins import NoConfigModuleMixin from wxPython.wx import * import vtk class testModule3(ModuleBase, NoConfigModuleMixin): """Module to prototype modification of homotopy and subsequent watershedding of curvature-on-surface image. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) mm = self._module_manager self._cleaner = vtk.vtkCleanPolyData() self._tf = vtk.vtkTriangleFilter() self._tf.SetInput(self._cleaner.GetOutput()) self._wspdf = vtk.vtkWindowedSincPolyDataFilter() #self._wspdf.SetNumberOfIterations(50) self._wspdf.SetInput(self._tf.GetOutput()) self._wspdf.SetProgressText('smoothing') self._wspdf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf)) self._cleaner2 = vtk.vtkCleanPolyData() self._cleaner2.SetInput(self._wspdf.GetOutput()) self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMean() self._curvatures.SetInput(self._cleaner2.GetOutput()) self._tf.SetProgressText('triangulating') self._tf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf)) self._curvatures.SetProgressText('calculating curvatures') self._curvatures.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures)) self._inputFilter = self._tf self._inputPoints = None self._inputPointsOID = None self._giaGlenoid = None self._outsidePoints = None self._outputPolyDataARB = vtk.vtkPolyData() self._outputPolyDataHM = vtk.vtkPolyData() self._createViewFrame('Test Module View', {'vtkTriangleFilter' : self._tf, 'vtkCurvatures' : self._curvatures}) self._viewFrame.Show(True) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._cleaner del self._cleaner2 del self._wspdf del self._curvatures del self._tf del self._inputPoints del self._outputPolyDataARB del self._outputPolyDataHM def get_input_descriptions(self): return ('vtkPolyData', 'Watershed minima') def set_input(self, idx, inputStream): if idx == 0: self._inputFilter.SetInput(inputStream) else: if inputStream is not self._inputPoints: if self._inputPoints: self._inputPoints.removeObserver(self._inputPointsOID) if inputStream: self._inputPointsOID = inputStream.addObserver( self._inputPointsObserver) self._inputPoints = inputStream # initial update self._inputPointsObserver(None) def get_output_descriptions(self): return ('ARB PolyData output', 'Homotopically modified polydata') def get_output(self, idx): if idx == 0: return self._outputPolyDataARB else: return self._outputPolyDataHM def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): if self._inputFilter.GetInput() and \ self._outsidePoints and self._giaGlenoid: self._curvatures.Update() # vtkCurvatures has added a mean curvature array to the # pointData of the output polydata pd = self._curvatures.GetOutput() # make a deep copy of the data that we can work with tempPd1 = vtk.vtkPolyData() tempPd1.DeepCopy(self._curvatures.GetOutput()) # and now we have to unsign it! tempPd1Scalars = tempPd1.GetPointData().GetScalars() for i in xrange(tempPd1Scalars.GetNumberOfTuples()): a = tempPd1Scalars.GetTuple1(i) tempPd1Scalars.SetTuple1(i, float(abs(a))) self._outputPolyDataARB.DeepCopy(tempPd1) # BUILDING NEIGHBOUR MAP #################################### # iterate through all points numPoints = tempPd1.GetNumberOfPoints() neighbourMap = [[] for i in range(numPoints)] cellIdList = vtk.vtkIdList() pointIdList = vtk.vtkIdList() for ptId in xrange(numPoints): # this has to be first neighbourMap[ptId].append(ptId) tempPd1.GetPointCells(ptId, cellIdList) # we now have all edges meeting at point i for cellIdListIdx in range(cellIdList.GetNumberOfIds()): edgeId = cellIdList.GetId(cellIdListIdx) tempPd1.GetCellPoints(edgeId, pointIdList) # there have to be two points per edge, # one if which is the centre-point itself # FIXME: we should check, cells aren't LIMITED to two # points, but could for instance be a longer line-segment # or a quad or somesuch for pointIdListIdx in range(pointIdList.GetNumberOfIds()): tempPtId = pointIdList.GetId(pointIdListIdx) if tempPtId not in neighbourMap[ptId]: neighbourMap[ptId].append(tempPtId) #print neighbourMap[ptId] if ptId % (numPoints / 20) == 0: self._module_manager.setProgress(100.0 * ptId / numPoints, "Building neighbour map") self._module_manager.setProgress(100.0, "Done building neighbour map") # DONE BUILDING NEIGBOUR MAP ################################ # BUILDING SEED IMAGE ####################################### # now let's build the seed image # wherever we want to enforce minima, the seed image # should be equal to the lowest value of the mask image # everywhere else it should be the maximum value of the mask # image cMin, cMax = tempPd1.GetScalarRange() print "range: %d - %d" % (cMin, cMax) seedPd = vtk.vtkPolyData() # first make a copy of the complete PolyData seedPd.DeepCopy(tempPd1) # now change EVERYTHING to the maximum value print seedPd.GetPointData().GetScalars().GetName() # we know that the active scalars thingy has only one component, # namely Mean_Curvature - set it all to MAX seedPd.GetPointData().GetScalars().FillComponent(0, cMax) # now find the minima and set them too gPtId = seedPd.FindPoint(self._giaGlenoid) seedPd.GetPointData().GetScalars().SetTuple1(gPtId, cMin) for outsidePoint in self._outsidePoints: oPtId = seedPd.FindPoint(outsidePoint) seedPd.GetPointData().GetScalars().SetTuple1(oPtId, cMin) # remember vtkDataArray: array of tuples, each tuple made up # of n components # DONE BUILDING SEED IMAGE ################################### # MODIFY MASK IMAGE ########################################## # make sure that the minima as indicated by the user are cMin # in the mask image! gPtId = tempPd1.FindPoint(self._giaGlenoid) tempPd1.GetPointData().GetScalars().SetTuple1(gPtId, cMin) for outsidePoint in self._outsidePoints: oPtId = tempPd1.FindPoint(outsidePoint) tempPd1.GetPointData().GetScalars().SetTuple1(oPtId, cMin) # DONE MODIFYING MASK IMAGE ################################## # BEGIN erosion + supremum (modification of image homotopy) newSeedPd = vtk.vtkPolyData() newSeedPd.DeepCopy(seedPd) # get out some temporary variables tempPd1Scalars = tempPd1.GetPointData().GetScalars() seedPdScalars = seedPd.GetPointData().GetScalars() newSeedPdScalars = newSeedPd.GetPointData().GetScalars() stable = False iteration = 0 while not stable: for nbh in neighbourMap: # by definition, EACH position in neighbourmap must have # at least ONE (1) ptId # create list with corresponding curvatures nbhC = [seedPdScalars.GetTuple1(ptId) for ptId in nbh] # sort it nbhC.sort() # replace the centre point in newSeedPd with the lowest val newSeedPdScalars.SetTuple1(nbh[0], nbhC[0]) # now put result of supremum of newSeed and tempPd1 (the mask) # directly into seedPd - the loop can then continue # in theory, these two polydatas have identical pointdata # go through them, constructing newSeedPdScalars # while we're iterating through this loop, also check if # newSeedPdScalars is identical to seedPdScalars stable = True for i in xrange(newSeedPdScalars.GetNumberOfTuples()): a = newSeedPdScalars.GetTuple1(i) b = tempPd1Scalars.GetTuple1(i) c = [b, a][bool(a > b)] if stable and c != seedPdScalars.GetTuple1(i): # we only check if stable == True # if a single scalar is different, stable becomes # false and we'll never have to check again stable = False print "unstable on point %d" % (i) # stuff the result directly into seedPdScalars, ready # for the next iteration seedPdScalars.SetTuple1(i, c) self._module_manager.setProgress(iteration / 500.0 * 100.0, "Homotopic modification") print "iteration %d done" % (iteration) iteration += 1 #if iteration == 2: # stable = True # seedPd is the output of the homotopic modification # END of erosion + supremum # BEGIN watershed pointLabels = [-1 for i in xrange(seedPd.GetNumberOfPoints())] # mark all minima as separate regions gPtId = seedPd.FindPoint(self._giaGlenoid) pointLabels[gPtId] = 1 i = 1 for outsidePoint in self._outsidePoints: oPtId = seedPd.FindPoint(outsidePoint) pointLabels[oPtId] = i * 200 i += 1 # now, iterate through all non-marked points seedPdScalars = seedPd.GetPointData().GetScalars() for ptId in xrange(seedPd.GetNumberOfPoints()): if pointLabels[ptId] == -1: print "starting ws with ptId %d" % (ptId) pathDone = False # this will contain all the pointIds we walk along, # starting with ptId (new path!) thePath = [ptId] while not pathDone: # now search for a neighbour with the lowest curvature # but also lower than ptId itself nbh = neighbourMap[thePath[-1]] nbhC = [seedPdScalars.GetTuple1(pi) for pi in nbh] cmi = 0 # curvature minimum index cmi # remember that in the neighbourhood map # the "centre" point is always first cms = nbhC[cmi] for ci in range(len(nbhC)): # contour index ci if nbhC[ci] < cms: cmi = ci cms = nbhC[ci] if cmi != 0: # this means we found a point we can move on to if pointLabels[nbh[cmi]] != -1: # if this is a labeled point, we know which # basin thePath belongs to theLabel = pointLabels[nbh[cmi]] for newLabelPtId in thePath: pointLabels[newLabelPtId] = theLabel print "found new path: %d (%d)" % \ (theLabel, len(thePath)) # and our loop is done pathDone = True else: # this is not a labeled point, which means # we just add it to our path thePath.append(nbh[cmi]) # END if cmi != 0 else: # we couldn't find any point lower than us! # let's eat as many plateau points as we can, # until we reach a lower-labeled point # c0 is the "current" curvature plateau, plateauNeighbours, plateauLabel = \ self._getPlateau(nbh[0], neighbourMap, seedPdScalars, pointLabels) if plateauLabel != -1: # this means the whole plateau is with a basin for i in plateau: thePath.append(i) for newLabelPtId in thePath: pointLabels[newLabelPtId] = plateauLabel print "found new path: %d (%d)" % \ (plateauLabel, len(thePath)) # and our loop is done pathDone = True elif not plateauNeighbours: # i.e. we have a single point or a floating # plateau... print "floating plateau!" pathDone = True else: # now look for the lowest neighbour # (c0 is the plateau scalar) minScalar = cms minId = -1 for nId in plateauNeighbours: si = seedPdScalars.GetTuple1(nId) if si < minScalar: minId = nId minScalar = si if minId != -1: # this means we found the smallest # neighbour # everything on the plateau gets added to # the path for i in plateau: thePath.append(i) if pointLabels[minId] != -1: # if this is a labeled point, we know # which basin thePath belongs to theLabel = pointLabels[minId] for newLabelPtId in thePath: pointLabels[newLabelPtId] = \ theLabel print "found new path: %d (%d)" % \ (theLabel, len(thePath)) # and our loop is done pathDone = True else: # this is not a labeled point, which # means we just add it to our path thePath.append(minId) else: print "HELP! - we found a minimum plateau!" # we're done with our little path walking... now we have to assign # our watershedded thingy to the output data self._outputPolyDataHM.DeepCopy(seedPd) for ptId in xrange(len(pointLabels)): self._outputPolyDataHM.GetPointData().GetScalars().SetTuple1( ptId, pointLabels[ptId]) def _getPlateau(self, initPt, neighbourMap, scalars, pointLabels): """Grow outwards from ptId nbh[0] and include all points with the same scalar value. return 2 lists: one with plateau ptIds and one with ALL the neighbour Ids. """ # by definition, the plateau will contain at least the initial point plateau = [initPt] plateauNeighbours = [] plateauLabel = -1 # we're going to use this to check VERY quickly whether we've # already stored a point donePoints = [False for i in xrange(len(neighbourMap))] donePoints[initPt] = True # and this is the scalar value of the plateau initScalar = scalars.GetTuple1(initPt) # setup for loop currentNeighbourPts = neighbourMap[initPt] # everything in currentNeighbourPts that has equal scalar # gets added to plateau while currentNeighbourPts: newNeighbourPts = [] for npt in currentNeighbourPts: if not donePoints[npt]: ns = scalars.GetTuple1(npt) if ns == initScalar: plateau.append(npt) # it could be that a point in our plateau is already # labeled - check for this if pointLabels[npt] != -1: plateauLabel = pointLabels[npt] else: plateauNeighbours.append(npt) donePoints[npt] = True # we've added a new point, now we need to get # its neighbours as well for i in neighbourMap[npt]: newNeighbourPts.append(i) currentNeighbourPts = newNeighbourPts return (plateau, plateauNeighbours, plateauLabel) def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise() def _inputPointsObserver(self, obj): # extract a list from the input points if self._inputPoints: # extract the two points with labels 'GIA Glenoid' # and 'GIA Humerus' giaGlenoid = [i['world'] for i in self._inputPoints if i['name'] == 'GIA Glenoid'] outsidePoints = [i['world'] for i in self._inputPoints \ if i['name'] == 'Outside'] if giaGlenoid and outsidePoints: # we only apply these points to our internal parameters # if they're valid and if they're new self._giaGlenoid = giaGlenoid[0] self._outsidePoints = outsidePoints
Python
import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import math class BSplineRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._create_pipeline() self._view_frame = None def _create_pipeline(self): interpolator = itk.LinearInterpolateImageFunction\ [itk.Image.F3, itk.D].New() metric = itk.MeanSquaresImageToImageMetric\ [itk.Image.F3, itk.Image.F3].New() optimizer = itk.LBFGSOptimizer.New() transform = itk.BSplineDeformableTransform[itk.D, 3, 3].New() r = itk.ImageRegistrationMethod[itk.Image.F3, itk.Image.F3].\ New( Interpolator=interpolator.GetPointer(), Metric=metric.GetPointer(), Optimizer=optimizer.GetPointer(), Transform=transform.GetPointer()) self._interpolator = interpolator self._metric = metric self._optimizer = optimizer self._transform = transform self._registration = r itk_kit.utils.setupITKObjectProgress( self, self._registration, 'BSpline Registration', 'Performing registration') itk_kit.utils.setupITKObjectProgress( self, self._optimizer, 'LBFGSOptimizer', 'Optimizing') def get_input_descriptions(self): return ('Fixed image', 'Moved image') def set_input(self, idx, input_stream): if idx == 0: self._fixed_image = input_stream self._registration.SetFixedImage(input_stream) else: self._moving_image = input_stream self._registration.SetMovingImage(input_stream) def get_output_descriptions(self): return ('BSpline Transform',) def get_output(self, idx): return self._registration.GetTransform() def execute_module(self): # itk.Size[3]() # itk.ImageRegion[3]() # we want a 1 node border on low x,y,z and a 2 node border on # high x,y,z; so if we want a bspline grid of 5x5x5, we need a # bspline region of 8x8x8 grid_size_on_image = [5,5,5] fi_region = self._fixed_image.GetBufferedRegion() self._registration.SetFixedImageRegion(fi_region) fi_size1 = fi_region.GetSize() fi_size = [fi_size1.GetElement(i) for i in range(3)] spacing = 3 * [0] origin = 3 * [0] for i in range(3): spacing[i] = self._fixed_image.GetSpacing().GetElement(i) * \ math.floor( (fi_size[i] - 1) / float(grid_size_on_image[i] - 1)) origin[i] = self._fixed_image.GetOrigin().GetElement(i) \ - spacing[i] self._transform.SetGridSpacing(spacing) self._transform.SetGridOrigin(origin) bspline_region = itk.ImageRegion[3]() bspline_region.SetSize([i + 3 for i in grid_size_on_image]) self._transform.SetGridRegion(bspline_region) num_params = self._transform.GetNumberOfParameters() params = itk.Array[itk.D](num_params) params.Fill(0.0) self._transform.SetParameters(params) self._registration.SetInitialTransformParameters( self._transform.GetParameters()) self._optimizer.SetGradientConvergenceTolerance( 0.05 ) self._optimizer.SetLineSearchAccuracy( 0.9 ) self._optimizer.SetDefaultStepLength( 1.5 ) self._optimizer.TraceOn() self._optimizer.SetMaximumNumberOfFunctionEvaluations( 1000 ) self._registration.Update() def logic_to_config(self): pass def config_to_logic(self): pass
Python
# dumy __init__ so this directory can function as a package
Python
# surfaceToDistanceField copyright (c) 2004 by Charl P. Botha cpbotha.net # $Id$ import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class surfaceToDistanceField(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._implicitModeller = vtk.vtkImplicitModeller() module_utils.setup_vtk_object_progress( self, self._implicitModeller, 'Converting surface to distance field') self._config.bounds = (-1, 1, -1, 1, -1, 1) self._config.dimensions = (64, 64, 64) self._config.maxDistance = 0.1 configList = [ ('Bounds:', 'bounds', 'tuple:float,6', 'text', 'The physical location of the sampled volume in space ' '(x0, x1, y0, y1, z0, z1)'), ('Dimensions:', 'dimensions', 'tuple:int,3', 'text', 'The number of points that should be sampled in each dimension.'), ('Maximum distance:', 'maxDistance', 'base:float', 'text', 'The distance will only be calculated up to this maximum.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImplicitModeller' : self._implicitModeller}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._implicitModeller def get_input_descriptions(self): return ('Surface (vtkPolyData)',) def set_input(self, idx, inputStream): self._implicitModeller.SetInput(inputStream) def get_output_descriptions(self): return ('Distance field (VTK Image Data)',) def get_output(self, idx): return self._implicitModeller.GetOutput() def logic_to_config(self): self._config.bounds = self._implicitModeller.GetModelBounds() self._config.dimensions = self._implicitModeller.GetSampleDimensions() self._config.maxDistance = self._implicitModeller.GetMaximumDistance() def config_to_logic(self): self._implicitModeller.SetModelBounds(self._config.bounds) self._implicitModeller.SetSampleDimensions(self._config.dimensions) self._implicitModeller.SetMaximumDistance(self._config.maxDistance) def execute_module(self): self._implicitModeller.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import IntrospectModuleMixin import module_utils import vtk class doubleThreshold(IntrospectModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._imageThreshold = vtk.vtkImageThreshold() module_utils.setup_vtk_object_progress(self, self._imageThreshold, 'Thresholding data') self._outputTypes = {'Double': 'VTK_DOUBLE', 'Float' : 'VTK_FLOAT', 'Long' : 'VTK_LONG', 'Unsigned Long' : 'VTK_UNSIGNED_LONG', 'Integer' : 'VTK_INT', 'Unsigned Integer' : 'VTK_UNSIGNED_INT', 'Short' : 'VTK_SHORT', 'Unsigned Short' : 'VTK_UNSIGNED_SHORT', 'Char' : 'VTK_CHAR', 'Unsigned Char' : 'VTK_UNSIGNED_CHAR', 'Same as input' : -1} self._view_frame = None # now setup some defaults before our sync self._config.lowerThreshold = 1250 self._config.upperThreshold = 2500 #self._config.rtu = 1 self._config.replaceIn = 1 self._config.inValue = 1 self._config.replaceOut = 1 self._config.outValue = 0 self._config.outputScalarType = self._imageThreshold.GetOutputScalarType() self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) # close down the vtkPipeline stuff IntrospectModuleMixin.close(self) # take out our view interface if self._view_frame is not None: self._view_frame.Destroy() # get rid of our reference del self._imageThreshold def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageThreshold.SetInput(inputStream) if not inputStream is None: # get scalar bounds minv, maxv = inputStream.GetScalarRange() def get_output_descriptions(self): return ('Thresholded data (vtkImageData)',) def get_output(self, idx): return self._imageThreshold.GetOutput() def logic_to_config(self): self._config.lowerThreshold = self._imageThreshold.GetLowerThreshold() self._config.upperThreshold = self._imageThreshold.GetUpperThreshold() self._config.replaceIn = self._imageThreshold.GetReplaceIn() self._config.inValue = self._imageThreshold.GetInValue() self._config.replaceOut = self._imageThreshold.GetReplaceOut() self._config.outValue = self._imageThreshold.GetOutValue() self._config.outputScalarType = self._imageThreshold.GetOutputScalarType() def config_to_logic(self): self._imageThreshold.ThresholdBetween(self._config.lowerThreshold, self._config.upperThreshold) # SetInValue HAS to be called before SetReplaceIn(), as SetInValue() # always toggles SetReplaceIn() to ON self._imageThreshold.SetInValue(self._config.inValue) self._imageThreshold.SetReplaceIn(self._config.replaceIn) # SetOutValue HAS to be called before SetReplaceOut(), same reason # as above self._imageThreshold.SetOutValue(self._config.outValue) self._imageThreshold.SetReplaceOut(self._config.replaceOut) self._imageThreshold.SetOutputScalarType(self._config.outputScalarType) def view_to_config(self): self._config.lowerThreshold = self._sanitiseThresholdTexts(0) self._config.upperThreshold = self._sanitiseThresholdTexts(1) self._config.replaceIn = self._view_frame.replaceInCheckBox.GetValue() self._config.inValue = float(self._view_frame.replaceInText.GetValue()) self._config.replaceOut = self._view_frame.replaceOutCheckBox.GetValue() self._config.outValue = float(self._view_frame.replaceOutText.GetValue()) ocString = self._view_frame.outputDataTypeChoice.GetStringSelection() if len(ocString) == 0: self._module_manager.log_error( "Impossible error with outputType choice in " "doubleThresholdFLT.py. Picking sane default.") # set to last string in list, should be default ocString = self._outputTypes.keys()[-1] try: symbolicOutputType = self._outputTypes[ocString] except KeyError: self._module_manager.log_error( "Impossible error with ocString in " "doubleThresholdFLT.py. Picking sane default.") # set to last string in list, should be default symbolicOutputType = self._outputTypes.values()[-1] if symbolicOutputType == -1: self._config.outputScalarType = -1 else: try: self._config.outputScalarType = getattr(vtk, symbolicOutputType) except AttributeError: self._module_manager.log_error( "Impossible error with symbolicOutputType " "in doubleThresholdFLT.py. Picking sane " "default.") self._config.outputScalarType = -1 def config_to_view(self): self._view_frame.lowerThresholdText.SetValue("%.2f" % (self._config.lowerThreshold)) self._view_frame.upperThresholdText.SetValue("%.2f" % (self._config.upperThreshold)) self._view_frame.replaceInCheckBox.SetValue(self._config.replaceIn) self._view_frame.replaceInText.SetValue(str(self._config.inValue)) self._view_frame.replaceOutCheckBox.SetValue(self._config.replaceOut) self._view_frame.replaceOutText.SetValue(str(self._config.outValue)) for key in self._outputTypes.keys(): symbolicOutputType = self._outputTypes[key] if hasattr(vtk, str(symbolicOutputType)): numericOutputType = getattr(vtk, symbolicOutputType) else: numericOutputType = -1 if self._config.outputScalarType == numericOutputType: break self._view_frame.outputDataTypeChoice.SetStringSelection(key) def execute_module(self): self._imageThreshold.Update() def streaming_execute_module(self): self._imageThreshold.Update() def view(self, parent_window=None): if self._view_frame is None: self._createViewFrame() self.sync_module_view_with_logic() # if the window was visible already. just raise it self._view_frame.Show(True) self._view_frame.Raise() def _createViewFrame(self): # import the viewFrame (created with wxGlade) import modules.filters.resources.python.doubleThresholdFLTFrame reload(modules.filters.resources.python.doubleThresholdFLTFrame) self._view_frame = module_utils.instantiate_module_view_frame( self, self._module_manager, modules.filters.resources.python.doubleThresholdFLTFrame.\ doubleThresholdFLTFrame) objectDict = {'imageThreshold' : self._imageThreshold, 'module (self)' : self} module_utils.create_standard_object_introspection( self, self._view_frame, self._view_frame.viewFramePanel, objectDict, None) module_utils.create_eoca_buttons(self, self._view_frame, self._view_frame.viewFramePanel) # finish setting up the output datatype choice self._view_frame.outputDataTypeChoice.Clear() for aType in self._outputTypes.keys(): self._view_frame.outputDataTypeChoice.Append(aType) def _sanitiseThresholdTexts(self, whichText): if whichText == 0: try: lower = float(self._view_frame.lowerThresholdText.GetValue()) except ValueError: # this means that the user did something stupid, so we # restore the value to what's in our config self._view_frame.lowerThresholdText.SetValue(str( self._config.lowerThreshold)) return self._config.lowerThreshold # lower is the new value... upper = float(self._view_frame.upperThresholdText.GetValue()) if lower > upper: lower = upper self._view_frame.lowerThresholdText.SetValue(str(lower)) return lower else: try: upper = float(self._view_frame.upperThresholdText.GetValue()) except ValueError: # this means that the user did something stupid, so we # restore the value to what's in our config self._view_frame.upperThresholdText.SetValue(str( self._config.upperThreshold)) return self._config.upperThreshold # upper is the new value lower = float(self._view_frame.lowerThresholdText.GetValue()) if upper < lower: upper = lower self._view_frame.upperThresholdText.SetValue(str(upper)) return upper
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import input_array_choice_mixin # need this for constants reload(input_array_choice_mixin) from input_array_choice_mixin import InputArrayChoiceMixin class warpPoints(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase): _defaultVectorsSelectionString = 'Default Active Vectors' _userDefinedString = 'User Defined' def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) InputArrayChoiceMixin.__init__(self) self._config.scaleFactor = 1 configList = [ ('Scale factor:', 'scaleFactor', 'base:float', 'text', 'The warping will be scaled by this factor'), ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice', 'The attribute that will be used as vectors for the warping.', (self._defaultVectorsSelectionString, self._userDefinedString))] self._warpVector = vtk.vtkWarpVector() ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkWarpVector' : self._warpVector}) module_utils.setup_vtk_object_progress(self, self._warpVector, 'Warping points.') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._warpVector def execute_module(self): self._warpVector.Update() if self.view_initialised: # second element in configuration list choice = self._getWidget(1) self.iac_execute_module(self._warpVector, choice, 0) def get_input_descriptions(self): return ('VTK points/polydata with vector attribute',) def set_input(self, idx, inputStream): if inputStream is None: self._warpVector.SetInputConnection(0, None) else: self._warpVector.SetInput(inputStream) def get_output_descriptions(self): return ('Warped data',) def get_output(self, idx): # we only return something if we have something if self._warpVector.GetNumberOfInputConnections(0): return self._warpVector.GetOutput() else: return None def logic_to_config(self): self._config.scaleFactor = self._warpVector.GetScaleFactor() # this will extract the possible choices self.iac_logic_to_config(self._warpVector, 0) def config_to_view(self): # first get our parent mixin to do its thing ScriptedConfigModuleMixin.config_to_view(self) # the vector choice is the second configTuple choice = self._getWidget(1) self.iac_config_to_view(choice) def config_to_logic(self): self._warpVector.SetScaleFactor(self._config.scaleFactor) self.iac_config_to_logic(self._warpVector, 0)
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class ICPTransform(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # this has no progress feedback self._icp = vtk.vtkIterativeClosestPointTransform() self._config.max_iterations = 50 self._config.mode = 'RigidBody' self._config.align_centroids = True config_list = [ ('Transformation mode:', 'mode', 'base:str', 'choice', 'Rigid: rotation + translation;\n' 'Similarity: rigid + isotropic scaling\n' 'Affine: rigid + scaling + shear', ('RigidBody', 'Similarity', 'Affine')), ('Maximum number of iterations:', 'max_iterations', 'base:int', 'text', 'Maximum number of iterations for ICP.'), ('Align centroids before start', 'align_centroids', 'base:bool', 'checkbox', 'Align centroids before iteratively optimizing closest points? (required for large relative translations)') ] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkIterativeClosestPointTransform' : self._icp}) self.sync_module_logic_with_config() def close(self): ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._icp ModuleBase.close(self) def get_input_descriptions(self): return ('source vtkPolyData', 'target vtkPolyData') def set_input(self, idx, input_stream): if idx == 0: self._icp.SetSource(input_stream) else: self._icp.SetTarget(input_stream) def get_output_descriptions(self): return ('Linear transform',) def get_output(self, idx): return self._icp def logic_to_config(self): self._config.mode = \ self._icp.GetLandmarkTransform().GetModeAsString() self._config.max_iterations = \ self._icp.GetMaximumNumberOfIterations() self._config.align_centroids = self._icp.GetStartByMatchingCentroids() def config_to_logic(self): lmt = self._icp.GetLandmarkTransform() if self._config.mode == 'RigidBody': lmt.SetModeToRigidBody() elif self._config.mode == 'Similarity': lmt.SetModeToSimilarity() else: lmt.SetModeToAffine() self._icp.SetMaximumNumberOfIterations( self._config.max_iterations) self._icp.SetStartByMatchingCentroids(self._config.align_centroids) def execute_module(self): self._module_manager.set_progress( 10, 'Starting ICP.') self._icp.Update() self._module_manager.set_progress( 100, 'ICP complete.')
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class contour(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._contourFilter = vtk.vtkContourFilter() module_utils.setup_vtk_object_progress(self, self._contourFilter, 'Extracting iso-surface') # now setup some defaults before our sync self._config.iso_value = 128 config_list = [ ('ISO value:', 'iso_value', 'base:float', 'text', 'Surface will pass through points with this value.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkContourFilter' : self._contourFilter}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._contourFilter def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._contourFilter.SetInput(inputStream) def get_output_descriptions(self): return (self._contourFilter.GetOutput().GetClassName(),) def get_output(self, idx): return self._contourFilter.GetOutput() def logic_to_config(self): self._config.iso_value = self._contourFilter.GetValue(0) def config_to_logic(self): self._contourFilter.SetValue(0, self._config.iso_value) def execute_module(self): self._contourFilter.Update() def streaming_execute_module(self): self._contourFilter.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class appendPolyData(NoConfigModuleMixin, ModuleBase): _numInputs = 5 def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # underlying VTK thingy self._appendPolyData = vtk.vtkAppendPolyData() # our own list of inputs self._inputStreams = self._numInputs * [None] module_utils.setup_vtk_object_progress(self, self._appendPolyData, 'Appending PolyData') NoConfigModuleMixin.__init__( self, {'vtkAppendPolyData' : self._appendPolyData}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._appendPolyData def get_input_descriptions(self): return self._numInputs * ('vtkPolyData',) def set_input(self, idx, inputStream): # only do something if we don't have this already if self._inputStreams[idx] != inputStream: if inputStream: # add it self._appendPolyData.AddInput(inputStream) else: # or remove it self._appendPolyData.RemoveInput(inputStream) # whatever the case, record it self._inputStreams[idx] = inputStream def get_output_descriptions(self): return (self._appendPolyData.GetOutput().GetClassName(), ) def get_output(self, idx): return self._appendPolyData.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._appendPolyData.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class imageGreyDilate(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() module_utils.setup_vtk_object_progress(self, self._imageDilate, 'Performing greyscale 3D dilation') self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageContinuousDilate3D' : self._imageDilate}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageDilate def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return (self._imageDilate.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageDilate.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageDilate.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageDilate.Update() def streaming_execute_module(self): self._imageDilate.Update()
Python
# TODO: simplify module!! all this muck was necessary due to the old # demand-driven model. Keep the code around, it could be used as # illustrative case. import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk import vtkdevide class modifyHomotopy(NoConfigModuleMixin, ModuleBase): """IMPORTANT: this module needs to be updated to the new event-driven execution scheme. It should still work, but it may also blow up your computer. Modifies homotopy of input image I so that the only minima will be at the user-specified seed-points or marker image, all other minima will be suppressed and ridge lines separating minima will be preserved. Either the seed-points or the marker image (or both) can be used. The marker image has to be >1 at the minima that are to be enforced and 0 otherwise. This module is often used as a pre-processing step to ensure that the watershed doesn't over-segment. This module uses a DeVIDE-specific implementation of Luc Vincent's fast greyscale reconstruction algorithm, extended for 3D. """ 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 close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # self._imageThreshold.RemoveObserver(self._imageThresholdObserverID) # get rid of our reference del self._dualGreyReconstruct del self._markerSource del self._maskSource del self._imageThreshold def get_input_descriptions(self): return ('VTK Image Data', 'Minima points', 'Minima image') def set_input(self, idx, inputStream): if idx == 0: if inputStream != self._inputImage: # if we have a different image input, the seeds will have to # be rebuilt! self._markerSource.Modified() # and obviously the masksource has to know that its "input" # has changed self._maskSource.Modified() self._dualGreyReconstruct.Modified() if inputStream: # we have to add an observer s = inputStream.GetSource() if s: self._inputImageObserverID = s.AddObserver( 'EndEvent', self._observerInputImage) else: # if we had an observer, remove it if self._inputImage: s = self._inputImage.GetSource() if s and self._inputImageObserverID: s.RemoveObserver( self._inputImageObserverID) self._inputImageObserverID = None # finally store the new data self._inputImage = inputStream elif idx == 1: if inputStream != self._inputPoints: # check that the inputStream is either None (meaning # disconnect) or a valid type try: if inputStream != None and \ inputStream.devideType != 'namedPoints': raise TypeError except (AttributeError, TypeError): raise TypeError, 'This input requires a points-type' if self._inputPoints: self._inputPoints.removeObserver( self._observerInputPoints) self._inputPoints = inputStream if self._inputPoints: self._inputPoints.addObserver(self._observerInputPoints) # the input points situation has changed, make sure # the marker source knows this... self._markerSource.Modified() # as well as the mask source of course self._maskSource.Modified() self._dualGreyReconstruct.Modified() else: if inputStream != self._imageThreshold.GetInput(): self._imageThreshold.SetInput(inputStream) # we have a different inputMarkerImage... have to recalc self._markerSource.Modified() self._maskSource.Modified() self._dualGreyReconstruct.Modified() def get_output_descriptions(self): return ('Modified VTK Image Data', 'I input', 'J input') def get_output(self, idx): if idx == 0: return self._dualGreyReconstruct.GetOutput() elif idx == 1: return self._maskSource.GetStructuredPointsOutput() else: return self._markerSource.GetStructuredPointsOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._dualGreyReconstruct.Update() def _markerSourceExecute(self): imageI = self._inputImage if imageI: imageI.Update() # setup and allocate J output outputJ = self._markerSource.GetStructuredPointsOutput() # _dualGreyReconstruct wants inputs the same with regards to # dimensions, origin and type, so this is okay. outputJ.CopyStructure(imageI) outputJ.AllocateScalars() # we need this to build up J minI, maxI = imageI.GetScalarRange() mi = self._imageThreshold.GetInput() if mi: if mi.GetOrigin() == outputJ.GetOrigin() and \ mi.GetExtent() == outputJ.GetExtent(): self._imageThreshold.SetInValue(minI) self._imageThreshold.SetOutValue(maxI) self._imageThreshold.SetOutputScalarType(imageI.GetScalarType()) self._imageThreshold.GetOutput().SetUpdateExtentToWholeExtent() self._imageThreshold.Update() outputJ.DeepCopy(self._imageThreshold.GetOutput()) else: vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: marker input should be same dimensions as image input!') # we can continue as if we only had seeds scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) else: # initialise all scalars to maxI scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) # now go through all seed points and set those positions in # the scalars to minI if self._inputPoints: for ip in self._inputPoints: x,y,z = ip['discrete'] outputJ.SetScalarComponentFromDouble(x, y, z, 0, minI) def _maskSourceExecute(self): inputI = self._inputImage if inputI: inputI.Update() self._markerSource.Update() outputJ = self._markerSource.GetStructuredPointsOutput() # we now have an outputJ if not inputI.GetScalarPointer() or \ not outputJ.GetScalarPointer() or \ not inputI.GetDimensions() > (0,0,0): vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: Input is empty.') return iMath = vtk.vtkImageMathematics() iMath.SetOperationToMin() iMath.SetInput1(outputJ) iMath.SetInput2(inputI) iMath.GetOutput().SetUpdateExtentToWholeExtent() iMath.Update() outputI = self._maskSource.GetStructuredPointsOutput() outputI.DeepCopy(iMath.GetOutput()) def _observerInputPoints(self, obj): # this will be called if anything happens to the points # simply make sure our markerSource knows that it's now invalid self._markerSource.Modified() self._maskSource.Modified() self._dualGreyReconstruct.Modified() def _observerInputImage(self, obj, eventName): # the inputImage has changed, so the marker will have to change too self._markerSource.Modified() # logical, input image has changed self._maskSource.Modified() self._dualGreyReconstruct.Modified() def _observerImageThreshold(self, obj, eventName): # if anything in the threshold has changed, (e.g. the input) we # have to invalidate everything else after it self._markerSource.Modified() self._maskSource.Modified() self._dualGreyReconstruct.Modified()
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class ShephardMethod(ScriptedConfigModuleMixin, ModuleBase): """Apply Shepard Method to input. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._shepardFilter = vtk.vtkShepardMethod() module_utils.setup_vtk_object_progress(self, self._shepardFilter, 'Applying Shepard Method.') self._config.maximum_distance = 1.0 configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageContinuousDilate3D' : self._imageDilate}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageDilate def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return (self._imageDilate.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageDilate.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageDilate.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageDilate.Update()
Python
# decimateFLT.py copyright (c) 2003 by Charl P. Botha http://cpbotha.net/ # $Id$ # module that triangulates and decimates polygonal input import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class decimate(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # the decimator only works on triangle data, so we make sure # that it only gets triangle data self._triFilter = vtk.vtkTriangleFilter() self._decimate = vtk.vtkDecimatePro() self._decimate.PreserveTopologyOn() self._decimate.SetInput(self._triFilter.GetOutput()) module_utils.setup_vtk_object_progress(self, self._triFilter, 'Converting to triangles') module_utils.setup_vtk_object_progress(self, self._decimate, 'Decimating mesh') # now setup some defaults before our sync self._config.target_reduction = self._decimate.GetTargetReduction() \ * 100.0 config_list = [ ('Target reduction (%):', 'target_reduction', 'base:float', 'text', 'Decimate algorithm will attempt to reduce by this much.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkDecimatePro' : self._decimate, 'vtkTriangleFilter' : self._triFilter}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._decimate del self._triFilter def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._triFilter.SetInput(inputStream) def get_output_descriptions(self): return (self._decimate.GetOutput().GetClassName(),) def get_output(self, idx): return self._decimate.GetOutput() def logic_to_config(self): self._config.target_reduction = self._decimate.GetTargetReduction() \ * 100.0 def config_to_logic(self): self._decimate.SetTargetReduction( self._config.target_reduction / 100.0) def execute_module(self): # get the filter doing its thing self._triFilter.Update() self._decimate.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class polyDataNormals(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._pdNormals = vtk.vtkPolyDataNormals() module_utils.setup_vtk_object_progress(self, self._pdNormals, 'Calculating normals') NoConfigModuleMixin.__init__( self, {'vtkPolyDataNormals' : self._pdNormals}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._pdNormals def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._pdNormals.SetInput(inputStream) def get_output_descriptions(self): return (self._pdNormals.GetOutput().GetClassName(), ) def get_output(self, idx): return self._pdNormals.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._pdNormals.Update() def streaming_execute_module(self): self._pdNormals.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import wx import vtk class imageFlip(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageFlip = vtk.vtkImageFlip() self._imageFlip.SetFilteredAxis(2) self._imageFlip.GetOutput().SetUpdateExtentToWholeExtent() module_utils.setup_vtk_object_progress(self, self._imageFlip, 'Flipping image') NoConfigModuleMixin.__init__( self, {'vtkImageFlip' : self._imageFlip}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageFlip def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageFlip.SetInput(inputStream) def get_output_descriptions(self): return (self._imageFlip.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageFlip.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageFlip.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class imageGreyErode(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageErode = vtk.vtkImageContinuousErode3D() module_utils.setup_vtk_object_progress(self, self._imageErode, 'Performing greyscale 3D erosion') self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageContinuousErode3D' : self._imageErode}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageErode def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageErode.SetInput(inputStream) def get_output_descriptions(self): return (self._imageErode.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageErode.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageErode.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageErode.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageErode.Update() def streaming_execute_module(self): self._imageErode.Update()
Python
from module_base import ModuleBase from module_mixins import vtkPipelineConfigModuleMixin import module_utils import vtk class contourFLTBase(ModuleBase, vtkPipelineConfigModuleMixin): def __init__(self, module_manager, contourFilterText): # call parent constructor ModuleBase.__init__(self, module_manager) self._contourFilterText = contourFilterText if contourFilterText == 'marchingCubes': self._contourFilter = vtk.vtkMarchingCubes() else: # contourFilter == 'contourFilter' self._contourFilter = vtk.vtkContourFilter() module_utils.setup_vtk_object_progress(self, self._contourFilter, 'Extracting iso-surface') # now setup some defaults before our sync self._config.isoValue = 128; self._viewFrame = None self._createViewFrame() # transfer these defaults to the logic self.config_to_logic() # then make sure they come all the way back up via self._config self.logic_to_config() self.config_to_view() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) # don't forget to call the close() method of the vtkPipeline mixin vtkPipelineConfigModuleMixin.close(self) # take out our view interface self._viewFrame.Destroy() # get rid of our reference del self._contourFilter def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._contourFilter.SetInput(inputStream) def get_output_descriptions(self): return (self._contourFilter.GetOutput().GetClassName(),) def get_output(self, idx): return self._contourFilter.GetOutput() def logic_to_config(self): self._config.isoValue = self._contourFilter.GetValue(0) def config_to_logic(self): self._contourFilter.SetValue(0, self._config.isoValue) def view_to_config(self): try: self._config.isoValue = float( self._viewFrame.isoValueText.GetValue()) except: pass def config_to_view(self): self._viewFrame.isoValueText.SetValue(str(self._config.isoValue)) def execute_module(self): self._contourFilter.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise() def _createViewFrame(self): # import the viewFrame (created with wxGlade) import modules.Filters.resources.python.contourFLTBaseViewFrame reload(modules.Filters.resources.python.contourFLTBaseViewFrame) self._viewFrame = module_utils.instantiate_module_view_frame( self, self._module_manager, modules.Filters.resources.python.contourFLTBaseViewFrame.\ contourFLTBaseViewFrame) objectDict = {'contourFilter' : self._contourFilter} module_utils.create_standard_object_introspection( self, self._viewFrame, self._viewFrame.viewFramePanel, objectDict, None) module_utils.create_eoca_buttons( self, self._viewFrame, self._viewFrame.viewFramePanel)
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk OPS = ['add', 'subtract', 'multiply', 'divide', 'invert', 'sin', 'cos', 'exp', 'log', 'abs', 'sqr', 'sqrt', 'min', 'max', 'atan', 'atan2', 'multiply by k', 'add c', 'conjugate', 'complex multiply', 'replace c by k'] OPS_DICT = {} for i,o in enumerate(OPS): OPS_DICT[o] = i class imageMathematics(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageMath = vtk.vtkImageMathematics() self._imageMath.SetInput1(None) self._imageMath.SetInput2(None) module_utils.setup_vtk_object_progress(self, self._imageMath, 'Performing image math') self._config.operation = 'subtract' self._config.constantC = 0.0 self._config.constantK = 1.0 configList = [ ('Operation:', 'operation', 'base:str', 'choice', 'The operation that should be performed.', tuple(OPS_DICT.keys())), ('Constant C:', 'constantC', 'base:float', 'text', 'The constant C used in some operations.'), ('Constant K:', 'constantK', 'base:float', 'text', 'The constant C used in some operations.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageMathematics' : self._imageMath}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageMath def get_input_descriptions(self): return ('VTK Image Data 1', 'VTK Image Data 2') def set_input(self, idx, inputStream): if idx == 0: self._imageMath.SetInput1(inputStream) else: self._imageMath.SetInput2(inputStream) def get_output_descriptions(self): return ('VTK Image Data Result',) def get_output(self, idx): return self._imageMath.GetOutput() def logic_to_config(self): o = self._imageMath.GetOperation() # search for o in _operations for name,idx in OPS_DICT.items(): if idx == o: break if idx == o: self._config.operation = name else: # default is subtract self._config.operation = 'Subtract' self._config.constantC = self._imageMath.GetConstantC() self._config.constantK = self._imageMath.GetConstantK() def config_to_logic(self): idx = OPS_DICT[self._config.operation] self._imageMath.SetOperation(idx) self._imageMath.SetConstantC(self._config.constantC) self._imageMath.SetConstantK(self._config.constantK) def execute_module(self): self._imageMath.Update() def streaming_execute_module(self): self._imageMath.Update()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class transformImageToTarget(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._reslicer = vtk.vtkImageReslice() self._probefilter = vtk.vtkProbeFilter() #This is retarded - we (sometimes, see below) need the padder #to get the image extent big enough to satisfy the probe filter. #No apparent logical reason, but it throws an exception if we don't. self._padder = vtk.vtkImageConstantPad() # initialise any mixins we might have NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageReslice' : self._reslicer}) module_utils.setup_vtk_object_progress(self, self._reslicer, 'Transforming image (Image Reslice)') module_utils.setup_vtk_object_progress(self, self._probefilter, 'Performing remapping (Probe Filter)') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # Rdisconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._reslicer del self._probefilter del self._padder def get_input_descriptions(self): return ('Source VTK Image Data', 'VTK Transform', 'Target VTK Image (supplies extent and spacing)') def set_input(self, idx, inputStream): if idx == 0: self._imagedata = inputStream self._reslicer.SetInput(self._imagedata) elif idx == 1: if inputStream == None: # disconnect self._transform = vtk.vtkMatrix4x4() else: # resliceTransform transforms the resampling grid, which # is equivalent to transforming the volume with its inverse self._transform = inputStream.GetMatrix() self._transform.Invert() #This is required else: if inputStream != None: self._outputVolumeExample = inputStream else: # define output extent same as input self._outputVolumeExample = self._imagedata def _convert_input(self): self._reslicer.SetInput(self._imagedata) self._reslicer.SetResliceAxes(self._transform) self._reslicer.SetAutoCropOutput(1) self._reslicer.SetInterpolationModeToCubic() spacing_i = self._imagedata.GetSpacing() isotropic_sp = min(min(spacing_i[0],spacing_i[1]),spacing_i[2]) self._reslicer.SetOutputSpacing(isotropic_sp, isotropic_sp, isotropic_sp) self._reslicer.Update() source = self._reslicer.GetOutput() source_extent = source.GetExtent() output_extent = self._outputVolumeExample.GetExtent() if (output_extent[0] < source_extent[0]) or (output_extent[2] < source_extent[2]) or (output_extent[4] < source_extent[4]): raise Exception('Output extent starts at lower index than source extent. Assumed that both should be zero?') elif (output_extent[1] > source_extent[1]) or (output_extent[3] > source_extent[3]) or (output_extent[5] > source_extent[5]): extX = max(output_extent[1], source_extent[1]) extY = max(output_extent[3], source_extent[3]) extZ = max(output_extent[5], source_extent[5]) padX = extX - source_extent[1] padY = extY - source_extent[3] padZ = extZ - source_extent[5] print 'Zero-padding source by (%d, %d, %d) voxels to force extent to match/exceed input''s extent. Lame, eh?' % (padX, padY, padZ) self._padder.SetInput(source) self._padder.SetConstant(0.0) self._padder.SetOutputWholeExtent(source_extent[0],extX,source_extent[2],extY,source_extent[4],extZ) self._padder.Update() source = self._padder.GetOutput() #dataType = self._outputVolumeExample.GetScalarType() #if dataType == 2 | dataType == 4: output = vtk.vtkImageData() output.DeepCopy(self._outputVolumeExample) self._probefilter.SetInput(output) self._probefilter.SetSource(source) self._probefilter.Update() self._output = self._probefilter.GetOutput() def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._output def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._convert_input()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import wx import vtk class imageGradientMagnitude(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageGradientMagnitude = vtk.vtkImageGradientMagnitude() self._imageGradientMagnitude.SetDimensionality(3) module_utils.setup_vtk_object_progress(self, self._imageGradientMagnitude, 'Calculating gradient magnitude') NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageGradientMagnitude' : self._imageGradientMagnitude}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageGradientMagnitude def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageGradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return (self._imageGradientMagnitude.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageGradientMagnitude.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageGradientMagnitude.Update()
Python