code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# 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_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 |
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 |
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 |
# $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 |
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: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $
class MyGaussian:
kits = ['vtk_kit']
cats = ['User','Optic Flow']
keywords = ['gaussian', 'source']
| 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 |
# dummy __init__ so that this dir will be seen as package. | Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class superQuadric(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
# setup config
self._config.toroidal = True
self._config.thickness = 0.3333
self._config.phiRoundness = 0.2
self._config.thetaRoundness = 0.8
self._config.size = 0.5
self._config.center = (0,0,0)
self._config.scale = (1,1,1)
self._config.thetaResolution = 64
self._config.phiResolution = 64
# and then our scripted config
configList = [
('Toroidal: ', 'toroidal', 'base:bool', 'checkbox',
'Should the quadric be toroidal.'),
('Thickness: ', 'thickness', 'base:float', 'text',
'Thickness of the toroid, scaled between 0 and 1'),
('Phi Roundness: ', 'phiRoundness', 'base:float', 'text',
'Controls shape of superquadric'),
('Theta Roundness: ', 'thetaRoundness', 'base:float', 'text',
'Controls shape of superquadric'),
('Size: ', 'size', 'base:float', 'text',
'The size of the superquadric.'),
('Centre: ', 'center', 'tuple:float,3', 'text',
'The translation transform of the resultant superquadric.'),
('Scale: ', 'scale', 'tuple:float,3', 'text',
'The scale transformof the resultant superquadric.'),
('Theta resolution: ', 'thetaResolution', 'base:int', 'text',
'The resolution of the output polydata'),
('Phi resolution: ', 'phiResolution', 'base:int', 'text',
'The resolution of the output polydata')]
# now create the necessary VTK modules
self._superquadric = vtk.vtkSuperquadric()
self._superquadricSource = vtk.vtkSuperquadricSource()
# we need these temporary outputs
self._outputs = [self._superquadric, vtk.vtkPolyData()]
# setup progress for the processObject
module_utils.setup_vtk_object_progress(self, self._superquadricSource,
"Synthesizing polydata.")
# mixin ctor
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkSuperquadric' : self._superquadric,
'vtkSuperquadricSource' : self._superquadricSource})
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._superquadricSource
del self._superquadric
def execute_module(self):
# when we're executed, outputs become active
self._superquadricSource.Update()
# self._outputs[0] (the superquadric implicit) is always ready
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('Implicit function',
'Polydata')
def get_output(self, idx):
#return self._outputs[idx]
if idx == 0:
return self._superquadric
else:
return self._superquadricSource.GetOutput()
def config_to_logic(self):
# sanity check
if self._config.thickness < 0.0:
self._config.thickness = 0.0
elif self._config.thickness > 1.0:
self._config.thickness = 1.0
for obj in (self._superquadric, self._superquadricSource):
obj.SetToroidal(self._config.toroidal)
obj.SetThickness(self._config.thickness)
obj.SetPhiRoundness(self._config.phiRoundness)
obj.SetThetaRoundness(self._config.thetaRoundness)
obj.SetSize(self._config.size)
obj.SetCenter(self._config.center)
obj.SetScale(self._config.scale)
# only applicable to the source
self._superquadricSource.SetThetaResolution(
self._config.thetaResolution)
self._superquadricSource.SetPhiResolution(
self._config.phiResolution)
def logic_to_config(self):
s = self._superquadric
self._config.toroidal = s.GetToroidal()
self._config.thickness = s.GetThickness()
self._config.phiRoundness = s.GetPhiRoundness()
self._config.thetaRoundness = s.GetThetaRoundness()
self._config.size = s.GetSize()
self._config.center = s.GetCenter()
self._config.scale = s.GetScale()
ss = self._superquadricSource
self._config.thetaResolution = ss.GetThetaResolution()
self._config.phiResolution = ss.GetPhiResolution()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class implicitToVolume(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
# setup config
self._config.sampleDimensions = (64, 64, 64)
self._config.modelBounds = (-1, 1, -1, 1, -1, 1)
# we init normals to off, they EAT memory (3 elements per point!)
self._config.computeNormals = False
# and then our scripted config
configList = [
('Sample dimensions: ', 'sampleDimensions', 'tuple:int,3',
'text', 'The dimensions of the output volume.'),
('Model bounds: ', 'modelBounds', 'tuple:float,6', 'text',
'Region in world space over which the sampling is performed.'),
('Compute normals: ', 'computeNormals', 'base:bool', 'checkbox',
'Must normals also be calculated and stored.')]
# now create the necessary VTK modules
self._sampleFunction = vtk.vtkSampleFunction()
# this is more than good enough.
self._sampleFunction.SetOutputScalarTypeToFloat()
# setup progress for the processObject
module_utils.setup_vtk_object_progress(self, self._sampleFunction,
"Sampling implicit function.")
self._example_input = None
# mixin ctor
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkSampleFunction' : self._sampleFunction})
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._sampleFunction
del self._example_input
def execute_module(self):
# if we have an example input volume, copy its bounds and resolution
i1 = self._example_input
try:
self._sampleFunction.SetModelBounds(i1.GetBounds())
self._sampleFunction.SetSampleDimensions(i1.GetDimensions())
except AttributeError:
# if we couldn't get example_input metadata, just use our config
self.config_to_logic()
self._sampleFunction.Update()
def get_input_descriptions(self):
return ('Implicit Function', 'Example vtkImageData')
def set_input(self, idx, inputStream):
if idx == 0:
self._sampleFunction.SetImplicitFunction(inputStream)
else:
self._example_input = inputStream
def get_output_descriptions(self):
return ('VTK Image Data (volume)',)
def get_output(self, idx):
return self._sampleFunction.GetOutput()
def config_to_logic(self):
self._sampleFunction.SetSampleDimensions(self._config.sampleDimensions)
self._sampleFunction.SetModelBounds(self._config.modelBounds)
self._sampleFunction.SetComputeNormals(self._config.computeNormals)
def logic_to_config(self):
s = self._sampleFunction
self._config.sampleDimensions = s.GetSampleDimensions()
self._config.modelBounds = s.GetModelBounds()
self._config.computeNormals = s.GetComputeNormals()
| Python |
#
#
#
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import operator
import vtk
import wx
class advectionProperties(ScriptedConfigModuleMixin, ModuleBase):
_numberOfInputs = 16
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._config.csvFilename = ''
configList = [
('CSV Filename:', 'csvFilename', 'base:str', 'filebrowser',
'Filename Comma-Separated-Values file that will be written.',
{'fileMode' : wx.SAVE,
'fileMask' : 'CSV files (*.csv)|*.csv|All files (*.*)|*.*'})]
self._inputs = [None] * self._numberOfInputs
#module_utils.setup_vtk_object_progress(self, self._warpVector,
# 'Warping points.')
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)
# get rid of any references
def execute_module(self):
# inputs are arranged according to timesteps (presumably)
# things have been marked with a VolumeIndex array
# find valid inputs with VolumeIndex scalars
newInputs = [i for i in self._inputs if i != None]
# we need at the very least three inputs:
# the VolumeIndex input and the actual volumes that will be used
if len(newInputs) < 3:
raise Exception, 'This module requires a minimum of 3 inputs.'
# make sure everything is up to date
[i.Update() for i in newInputs]
# the first input MUST have a VolumeIndex attribute
if newInputs[0].GetPointData().GetScalars('VolumeIndex') == None:
raise Exception, 'The first input must have ' \
'a VolumeIndex scalar attribute.'
# now we're going to build up a dictionary to translate
# from volume index to a list of point ids
vis = newInputs[0].GetPointData().GetScalars('VolumeIndex')
volIdxToPtIds = {}
for ptid in xrange(vis.GetNumberOfTuples()):
vidx = vis.GetTuple1(ptid)
if vidx >= 0:
if vidx in volIdxToPtIds:
volIdxToPtIds[vidx].append(ptid)
else:
volIdxToPtIds[vidx] = [ptid]
# 1. calculate centroids
# centroids is a dictionary with volume index as key
# centroids over time as the values
# create dict with keys == volumeIds; values will be lists
# of centroids over time
centroids = {}
for volIdx in volIdxToPtIds:
centroids[volIdx] = []
for volIdx in centroids:
# get all pointIds for this volume
ptIds = volIdxToPtIds[volIdx]
# do all timesteps
for tsi in range(len(newInputs) - 1):
pd = newInputs[tsi + 1]
coordSums = [0,0,0]
for ptId in ptIds:
coordSums = map(operator.add, coordSums,
pd.GetPoint(ptId))
# calc centroid
numPoints = float(len(ptIds))
centroid = map(lambda e: e / numPoints, coordSums)
centroids[volIdx].append(centroid)
# now use the centroids to build table
volids = centroids.keys()
volids.sort()
# centroidVectors of the format:
# step-label, vol0 x, vol0 y, vol0 z, vol0 mag, vol1 x, vol1 y, etc.
centroidVectors = []
# newInputs - 1 for the first input, -1 because we're doing vectors
for tsi in range(len(newInputs) - 2):
# new row
centroidVectors.append(['%d - %d' % (tsi, tsi+1)])
for volIdx in volids:
cvec = map(operator.sub,
centroids[volIdx][tsi+1], centroids[volIdx][tsi])
centroidVectors[-1].extend(cvec)
# also the sum of motion
centroidVectors[-1].append(vtk.vtkMath.Norm(cvec))
# possible python storage:
# [
# [[v0x,v0y,v0z], [v0x,v0y,v0z], ... , [v0x,v0y,v0z]], # timestep0
# [ ] # timestep1
# ]
if self._config.csvFilename:
# write centroid vectors
csvFile = file(self._config.csvFilename, 'w')
labelString = 'step-label'
for volid in volids:
labelString = '%s, vol%d x, vol%d y, vol%d z, vol%d mag' % \
(labelString,volid,volid,volid,volid)
# write label string
csvFile.write('%s\n' % (labelString,))
# secretly open python file too (tee hee)
py_file = file(self._config.csvFilename + '.py', 'w')
py_file.write('# for each volume, all centroids over time\n')
py_file.write('centroids = [\n')
# end of secret bit (till later)
# first we write the centroids (naughty)
for tsi in range(len(newInputs) - 1):
cline = "'%d'" % (tsi,)
for volid in volids:
# get me the centroid for this volid and this step
c = centroids[volid][tsi]
cline = '%s, %.3f, %.3f, %.3f, 0' % \
(cline, c[0], c[1], c[2])
csvFile.write('%s\n' % (cline,))
# secret python bit
for volid in volids:
centroid_over_time = []
for tsi in range(len(newInputs) - 1):
c = centroids[volid][tsi]
centroid_over_time.append('[%.3f, %.3f, %.3f]' % tuple(c))
py_file.write('[%s],\n' % (','.join(centroid_over_time),))
py_file.write('\n]\n')
py_file.close()
# end secret python bit
# then we write the centroid motion vectors
for cvecLine in centroidVectors:
# strip off starting and ending []
csvFile.write('%s\n' % (str(cvecLine)[1:-1],))
def get_input_descriptions(self):
return ('vtkPolyData with VolumeIndex attribute',) * \
self._numberOfInputs
def set_input(self, idx, inputStream):
validInput = False
try:
if inputStream.GetClassName() == 'vtkPolyData':
validInput = True
except:
# we come here if GetClassName() is not callable (or doesn't
# exist) - but things could still be None
if inputStream == None:
validInput = True
if validInput:
self._inputs[idx] = inputStream
else:
raise TypeError, 'This input requires a vtkPolyData.'
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
| Python |
# $Id$
class advectionProperties:
kits = ['vtk_kit']
cats = ['Sources']
help = """Given a series of prepared advection volumes (each input is a
timestep), calculate a number of metrics.
The first input HAS to have a VolumeIndex PointData attribute/array. For
example, the output of the pointsToSpheres that you used BEFORE having
passed through the first probeFilters. This first input will NOT be used
for the actual calculations, but only for point -> volume lookups.
Calculations will be performed for the second input and onwards.
This module writes a CSV file with the volume centroids over time, and
secretly writes a python file with all data as a python nested list.
This can easily be loaded in a Python script for further analysis.
"""
class cptDistanceField:
kits = ['vtk_kit']
cats = ['Sources']
help = """Driver module for Mauch's CPT code.
This takes an image data and a mesh input. The imagedata is only used
to determine the bounds of the output distance field. The mesh
is converted to the CPT brep format using the DeVIDE cptBrepWRT module.
A geom file is created. The CPT driver is executed with the geom and
brep files. The output distance field is read, y-axis is flipped, and
the whole shebang is made available at the output.
Contributions to module code by Stef Busking.
Suggestion: On Windows, your driver.bat could make use of plink /
pscp to copy data to a linux server and run Mauch's code there,
and then copy everything back. On Linux you can run Mauch's code
directly.
"""
class implicitToVolume:
kits = ['vtk_kit']
cats = ['Sources']
help = """Given an implicit function, this module will evaluate it over
a volume and yield that volume as output.
"""
class manualTransform:
kits = ['vtk_kit']
cats = ['Sources']
help = """Manually create linear transform by entering scale factors,
rotation angles and translations.
Scaling is performed, then rotation, then translation. It is often easier
to chain manualTransform modules than performing all transformations at
once.
"""
class MarschnerLobb:
kits = ['vtk_kit']
cats = ['Sources']
help = """Pure Python filter to generate Marschner-Lobb test
volume.
When resolution is left at the default value of 40, the generated
volume should be at the Nyquist frequency of the signal (analytic
function) that it has sampled.
Pure Python implementation: for the default resolution, takes a
second or two, 200 cubed takes about 20 seconds on Core2 hardware.
"""
class PassThrough:
kits = []
cats = ['Filters', 'System']
help = """Simple pass-through filter.
This is quite useful if you have a source that connects to a
number of consumers, and you want to be able to change sources
easily. Connect the source to the PassThrough, and the
PassThrough output to all the consumers. Now when you replace the
source, you only have to reconnect one module.
"""
class pointsToSpheres:
kits = ['vtk_kit']
cats = ['Sources']
help = """Given a set of selected points (for instance from a slice3dVWR),
generate polydata spheres centred at these points with user-specified
radius. The spheres' interiors are filled with smaller spheres. This is
useful when using selected points to generate points for seeding
streamlines or calculating advection by a vector field.
Each point's sphere has an array associated to its pointdata called
'VolumeIndex'. All values in this array are equal to the corresponding
point's index in the input points list.
"""
class superQuadric:
kits = ['vtk_kit']
cats = ['Sources']
help = """Generates a SuperQuadric implicit function and polydata as
outputs.
"""
| 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 math
class MarschnerLobb(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
# setup config
self._config.resolution = 40
# and then our scripted config
configList = [
('Resolution: ', 'resolution', 'base:int', 'text',
'x, y and z resolution of sampled volume. '
'According to the article, should be 40 to be '
'at Nyquist.')]
# now create the necessary VTK modules
self._es = vtk.vtkImageEllipsoidSource()
self._es.SetOutputScalarTypeToFloat()
self._ic = vtk.vtkImageChangeInformation()
self._ic.SetInputConnection(self._es.GetOutputPort())
self._output = vtk.vtkImageData()
# mixin ctor
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._es
del self._ic
def execute_module(self):
e = self._config.resolution
self._es.SetWholeExtent(0,e-1,0,e-1,0,e-1)
spc = 2.0 / (e - 1)
self._ic.SetOutputSpacing(spc, spc, spc)
self._ic.SetOutputOrigin(-1.0, -1.0, -1.0)
self._ic.Update()
data = self._ic.GetOutput()
fm = 6
alpha = 0.25
topa = 2.0 * (1.0 + alpha)
dimx,dimy,dimz = data.GetDimensions()
dx,dy,dz = data.GetSpacing()
ox,oy,oz = data.GetOrigin()
progress = 0.0
pinc = 100.0 / dimz
for k in range(dimz):
z = oz + k * dz
for j in range(dimy):
y = oy + j * dy
for i in range(dimx):
x = ox + i * dx
rho_r = math.cos(2 * math.pi * fm *
math.cos(math.pi * math.hypot(x,y) / 2.0))
rho = (1.0 - math.sin(math.pi * z / 2.0) + alpha *
(1.0 + rho_r)) / topa
data.SetScalarComponentFromDouble(i,j,k,0,rho)
progress += pinc
self._module_manager.set_progress(progress, 'Sampling function.')
self._output.ShallowCopy(data)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('Marschner-Lobb volume',)
def get_output(self, idx):
return self._output
def config_to_logic(self):
pass
def logic_to_config(self):
pass
| Python |
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
class PassThrough(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
NoConfigModuleMixin.__init__(
self, {'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
NoConfigModuleMixin.close(self)
def get_input_descriptions(self):
return ('Anything',)
def set_input(self, idx, input_stream):
self._input = input_stream
def get_output_descriptions(self):
return ('Same as input', )
def get_output(self, idx):
return self._input
def execute_module(self):
pass
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# pointsToSpheres.py copyright (c) 2005 by Charl P. Botha <cpbotha@ieee.org>
# $Id$
# see module documentation
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import wx
import vtk
class pointsToSpheres(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._inputPoints = None
self._internalPoints = None
self._config.radius = 5
self._config.thetaResolution = 8 # minimum 3
self._config.phiResolution = 8 # minimum 3
self._config.numInternalSpheres = 3
configList = [('Sphere radius:', 'radius', 'base:float', 'text',
'The radius of the spheres that will be created '
'in world coordinate units.'),
('Theta resolution:', 'thetaResolution', 'base:int',
'text',
'Number of points in the longitudinal direction.'),
('Phi resolution:', 'phiResolution', 'base:int',
'text',
'Number of points in the latitudinal direction.'),
('Number of internal spheres:', 'numInternalSpheres',
'base:int', 'text',
'Number of spheres to create in the interior.')]
self._appendPolyData = vtk.vtkAppendPolyData()
if False:
# checked on 20090314: dummy input is very definitely
# required
# we do need a dummy sphere, else the appender complains
dummySphere = vtk.vtkSphereSource()
dummySphere.SetRadius(0.0)
# and a dummy calc, with -1 index
# if we don't add the VolumeIndex array here as well, the append
# polydata discards all the others
calc = vtk.vtkArrayCalculator()
calc.SetAttributeModeToUsePointData()
calc.SetFunction('-1')
calc.SetResultArrayName('VolumeIndex')
calc.SetInput(dummySphere.GetOutput())
self._appendPolyData.AddInput(calc.GetOutput())
else:
self._appendPolyData.AddInput(vtk.vtkPolyData())
# this will be a list of lists containing tuples
# (vtkArrayCalculator, vtkSphereSource)
self._sphereSources = []
# this will hold our shallow-copied output
self._output = vtk.vtkPolyData()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : 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
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._appendPolyData
del self._sphereSources
del self._output
def get_input_descriptions(self):
return ('Selected points',)
def set_input(self, idx, inputStream):
if inputStream is not self._inputPoints:
if inputStream == None:
self._inputPoints = None
elif hasattr(inputStream, 'devideType') and \
inputStream.devideType == 'namedPoints':
# correct type
self._inputPoints = inputStream
else:
raise TypeError, 'This input requires a named points type.'
def get_output_descriptions(self):
return ('PolyData spheres',)
def get_output(self, idx):
#return self._appendPolyData.GetOutput()
return self._output
def logic_to_config(self):
pass
def config_to_logic(self):
# if any of the parameters have changed, this affects all the spheres
# fortunately VTK caches this type of parameter so we don't have to
# check
# some sanity checking
if self._config.radius < 0:
self._config.radius = 0
if self._config.thetaResolution < 3:
self._config.thetaResolution = 3
if self._config.phiResolution < 3:
self._config.phiResolution = 3
if self._config.numInternalSpheres < 0:
self._config.numInternalSpheres = 0
# if the number of internal spheres has changed, we have to start over
haveToCreate = False
if len(self._sphereSources) > 0:
# this means we HAVE spheres already
currentNum = len(self._sphereSources[0]) - 1
if currentNum != self._config.numInternalSpheres:
haveToCreate = True
if haveToCreate:
self._createSpheres()
else:
radiusStep = self._getRadiusStep()
for spheres in self._sphereSources:
for i in range(len(spheres)):
# each element of spheres is a (calc, sphere) tuple
sphere = spheres[i][1]
sphere.SetRadius(self._config.radius - radiusStep * i)
sphere.SetThetaResolution(self._config.thetaResolution)
sphere.SetPhiResolution(self._config.phiResolution)
def execute_module(self):
# synchronise our balls on the input points (they might have changed)
self._syncOnInputPoints()
# run the whole pipeline
self._appendPolyData.Update()
# shallow copy the polydata
self._output.ShallowCopy(self._appendPolyData.GetOutput())
# indicate that the output has been modified
self._output.Modified()
def _syncOnInputPoints(self):
# extract a list from the input points
tempList = []
if self._inputPoints:
for i in self._inputPoints:
tempList.append(i['world'])
if tempList != self._internalPoints:
# store the new points
self._internalPoints = tempList
if len(self._internalPoints) == len(self._sphereSources):
# if the number of points has not changed, we only have to
# move points
for i in range(len(self._internalPoints)):
pt = self._internalPoints[i]
for calc,sphere in self._sphereSources[i]:
# set new centre
sphere.SetCenter(pt)
# set new index!
calc.SetFunction('%d' % (i,))
else:
# if the number of points HAS changed, we have to redo
# everything (we could try figuring out how things have
# changed, but we won't)
self._createSpheres()
def _destroySpheres(self):
# first remove all inputs from the appender
for spheres in self._sphereSources:
for calc, sphere in spheres:
self._appendPolyData.RemoveInput(calc.GetOutput())
# now actually nuke our references
del self._sphereSources[:]
def _createSpheres(self):
"""Create all spheres according to self._internalPoints.
"""
# make sure we're all empty
self._destroySpheres()
for ptIdx in range(len(self._internalPoints)):
pt = self._internalPoints[ptIdx]
# each point gets potentially more than one sphere
spheres = []
# then create and add the internal spheres
radiusStep = self._getRadiusStep()
# we do the mainSphere and the internal spheres in one go
for i in range(self._config.numInternalSpheres + 1):
sphere = vtk.vtkSphereSource()
sphere.SetCenter(pt)
sphere.SetRadius(self._config.radius - radiusStep * i)
sphere.SetThetaResolution(self._config.thetaResolution)
sphere.SetPhiResolution(self._config.phiResolution)
# use calculator to add array with VolumeIndex
calc = vtk.vtkArrayCalculator()
calc.SetAttributeModeToUsePointData()
calc.SetFunction('%d' % (ptIdx,))
calc.SetResultArrayName('VolumeIndex')
calc.SetInput(sphere.GetOutput())
self._appendPolyData.AddInput(calc.GetOutput())
spheres.append((calc,sphere))
self._sphereSources.append(spheres)
def _getRadiusStep(self):
radiusStep = self._config.radius / \
float(self._config.numInternalSpheres + 1)
return radiusStep
| Python |
import gen_utils
from module_base import ModuleBase
import module_utils
import module_mixins
from module_mixins import ScriptedConfigModuleMixin
import os
import vtk
class cptDistanceField(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._imageInput = None
self._meshInput = None
self._flipper = vtk.vtkImageFlip()
self._flipper.SetFilteredAxis(1)
module_utils.setup_vtk_object_progress(
self, self._flipper, 'Flipping Y axis.')
self._config.cpt_driver_path = \
'd:\\misc\\stuff\\driver.bat'
#'/home/cpbotha/build/cpt/3d/driver/driver.exe'
self._config.max_distance = 5
config_list = [
('CPT driver path', 'cpt_driver_path',
'base:str', 'filebrowser',
'Path to CPT driver executable',
{'fileMode' : module_mixins.wx.OPEN,
'fileMask' : 'All files (*.*)|*.*'}),
('Maximum distance', 'max_distance',
'base:float', 'text',
'The maximum (absolute) distance up to which the field is computed.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
self.sync_module_logic_with_config()
def close(self):
# we should disconnect all inputs
self.set_input(0, None)
self.set_input(1, None)
ScriptedConfigModuleMixin.close(self)
def get_input_descriptions(self):
return ('VTK Image', 'VTK Polydata')
def set_input(self, idx, inputStream):
if idx == 0:
try:
if inputStream == None or inputStream.IsA('vtkImageData'):
self._imageInput = inputStream
else:
raise TypeError
except (TypeError, AttributeError):
raise TypeError, 'This input requires a vtkImageData.'
else:
try:
if inputStream == None or inputStream.IsA('vtkPolyData'):
self._meshInput = inputStream
else:
raise TypeError
except (TypeError, AttributeError):
raise TypeError, 'This input requires a vtkPolyData.'
def get_output_descriptions(self):
return ('Distance field (VTK Image)',)
def get_output(self, idx):
return self._flipper.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def execute_module(self):
if self._imageInput and self._meshInput:
# basename for all CPT files
cptBaseName = os.tempnam()
# first convert mesh data to brep
cbw = self._module_manager.create_module(
'modules.writers.cptBrepWRT')
cbw.set_input(0, self._meshInput)
cfg = cbw.get_config()
brepFilename = '%s.brep' % (cptBaseName,)
cfg.filename = brepFilename
cbw.set_config(cfg)
# we're calling it directly... propagations will propagate
# upwards to our caller (the ModuleManager) - execution
# will be interrupted if cbw flags an error
cbw.execute_module()
# now let's write the geom file
self._imageInput.UpdateInformation()
b = self._imageInput.GetBounds()
d = self._imageInput.GetDimensions()
geomFile = file('%s.geom' % (cptBaseName,), 'w')
# bounds
geomFile.write('%f %f %f %f %f %f\n' % (b[0], b[2], b[4],
b[1], b[3], b[5]))
# dimensions
geomFile.write('%d %d %d\n' % (d[0], d[1], d[2]))
# maximum distance
geomFile.write('%d\n' % (self._config.max_distance,))
# must be signed
geomFile.write('1\n')
geomFile.close()
# now we can call the driver
os.system('%s -b -o %s %s.geom %s.brep' % \
(self._config.cpt_driver_path,
cptBaseName, cptBaseName, cptBaseName))
# we should have cptBaseName.dist waiting...
reader = vtk.vtkImageReader()
reader.SetFileName('%s.dist' % (cptBaseName,))
reader.SetFileDimensionality(3)
reader.SetDataScalarType(vtk.VTK_DOUBLE)
# 3 doubles in header
reader.SetHeaderSize(24)
reader.SetDataExtent(self._imageInput.GetWholeExtent())
reader.SetDataSpacing(self._imageInput.GetSpacing())
module_utils.setup_vtk_object_progress(
self, reader, 'Reading CPT distance field output.')
self._flipper.SetInput(reader.GetOutput())
self._flipper.GetOutput().UpdateInformation()
self._flipper.GetOutput().SetUpdateExtentToWholeExtent()
self._flipper.Update()
self._module_manager.delete_module(cbw)
print "CPT Basename == %s" % (cptBaseName,)
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class manualTransform(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._config.scale = (1.0, 1.0, 1.0)
self._config.orientation = (0.0, 0.0, 0.0)
self._config.translation = (0.0, 0.0, 0.0)
configList = [
('Scaling:', 'scale', 'tuple:float,3', 'tupleText',
'Scale factor in the x, y and z directions in world units.'),
('Orientation:', 'orientation', 'tuple:float,3', 'tupleText',
'Rotation, in order, around the x, the new y and the new z axes '
'in degrees.'),
('Translation:', 'translation', 'tuple:float,3', 'tupleText',
'Translation in the x,y,z directions.')]
self._transform = vtk.vtkTransform()
# we want changes here to happen AFTER the transformations
# represented by the input
self._transform.PostMultiply()
# has no progress!
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkTransform' : self._transform})
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._transform
def execute_module(self):
self._transform.Update()
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('VTK Transform',)
def get_output(self, idx):
return self._transform
def logic_to_config(self):
self._config.scale = self._transform.GetScale()
self._config.orientation = self._transform.GetOrientation()
self._config.translation = self._transform.GetPosition()
def config_to_logic(self):
# we have to reset the transform firstn
self._transform.Identity()
self._transform.Scale(self._config.scale)
self._transform.RotateX(self._config.orientation[0])
self._transform.RotateY(self._config.orientation[1])
self._transform.RotateZ(self._config.orientation[2])
self._transform.Translate(self._config.translation)
| 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
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 |
# 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 |
# 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 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 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.
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 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 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 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 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.
# 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 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.
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
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 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 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.
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.
# 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 |
# 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.
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 |
# 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 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
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 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 |
# 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 |
# 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 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
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.
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.
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.
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.
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 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 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 |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtpRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkXMLPolyDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK Poly Data (*.vtp)|*.vtp|All files (*)|*',
{'vtkXMLPolyDataReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading VTK PolyData')
self._viewFrame = None
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkPolyData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class stlRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkSTLReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'STL data (*.stl)|*.stl|All files (*)|*',
{'vtkSTLReader': self._reader})
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading STL data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkSTLReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class pngRDR(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkPNGReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading PNG images.')
self._config.filePattern = '%03d.png'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
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 (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkPNGReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
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())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class objRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkOBJReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'Wavefront OBJ data (*.obj)|*.obj|All files (*)|*',
{'vtkOBJReader': self._reader})
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading Wavefront OBJ data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkSTLReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import vtkPipelineConfigModuleMixin
from module_mixins import FileOpenDialogModuleMixin
import module_utils
import vtk
import wx
class rawVolumeRDR(ModuleBase,
vtkPipelineConfigModuleMixin,
FileOpenDialogModuleMixin):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkImageReader()
self._reader.SetFileDimensionality(3)
# FIXME: make configurable (or disable)
#self._reader.SetFileLowerLeft(1)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading raw volume data')
self._dataTypes = {'Double': vtk.VTK_DOUBLE,
'Float' : vtk.VTK_FLOAT,
'Long' : vtk.VTK_LONG,
'Unsigned Long' : vtk.VTK_UNSIGNED_LONG,
'Integer' : vtk.VTK_INT,
'Unsigned Integer' : vtk.VTK_UNSIGNED_INT,
'Short' : vtk.VTK_SHORT,
'Unsigned Short' : vtk.VTK_UNSIGNED_SHORT,
'Char' : vtk.VTK_CHAR,
'Unsigned Char' : vtk.VTK_UNSIGNED_CHAR}
self._viewFrame = None
# now setup some defaults before our sync
self._config.filename = ''
self._config.dataType = self._reader.GetDataScalarType()
# 1 is little endian
self._config.endianness = 1
self._config.headerSize = 0
self._config.extent = (0, 128, 0, 128, 0, 128)
self._config.spacing = (1.0, 1.0, 1.0)
self.sync_module_logic_with_config()
def close(self):
# close down the vtkPipeline stuff
vtkPipelineConfigModuleMixin.close(self)
# take out our view interface
if self._viewFrame is not None:
self._viewFrame.Destroy()
# get rid of our reference
del self._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception, 'rawVolumeRDR has no input!'
def get_output_descriptions(self):
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
# now setup some defaults before our sync
self._config.filename = self._reader.GetFileName()
self._config.dataType = self._reader.GetDataScalarType()
self._config.endianness = self._reader.GetDataByteOrder()
# it's going to try and calculate this... do we want this behaviour?
self._config.headerSize = self._reader.GetHeaderSize()
self._config.extent = self._reader.GetDataExtent()
self._config.spacing = self._reader.GetDataSpacing()
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
self._reader.SetDataScalarType(self._config.dataType)
self._reader.SetDataByteOrder(self._config.endianness)
self._reader.SetHeaderSize(self._config.headerSize)
self._reader.SetDataExtent(self._config.extent)
self._reader.SetDataSpacing(self._config.spacing)
def view_to_config(self):
if self._viewFrame is None:
self._createViewFrame()
self._config.filename = self._viewFrame.filenameText.GetValue()
# first get the selected string
dtcString = self._viewFrame.dataTypeChoice.GetStringSelection()
# this string MUST be in our dataTypes dictionary, get its value
self._config.dataType = self._dataTypes[dtcString]
# we have little endian first, but in VTK world it has to be 1
ebs = self._viewFrame.endiannessRadioBox.GetSelection()
self._config.endianness = not ebs
# try and convert headerSize control to int, if it doesn't work,
# use old value
try:
headerSize = int(self._viewFrame.headerSizeText.GetValue())
except:
headerSize = self._config.headerSize
self._config.headerSize = headerSize
# try and convert the string to a tuple
# yes, this is a valid away! see:
# http://mail.python.org/pipermail/python-list/1999-April/000546.html
try:
extent = eval(self._viewFrame.extentText.GetValue())
# now check that extent is a 6-element tuple
if type(extent) != tuple or len(extent) != 6:
raise Exception
# make sure that each element is an int
extent = tuple([int(i) for i in extent])
except:
# if this couldn't be converted to a 6-element int tuple, default
# to what's in config
extent = self._config.extent
self._config.extent = extent
try:
spacing = eval(self._viewFrame.spacingText.GetValue())
# now check that spacing is a 3-element tuple
if type(spacing) != tuple or len(spacing) != 3:
raise Exception
# make sure that each element is an FLOAT
spacing = tuple([float(i) for i in spacing])
except:
# if this couldn't be converted to a 6-element int tuple, default
# to what's in config
spacing = self._config.spacing
self._config.spacing = spacing
def config_to_view(self):
self._viewFrame.filenameText.SetValue(self._config.filename)
# now we have to find self._config.dataType in self._dataTypes
# I believe that I can assume .values() and .keys() to be consistent
# with each other (if I don't mutate the dictionary)
idx = self._dataTypes.values().index(self._config.dataType)
self._viewFrame.dataTypeChoice.SetStringSelection(
self._dataTypes.keys()[idx])
self._viewFrame.endiannessRadioBox.SetSelection(
not self._config.endianness)
self._viewFrame.headerSizeText.SetValue(str(self._config.headerSize))
self._viewFrame.extentText.SetValue(str(self._config.extent))
spacingText = "(%.3f, %.3f, %.3f)" % tuple(self._config.spacing)
self._viewFrame.spacingText.SetValue(spacingText)
def execute_module(self):
# get the reader to read :)
self._reader.Update()
def view(self, parent_window=None):
if self._viewFrame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
# 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.readers.resources.python.rawVolumeRDRViewFrame
reload(modules.readers.resources.python.rawVolumeRDRViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.rawVolumeRDRViewFrame.\
rawVolumeRDRViewFrame)
# bind the file browse button
wx.EVT_BUTTON(self._viewFrame,
self._viewFrame.browseButtonId,
self._browseButtonCallback)
# setup object introspection
objectDict = {'vtkImageReader' : self._reader}
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
objectDict, None)
# standard module buttons + events
module_utils.create_eoca_buttons(self, self._viewFrame,
self._viewFrame.viewFramePanel)
# finish setting up the output datatype choice
self._viewFrame.dataTypeChoice.Clear()
for aType in self._dataTypes.keys():
self._viewFrame.dataTypeChoice.Append(aType)
def _browseButtonCallback(self, event):
path = self.filenameBrowse(self._viewFrame,
"Select a raw volume filename",
"All files (*)|*")
if path != None:
self._viewFrame.filenameText.SetValue(path)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class BMPReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of BMP files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d 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 counts from the 'First slice' to the
'Last slice'.
"""
class DICOMReader:
kits = ['vtk_kit']
cats = ['Readers', 'Medical', 'DICOM']
help = """New module for reading DICOM data.
GDCM-based module for reading DICOM data. This is newer than
dicomRDR (which is DCMTK-based) and should be able to read more
kinds of data. The interface is deliberately less rich, as the
DICOMReader is supposed to be used in concert with the
DICOMBrowser.
If DICOMReader fails to read your DICOM data, please also try the
dicomRDR as its code is a few more years more mature than that of
the more flexible but younger DICOMReader.
"""
class dicomRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Module for reading DICOM data.
This is older DCMTK-based DICOM reader class. It used to be the
default in DeVIDE before the advent of the GDCM-based DICOMReader
in 8.5.
Add DICOM files (they may be from multiple series) by using the 'Add'
button on the view/config window. You can select multiple files in
the File dialog by holding shift or control whilst clicking. You
can also drag and drop files from a file or DICOM browser either
onto an existing dicomRDR or directly onto the Graph Editor
canvas.
"""
class JPEGReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of JPG (JPEG) files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d 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 counts from the 'First slice' to the
'Last slice'.
"""
class metaImageRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads MetaImage format files.
MetaImage files have an .mha or .mhd file extension. .mha files are
single files containing header and data, whereas .mhd are separate headers
that refer to a separate raw data file.
"""
class objRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for OBJ polydata format.
"""
class pngRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of PNG files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d 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 counts from the 'First slice' to the
'Last slice'.
"""
class points_reader:
# BUG: empty kits list screws up dependency checking
kits = ['vtk_kit']
cats = ['Writers']
help = """TBD
"""
class rawVolumeRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Use this module to read raw data volumes from disk.
"""
class stlRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for simple STL triangle-based polydata format.
"""
class TIFFReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of TIFF files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d 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 counts from the 'First slice' to the
'Last slice'.
"""
class vtiRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for VTK XML Image Data, the preferred format for all
VTK-compatible image data storage.
"""
class vtkPolyDataRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for legacy VTK polydata.
"""
class vtkStructPtsRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for legacy VTK structured points (image) data.
"""
class vtpRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads VTK PolyData in the VTK XML format.
VTP is the preferred format for DeVIDE PolyData.
"""
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_kits.misc_kit import misc_utils
from module_mixins import \
IntrospectModuleMixin
import module_utils
import gdcm
import vtk
import vtkgdcm
import wx
from module_kits.misc_kit.devide_types import MedicalMetaData
class DRDropTarget(wx.PyDropTarget):
def __init__(self, dicom_reader):
wx.PyDropTarget.__init__(self)
self._fdo = wx.FileDataObject()
self.SetDataObject(self._fdo)
self._dicom_reader = dicom_reader
def OnDrop(self, x, y):
return True
def OnData(self, x, y, d):
if self.GetData():
filenames = self._fdo.GetFilenames()
lb = self._dicom_reader._view_frame.dicom_files_lb
lb.Clear()
lb.AppendItems(filenames)
return d
class DICOMReader(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtkgdcm.vtkGDCMImageReader()
# NB NB NB: for now we're SWITCHING off the VTK-compatible
# Y-flip, until the X-mirror issues can be solved.
self._reader.SetFileLowerLeft(1)
self._ici = vtk.vtkImageChangeInformation()
self._ici.SetInputConnection(0, self._reader.GetOutputPort(0))
# create output MedicalMetaData and populate it with the
# necessary bindings.
mmd = MedicalMetaData()
mmd.medical_image_properties = \
self._reader.GetMedicalImageProperties()
mmd.direction_cosines = \
self._reader.GetDirectionCosines()
self._output_mmd = mmd
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading DICOM data')
self._view_frame = None
self._file_dialog = None
self._config.dicom_filenames = []
# if this is true, module will still try to load set even if
# IPP sorting fails by sorting images alphabetically
self._config.robust_spacing = False
self.sync_module_logic_with_config()
def close(self):
IntrospectModuleMixin.close(self)
# we just delete our binding. Destroying the view_frame
# should also take care of this one.
del self._file_dialog
if self._view_frame is not None:
self._view_frame.Destroy()
self._output_mmd.close()
del self._output_mmd
del self._reader
ModuleBase.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('DICOM data (vtkStructuredPoints)',
'Medical Meta Data')
def get_output(self, idx):
if idx == 0:
return self._ici.GetOutput()
elif idx == 1:
return self._output_mmd
def logic_to_config(self):
# we deliberately don't do any processing here, as we want to
# limit all DICOM parsing to the execute_module
pass
def config_to_logic(self):
# we deliberately don't add filenames to the reader here, as
# we would need to sort them, which would imply scanning all
# of them during this step
# we return False to indicate that we haven't made any changes
# to the underlying logic (so that the MetaModule knows it
# doesn't have to invalidate us after a call to
# config_to_logic)
return False
def view_to_config(self):
lb = self._view_frame.dicom_files_lb
# just clear out the current list
# and copy everything, only if necessary!
if self._config.dicom_filenames[:] == lb.GetStrings()[:]:
return False
else:
self._config.dicom_filenames[:] = lb.GetStrings()[:]
return True
def config_to_view(self):
# get listbox, clear it out, add filenames from the config
lb = self._view_frame.dicom_files_lb
if self._config.dicom_filenames[:] != lb.GetStrings()[:]:
lb.Clear()
lb.AppendItems(self._config.dicom_filenames)
def execute_module(self):
# have to cast to normal strings (from unicode)
filenames = [str(i) for i in self._config.dicom_filenames]
# make sure all is zeroed.
self._reader.SetFileName(None)
self._reader.SetFileNames(None)
# we only sort and derive slice-based spacing if there are
# more than 1 filenames
if len(filenames) > 1:
sorter = gdcm.IPPSorter()
sorter.SetComputeZSpacing(True)
sorter.SetZSpacingTolerance(1e-2)
ret = sorter.Sort(filenames)
alpha_sorted = False
if not ret:
if self._config.robust_spacing:
self._module_manager.log_warning(
'Could not sort DICOM filenames by IPP. Doing alphabetical sorting.')
filenames.sort()
alpha_sorted = True
else:
raise RuntimeError(
'Could not sort DICOM filenames before loading.')
if sorter.GetZSpacing() == 0.0 and not alpha_sorted:
msg = 'DICOM IPP sorting yielded incorrect results.'
raise RuntimeError(msg)
# then give the reader the sorted list of files
sa = vtk.vtkStringArray()
if alpha_sorted:
flist = filenames
else:
flist = sorter.GetFilenames()
for fn in flist:
sa.InsertNextValue(fn)
self._reader.SetFileNames(sa)
elif len(filenames) == 1:
self._reader.SetFileName(filenames[0])
else:
raise RuntimeError(
'No DICOM filenames to read.')
# now do the actual reading
self._reader.Update()
# see what the reader thinks the spacing is
spacing = list(self._reader.GetDataSpacing())
if len(filenames) > 1 and not alpha_sorted:
# after the reader has done its thing,
# impose derived spacing on the vtkImageChangeInformation
# (by default it takes the SpacingBetweenSlices, which is
# not always correct)
spacing[2] = sorter.GetZSpacing()
# single or multiple filenames, we have to set the correct
# output spacing on the image change information
print "SPACING: ", spacing
self._ici.SetOutputSpacing(spacing)
self._ici.Update()
# integrate DirectionCosines into output data ###############
# DirectionCosines: first two columns are X and Y in the LPH
# coordinate system
dc = self._reader.GetDirectionCosines()
x_cosine = \
dc.GetElement(0,0), dc.GetElement(1,0), dc.GetElement(2,0)
y_cosine = \
dc.GetElement(0,1), dc.GetElement(1,1), dc.GetElement(2,1)
# calculate plane normal (z axis) in LPH coordinate system by taking the cross product
norm = [0,0,0]
vtk.vtkMath.Cross(x_cosine, y_cosine, norm)
xl = misc_utils.major_axis_from_iop_cosine(x_cosine)
yl = misc_utils.major_axis_from_iop_cosine(y_cosine)
# vtkGDCMImageReader swaps the y (to fit the VTK convention),
# but does not flip the DirectionCosines here, so we do that.
# (only if the reader is flipping)
if yl and not self._reader.GetFileLowerLeft():
yl = tuple((yl[1], yl[0]))
zl = misc_utils.major_axis_from_iop_cosine(norm)
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
if xl and yl and zl:
# add this data as a vtkFieldData
fd = self._ici.GetOutput().GetFieldData()
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
for l in xl + yl + zl:
axis_labels_array.InsertNextValue(lut[l])
fd.AddArray(axis_labels_array)
def _create_view_frame(self):
import modules.readers.resources.python.DICOMReaderViewFrame
reload(modules.readers.resources.python.DICOMReaderViewFrame)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.DICOMReaderViewFrame.\
DICOMReaderViewFrame)
# make sure the listbox is empty
self._view_frame.dicom_files_lb.Clear()
object_dict = {
'Module (self)' : self,
'vtkGDCMImageReader' : self._reader}
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.view_frame_panel,
object_dict, None)
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel)
# now add the event handlers
self._view_frame.add_files_b.Bind(wx.EVT_BUTTON,
self._handler_add_files_b)
self._view_frame.remove_files_b.Bind(wx.EVT_BUTTON,
self._handler_remove_files_b)
# also the drop handler
dt = DRDropTarget(self)
self._view_frame.dicom_files_lb.SetDropTarget(dt)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
def view(self, parent_window=None):
if self._view_frame is None:
self._create_view_frame()
self.sync_module_view_with_logic()
self._view_frame.Show(True)
self._view_frame.Raise()
def _add_filenames_to_listbox(self, filenames):
# only add filenames that are not in there yet...
lb = self._view_frame.dicom_files_lb
# create new dictionary with current filenames as keys
dup_dict = {}.fromkeys(lb.GetStrings(), 1)
fns_to_add = [fn for fn in filenames
if fn not in dup_dict]
lb.AppendItems(fns_to_add)
def _handler_add_files_b(self, event):
if not self._file_dialog:
self._file_dialog = wx.FileDialog(
self._view_frame,
'Select files to add to the list', "", "",
"DICOM files (*.dcm)|*.dcm|DICOM files (*.img)|*.img|All files (*)|*",
wx.OPEN | wx.MULTIPLE)
if self._file_dialog.ShowModal() == wx.ID_OK:
new_filenames = self._file_dialog.GetPaths()
self._add_filenames_to_listbox(new_filenames)
def _handler_remove_files_b(self, event):
lb = self._view_frame.dicom_files_lb
sels = list(lb.GetSelections())
# we have to delete from the back to the front
sels.sort()
sels.reverse()
for sel in sels:
lb.Delete(sel)
| Python |
# $Id: vtpWRT.py 2401 2006-12-20 20:29:15Z cpbotha $
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import types
from modules.viewers.slice3dVWRmodules.selectedPoints import outputSelectedPoints
class points_reader(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'DeVIDE points (*.dvp)|*.dvp|All files (*)|*',
{'Module (self)': self},
fileOpen=True)
# set up some defaults
self._config.filename = ''
self._output_points = None
self.sync_module_logic_with_config()
def close(self):
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise NotImplementedError
def get_output_descriptions(self):
return ('DeVIDE points',)
def get_output(self, idx):
return self._output_points
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 self._config.filename:
fh = file(self._config.filename)
ltext = fh.read()
fh.close()
points_list = eval(ltext)
self._output_points = outputSelectedPoints()
self._output_points.extend(points_list)
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class vtkPolyDataRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkPolyDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK data (*.vtk)|*.vtk|All files (*)|*',
{'vtkPolyDataReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading vtk polydata')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkPolyDataReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id: BMPRDR.py 1853 2006-02-01 17:16:28Z cpbotha $
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class BMPReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkBMPReader()
self._reader.SetFileDimensionality(3)
self._reader.SetAllow8BitBMP(1)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading BMP images.')
self._config.filePattern = '%03d.bmp'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
configList = [
('File pattern:', 'filePattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : wx.OPEN,
'fileMask' :
'BMP files (*.bmp)|*.bmp|All files (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkBMPReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
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())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class metaImageRDR(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkMetaImageReader()
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading MetaImage data.')
self._config.filename = ''
configList = [
('File name:', 'filename', 'base:str', 'filebrowser',
'The name of the MetaImage file you want to load.',
{'fileMode' : wx.OPEN,
'fileMask' :
'MetaImage single file (*.mha)|*.mha|MetaImage separate header '
'(*.mhd)|*.mhd|All files (*.*)|*.*'})]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkMetaImageReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.filename = self._reader.GetFileName()
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def execute_module(self):
self._reader.Update()
| 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 gen_utils
from module_kits.misc_kit import misc_utils
import os
from module_base import ModuleBase
from module_mixins import \
IntrospectModuleMixin, FileOpenDialogModuleMixin
import module_utils
import stat
import wx
import vtk
import vtkdevide
import module_utils
class dicomRDR(ModuleBase,
IntrospectModuleMixin,
FileOpenDialogModuleMixin):
def __init__(self, module_manager):
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtkdevide.vtkDICOMVolumeReader()
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading DICOM data')
self._viewFrame = None
self._fileDialog = None
# setup some defaults
self._config.dicomFilenames = []
self._config.seriesInstanceIdx = 0
self._config.estimateSliceThickness = 1
# do the normal thang (down to logic, up again)
self.sync_module_logic_with_config()
def close(self):
if self._fileDialog is not None:
del self._fileDialog
# this will take care of all the vtkPipeline windows
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
# take care of our own window
self._viewFrame.Destroy()
# also remove the binding we have to our 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 ('DICOM data (vtkStructuredPoints)',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.seriesInstanceIdx = self._reader.GetSeriesInstanceIdx()
# refresh our list of dicomFilenames
del self._config.dicomFilenames[:]
for i in range(self._reader.get_number_of_dicom_filenames()):
self._config.dicomFilenames.append(
self._reader.get_dicom_filename(i))
self._config.estimateSliceThickness = self._reader.\
GetEstimateSliceThickness()
def config_to_logic(self):
self._reader.SetSeriesInstanceIdx(self._config.seriesInstanceIdx)
# this will clear only the dicom_filenames_buffer without setting
# mtime of the vtkDICOMVolumeReader
self._reader.clear_dicom_filenames()
for fullname in self._config.dicomFilenames:
# this will simply add a file to the buffer list of the
# vtkDICOMVolumeReader (will not set mtime)
self._reader.add_dicom_filename(fullname)
# if we've added the same list as we added at the previous exec
# of apply_config(), the dicomreader is clever enough to know that
# it doesn't require an update. Yay me.
self._reader.SetEstimateSliceThickness(
self._config.estimateSliceThickness)
def view_to_config(self):
self._config.seriesInstanceIdx = self._viewFrame.si_idx_spin.GetValue()
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
filenames_init = []
for n in range(count):
filenames_init.append(lb.GetString(n))
# go through list of files in directory, perform trivial tests
# and create a new list of files
del self._config.dicomFilenames[:]
for filename in filenames_init:
# at the moment, we check that it's a regular file
if stat.S_ISREG(os.stat(filename)[stat.ST_MODE]):
self._config.dicomFilenames.append(filename)
if len(self._config.dicomFilenames) == 0:
wx.LogError('Empty directory specified, not attempting '
'change in config.')
self._config.estimateSliceThickness = self._viewFrame.\
estimateSliceThicknessCheckBox.\
GetValue()
def config_to_view(self):
# first transfer list of files to listbox
lb = self._viewFrame.dicomFilesListBox
lb.Clear()
for fn in self._config.dicomFilenames:
lb.Append(fn)
# at this stage, we can always assume that the logic is current
# with the config struct...
self._viewFrame.si_idx_spin.SetValue(self._config.seriesInstanceIdx)
# some information in the view does NOT form part of the config,
# but comes directly from the logic:
# we're going to be reading some information from the _reader which
# is only up to date after this call
self._reader.UpdateInformation()
# get current SeriesInstanceIdx from the DICOMReader
# FIXME: the frikking SpinCtrl does not want to update when we call
# SetValue()... we've now hard-coded it in wxGlade (still doesn't work)
self._viewFrame.si_idx_spin.SetValue(
int(self._reader.GetSeriesInstanceIdx()))
# try to get current SeriesInstanceIdx (this will run at least
# UpdateInfo)
si_uid = self._reader.GetSeriesInstanceUID()
if si_uid == None:
si_uid = "NONE"
self._viewFrame.si_uid_text.SetValue(si_uid)
msii = self._reader.GetMaximumSeriesInstanceIdx()
self._viewFrame.seriesInstancesText.SetValue(str(msii))
# also limit the spin-control
self._viewFrame.si_idx_spin.SetRange(0, msii)
sd = self._reader.GetStudyDescription()
if sd == None:
self._viewFrame.study_description_text.SetValue("NONE");
else:
self._viewFrame.study_description_text.SetValue(sd);
rp = self._reader.GetReferringPhysician()
if rp == None:
self._viewFrame.referring_physician_text.SetValue("NONE");
else:
self._viewFrame.referring_physician_text.SetValue(rp);
dd = self._reader.GetDataDimensions()
ds = self._reader.GetDataSpacing()
self._viewFrame.dimensions_text.SetValue(
'%d x %d x %d at %.2f x %.2f x %.2f mm / voxel' % tuple(dd + ds))
self._viewFrame.estimateSliceThicknessCheckBox.SetValue(
self._config.estimateSliceThickness)
def execute_module(self):
# get the vtkDICOMVolumeReader to try and execute
self._reader.Update()
# now get some metadata out and insert it in our output stream
# first determine axis labels based on IOP ####################
iop = self._reader.GetImageOrientationPatient()
row = iop[0:3]
col = iop[3:6]
# the cross product (plane normal) based on the row and col will
# also be in the LPH coordinate system
norm = [0,0,0]
vtk.vtkMath.Cross(row, col, norm)
xl = misc_utils.major_axis_from_iop_cosine(row)
yl = misc_utils.major_axis_from_iop_cosine(col)
zl = misc_utils.major_axis_from_iop_cosine(norm)
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
if xl and yl and zl:
# add this data as a vtkFieldData
fd = self._reader.GetOutput().GetFieldData()
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
for l in xl + yl + zl:
axis_labels_array.InsertNextValue(lut[l])
fd.AddArray(axis_labels_array)
# window/level ###############################################
def _createViewFrame(self):
import modules.readers.resources.python.dicomRDRViewFrame
reload(modules.readers.resources.python.dicomRDRViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.dicomRDRViewFrame.\
dicomRDRViewFrame)
# make sure the listbox is empty
self._viewFrame.dicomFilesListBox.Clear()
objectDict = {'dicom reader' : self._reader}
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)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.addButton.GetId(),
self._handlerAddButton)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.removeButton.GetId(),
self._handlerRemoveButton)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
def view(self, parent_window=None):
if self._viewFrame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def _handlerAddButton(self, event):
if not self._fileDialog:
self._fileDialog = wx.FileDialog(
self._module_manager.get_module_view_parent_window(),
'Select files to add to the list', "", "",
"DICOM files (*.dcm)|*.dcm|DICOM files (*.img)|*.img|All files (*)|*",
wx.OPEN | wx.MULTIPLE)
if self._fileDialog.ShowModal() == wx.ID_OK:
newFilenames = self._fileDialog.GetPaths()
# first check for duplicates in the listbox
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
oldFilenames = []
for n in range(count):
oldFilenames.append(lb.GetString(n))
filenamesToAdd = [fn for fn in newFilenames
if fn not in oldFilenames]
for fn in filenamesToAdd:
lb.Append(fn)
def _handlerRemoveButton(self, event):
"""Remove all selected filenames from the internal list.
"""
lb = self._viewFrame.dicomFilesListBox
sels = list(lb.GetSelections())
# we have to delete from the back to the front
sels.sort()
sels.reverse()
# build list
for sel in sels:
lb.Delete(sel)
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtiRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkXMLImageDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK Image Data (*.vti)|*.vti|All files (*)|*',
{'vtkXMLImageDataReader': self._reader,
'Module (self)' : self})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading VTK ImageData')
# set up some defaults
self._config.filename = ''
# there is no view yet...
self._module_manager.sync_module_logic_with_config(self)
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
def streaming_execute_module(self):
if len(self._reader.GetFileName()):
self._reader.UpdateInformation()
self._reader.GetOutput().SetUpdateExtentToWholeExtent()
self._reader.Update()
| 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 module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin, WX_OPEN
import module_utils
import vtk
class TIFFReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkTIFFReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading TIFF images.')
self._config.file_pattern = '%03d.tif'
self._config.first_slice = 0
self._config.last_slice = 1
self._config.spacing = (1,1,1)
self._config.file_lower_left = False
configList = [
('File pattern:', 'file_pattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : WX_OPEN,
'fileMask' :
'TIFF files (*.tif or *.tiff)|*.tif;*.tiff|All files (*.*)|*.*'}),
('First slice:', 'first_slice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'last_slice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'file_lower_left', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkTIFFReader' : self._reader})
self.sync_module_logic_with_config()
def close(self):
# 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 ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.file_pattern = self._reader.GetFilePattern()
self._config.first_slice = self._reader.GetFileNameSliceOffset()
e = self._reader.GetDataExtent()
self._config.last_slice = self._config.first_slice + e[5] - e[4]
self._config.spacing = self._reader.GetDataSpacing()
self._config.file_lower_left = bool(self._reader.GetFileLowerLeft())
def config_to_logic(self):
self._reader.SetFilePattern(self._config.file_pattern)
self._reader.SetFileNameSliceOffset(self._config.first_slice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.last_slice -
self._config.first_slice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.file_lower_left)
def execute_module(self):
self._reader.Update()
def streaming_execute_module(self):
self._reader.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class JPEGReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkJPEGReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading JPG images.')
self._config.filePattern = '%03d.jpg'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
configList = [
('File pattern:', 'filePattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : wx.OPEN,
'fileMask' :
'JPG files (*.jpg)|*.jpg|All files (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkJPEGReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
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())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtkStructPtsRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkStructuredPointsReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK data (*.vtk)|*.vtk|All files (*)|*',
{'vtkStructuredPointsReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading vtk structured points data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkStructuredPoints',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.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):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class wsMeshSmooth(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._wsPDFilter = vtk.vtkWindowedSincPolyDataFilter()
module_utils.setup_vtk_object_progress(self, self._wsPDFilter,
'Smoothing polydata')
# setup some defaults
self._config.numberOfIterations = 20
self._config.passBand = 0.1
self._config.featureEdgeSmoothing = False
self._config.boundarySmoothing = True
self._config.non_manifold_smoothing = False
config_list = [
('Number of iterations', 'numberOfIterations', 'base:int', 'text',
'Algorithm will stop after this many iterations.'),
('Pass band (0 - 2, default 0.1)', 'passBand', 'base:float',
'text', 'Indication of frequency cut-off, the lower, the more '
'it smoothes.'),
('Feature edge smoothing', 'featureEdgeSmoothing', 'base:bool',
'checkbox', 'Smooth feature edges (large dihedral angle)'),
('Boundary smoothing', 'boundarySmoothing', 'base:bool',
'checkbox', 'Smooth boundary edges (edges with only one face).'),
('Non-manifold smoothing', 'non_manifold_smoothing',
'base:bool', 'checkbox',
'Smooth non-manifold vertices, for example output of '
'discrete marching cubes (multi-material).')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkWindowedSincPolyDataFilter' : self._wsPDFilter})
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._wsPDFilter
def get_input_descriptions(self):
return ('vtkPolyData',)
def set_input(self, idx, inputStream):
self._wsPDFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._wsPDFilter.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._wsPDFilter.GetOutput()
def logic_to_config(self):
self._config.numberOfIterations = self._wsPDFilter.\
GetNumberOfIterations()
self._config.passBand = self._wsPDFilter.GetPassBand()
self._config.featureEdgeSmoothing = bool(
self._wsPDFilter.GetFeatureEdgeSmoothing())
self._config.boundarySmoothing = bool(
self._wsPDFilter.GetBoundarySmoothing())
self._config.non_manifold_smoothing = bool(
self._wsPDFilter.GetNonManifoldSmoothing())
def config_to_logic(self):
self._wsPDFilter.SetNumberOfIterations(self._config.numberOfIterations)
self._wsPDFilter.SetPassBand(self._config.passBand)
self._wsPDFilter.SetFeatureEdgeSmoothing(
self._config.featureEdgeSmoothing)
self._wsPDFilter.SetBoundarySmoothing(
self._config.boundarySmoothing)
self._wsPDFilter.SetNonManifoldSmoothing(
self._config.non_manifold_smoothing)
def execute_module(self):
self._wsPDFilter.Update()
# no streaming yet :) (underlying filter works with 2 streaming
# pieces, no other settings)
| 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 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 |
# DicomAligner.py by Francois Malan - 2011-06-23
# Revised as version 2.0 on 2011-07-07
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
from module_kits.misc_kit import misc_utils
import wx
import os
import vtk
import itk
import math
import numpy
class DICOMAligner(
NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
NoConfigModuleMixin.__init__(
self, {'Module (self)' : self})
self.sync_module_logic_with_config()
self._ir = vtk.vtkImageReslice()
self._ici = vtk.vtkImageChangeInformation()
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
NoConfigModuleMixin.close(self)
def set_input(self, idx, input_stream):
if idx == 0:
self._imagedata = input_stream
else:
self._metadata = input_stream
self._input = input_stream
def get_input_descriptions(self):
return ('vtkImageData (from DICOMReader port 0)', 'Medical metadata (from DICOMReader port 1)')
def get_output_descriptions(self):
return ('vtkImageData', )
def get_output(self, idx):
return self._output
def _convert_input(self):
'''
Performs the required transformation to match the image to the world coordinate system defined by medmeta
'''
# the first two columns of the direction cosines matrix represent
# the x,y axes of the DICOM slices in the patient's LPH space
# if we want to resample the images so that x,y are always LP
# the inverse should do the trick (transpose should also work as long as boths sets of axes
# is right-handed but let's stick to inverse for safety)
dcmatrix = vtk.vtkMatrix4x4()
dcmatrix.DeepCopy(self._metadata.direction_cosines)
dcmatrix.Invert()
origin = self._imagedata.GetOrigin()
spacing = self._imagedata.GetSpacing()
extent = self._imagedata.GetExtent()
# convert our new cosines to something we can give the ImageReslice
dcm = [[0,0,0] for _ in range(3)]
for col in range(3):
for row in range(3):
dcm[col][row] = dcmatrix.GetElement(row, col)
# do it.
self._ir.SetResliceAxesDirectionCosines(dcm[0], dcm[1], dcm[2])
self._ir.SetInput(self._imagedata)
self._ir.SetAutoCropOutput(1)
self._ir.SetInterpolationModeToCubic()
isotropic_sp = min(min(spacing[0],spacing[1]),spacing[2])
self._ir.SetOutputSpacing(isotropic_sp, isotropic_sp, isotropic_sp)
self._ir.Update()
output = self._ir.GetOutput()
#We now have to check whether the origin needs to be moved from its prior position
#Yes folks - the reslice operation screws up the origin and we must fix it.
#(Since the IPP is INDEPENDENT of the IOP, a reslice operation to fix the axes' orientation
# should not rotate the origin)
#
#The origin's coordinates (as provided by the DICOMreader) are expressed in PATIENT-LPH
#We are transforming the voxels (i.e. image coordiante axes)
# FROM IMAGE TO LPH coordinates. We must not transform the origin in this
# sense- only the image axes (and therefore voxels). However, vtkImageReslice
# (for some strange reason) transforms the origin according to the
# transformation matrix (?). So we need to reset this.
#Once the image is aligned to the LPH coordinate axes, a voxel(centre)'s LPH coordinates
# = origin + image_coordinates * spacing.
#But, there is a caveat.
# Since both image coordinates and spacing are positive, the origin must be at
# the "most negative" corner (in LPH terms). Even worse, if the LPH axes are not
# perpendicular relative to the original image axes, this "most negative" corner will
# lie outside of the original image volume (in a zero-padded region) - see AutoCropOutput.
# But the original origin is defined at the "most negative" corner in IMAGE
# coordinates(!). This means that the origin should, in most cases, be
# translated from its original position, depending on the relative LPH and
# image axes' orientations.
#
#The (x,y,z) components of the new origin are, independently, the most negative x,
#most negative y and most negative z LPH coordinates of the eight ORIGINAL IMAGE corners.
#To determine this we compute the eight corner coordinates and do a minimization.
#
#Remember that (in matlab syntax)
# p_world = dcm_matrix * diag(spacing)*p_image + origin
#for example: for a 90 degree rotation around the x axis this is
# [p_x] [ 1 0 0][nx*dx] [ox]
# [p_y] = [ 0 0 1][ny*dy] + [oy]
# [p_z] [ 0 -1 0][nz*dz] [oz]
#, where p is the LPH coordinates, d is the spacing, n is the image
# coordinates and o is the origin (IPP of the slice with the most negative IMAGE z coordinate).
originn = numpy.array(origin)
dcmn = numpy.array(dcm)
corners = numpy.zeros((3,8))
#first column of the DCM is a unit LPH-space vector in the direction of the first IMAGE axis, etc.
#From this it follows that the displacements along the full IMAGE's x, y and z extents are:
sx = spacing[0]*extent[1]*dcmn[:,0]
sy = spacing[1]*extent[3]*dcmn[:,1]
sz = spacing[2]*extent[5]*dcmn[:,2]
corners[:,0] = originn
corners[:,1] = originn + sx
corners[:,2] = originn + sy
corners[:,3] = originn + sx + sy
corners[:,4] = originn + sz
corners[:,5] = originn + sx + sz
corners[:,6] = originn + sy + sz
corners[:,7] = originn + sx + sy + sz
newOriginX = min(corners[0,:]);
newOriginY = min(corners[1,:]);
newOriginZ = min(corners[2,:]);
#Since we set the direction cosine matrix to unity we have to reset the
#axis labels array as well.
self._ici.SetInput(output)
self._ici.Update()
fd = self._ici.GetOutput().GetFieldData()
fd.RemoveArray('axis_labels_array')
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
fd.RemoveArray('axis_labels_array')
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
axis_labels_array.InsertNextValue(lut['R'])
axis_labels_array.InsertNextValue(lut['L'])
axis_labels_array.InsertNextValue(lut['A'])
axis_labels_array.InsertNextValue(lut['P'])
axis_labels_array.InsertNextValue(lut['F'])
axis_labels_array.InsertNextValue(lut['H'])
fd.AddArray(axis_labels_array)
self._ici.Update()
output = self._ici.GetOutput()
output.SetOrigin(newOriginX, newOriginY, newOriginZ)
self._output = output
def execute_module(self):
self._convert_input() | 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 |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
EMODES = {
1:'Point seeded regions',
2:'Cell seeded regions',
3:'Specified regions',
4:'Largest region',
5:'All regions',
6:'Closest point region'
}
class polyDataConnect(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._polyDataConnect = vtk.vtkPolyDataConnectivityFilter()
# we're not going to use this feature just yet
self._polyDataConnect.ScalarConnectivityOff()
#
self._polyDataConnect.SetExtractionModeToPointSeededRegions()
module_utils.setup_vtk_object_progress(self, self._polyDataConnect,
'Finding connected surfaces')
# default is point seeded regions (we store zero-based)
self._config.extraction_mode = 0
self._config.colour_regions = 0
config_list = [
('Extraction mode:', 'extraction_mode', 'base:int',
'choice',
'What kind of connected regions should be extracted.',
[EMODES[i] for i in range(1,7)]),
('Colour regions:', 'colour_regions', 'base:int',
'checkbox',
'Should connected regions be coloured differently.')
]
# and the mixin constructor
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkPolyDataConnectivityFilter' : self._polyDataConnect})
# we'll use this to keep a binding (reference) to the passed object
self._input_points = None
# this will be our internal list of points
self._seedIds = []
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)
# don't forget to call the close() method of the vtkPipeline mixin
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._polyDataConnect
def get_input_descriptions(self):
return ('vtkPolyData', 'Seed points')
def set_input(self, idx, inputStream):
if idx == 0:
# will work for None and not-None
self._polyDataConnect.SetInput(inputStream)
else:
self._input_points = inputStream
def get_output_descriptions(self):
return (self._polyDataConnect.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._polyDataConnect.GetOutput()
def logic_to_config(self):
# extractionmodes in vtkPolyDataCF start at 1
# we store it as 0-based
emode = self._polyDataConnect.GetExtractionMode()
self._config.extraction_mode = emode - 1
self._config.colour_regions = \
self._polyDataConnect.GetColorRegions()
def config_to_logic(self):
# extractionmodes in vtkPolyDataCF start at 1
# we store it as 0-based
self._polyDataConnect.SetExtractionMode(
self._config.extraction_mode + 1)
self._polyDataConnect.SetColorRegions(
self._config.colour_regions)
def execute_module(self):
if self._polyDataConnect.GetExtractionMode() == 1:
self._sync_pdc_to_input_points()
self._polyDataConnect.Update()
def _sync_pdc_to_input_points(self):
# extract a list from the input points
temp_list = []
if self._input_points and self._polyDataConnect.GetInput():
for i in self._input_points:
id = self._polyDataConnect.GetInput().FindPoint(i['world'])
if id > 0:
temp_list.append(id)
if temp_list != self._seedIds:
self._seedIds = temp_list
# I'm hoping this clears the list
self._polyDataConnect.InitializeSeedList()
for seedId in self._seedIds:
self._polyDataConnect.AddSeed(seedId)
print "adding %d" % (seedId)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class transformPolyData(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._transformPolyData = vtk.vtkTransformPolyDataFilter()
NoConfigModuleMixin.__init__(
self, {'vtkTransformPolyDataFilter' : self._transformPolyData})
module_utils.setup_vtk_object_progress(self, self._transformPolyData,
'Transforming geometry')
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._transformPolyData
def get_input_descriptions(self):
return ('vtkPolyData', 'vtkTransform')
def set_input(self, idx, inputStream):
if idx == 0:
self._transformPolyData.SetInput(inputStream)
else:
self._transformPolyData.SetTransform(inputStream)
def get_output_descriptions(self):
return (self._transformPolyData.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._transformPolyData.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._transformPolyData.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class imageMask(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# setup VTK pipeline #########################################
# 1. vtkImageMask
self._imageMask = vtk.vtkImageMask()
self._imageMask.GetOutput().SetUpdateExtentToWholeExtent()
#self._imageMask.SetMaskedOutputValue(0)
module_utils.setup_vtk_object_progress(self, self._imageMask,
'Masking image')
# 2. vtkImageCast
self._image_cast = vtk.vtkImageCast()
# type required by vtkImageMask
self._image_cast.SetOutputScalarTypeToUnsignedChar()
# connect output of cast to imagemask input
self._imageMask.SetMaskInput(self._image_cast.GetOutput())
module_utils.setup_vtk_object_progress(
self, self._image_cast,
'Casting mask image to unsigned char')
###############################################################
self._config.not_mask = False
self._config.masked_output_value = 0.0
config_list = [
('Negate (NOT) mask:', 'not_mask', 'base:bool', 'checkbox',
'Should mask be negated (NOT operator applied) before '
'applying to input?'),
('Masked output value:', 'masked_output_value', 'base:float',
'text', 'Positions outside the mask will be assigned this '
'value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' :self,
'vtkImageMask' : self._imageMask})
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._imageMask
del self._image_cast
def get_input_descriptions(self):
return ('vtkImageData (data)', 'vtkImageData (mask)')
def set_input(self, idx, inputStream):
if idx == 0:
self._imageMask.SetImageInput(inputStream)
else:
self._image_cast.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageMask.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._imageMask.GetOutput()
def logic_to_config(self):
self._config.not_mask = bool(self._imageMask.GetNotMask())
# GetMaskedOutputValue() is not wrapped. *SIGH*
#self._config.masked_output_value = \
# self._imageMask.GetMaskedOutputValue()
def config_to_logic(self):
self._imageMask.SetNotMask(self._config.not_mask)
self._imageMask.SetMaskedOutputValue(self._config.masked_output_value)
def execute_module(self):
self._imageMask.Update()
def streaming_execute_module(self):
self._imageMask.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class extractGrid(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._config.sampleRate = (1, 1, 1)
configList = [
('Sample rate:', 'sampleRate', 'tuple:int,3', 'tupleText',
'Subsampling rate.')]
self._extractGrid = vtkdevide.vtkPVExtractVOI()
module_utils.setup_vtk_object_progress(self, self._extractGrid,
'Subsampling structured grid.')
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkExtractGrid' : self._extractGrid})
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._extractGrid
def execute_module(self):
self._extractGrid.Update()
def get_input_descriptions(self):
return ('VTK Dataset',)
def set_input(self, idx, inputStream):
self._extractGrid.SetInput(inputStream)
def get_output_descriptions(self):
return ('Subsampled VTK Dataset',)
def get_output(self, idx):
return self._extractGrid.GetOutput()
def logic_to_config(self):
self._config.sampleRate = self._extractGrid.GetSampleRate()
def config_to_logic(self):
self._extractGrid.SetSampleRate(self._config.sampleRate)
| Python |
import input_array_choice_mixin
from input_array_choice_mixin import InputArrayChoiceMixin
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
INTEG_TYPE = ['RK2', 'RK4', 'RK45']
INTEG_TYPE_TEXTS = ['Runge-Kutta 2', 'Runge-Kutta 4', 'Runge-Kutta 45']
INTEG_DIR = ['FORWARD', 'BACKWARD', 'BOTH']
INTEG_DIR_TEXTS = ['Forward', 'Backward', 'Both']
ARRAY_IDX = 0
class streamTracer(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
InputArrayChoiceMixin.__init__(self)
# 0 = RK2
# 1 = RK4
# 2 = RK45
self._config.integrator = INTEG_TYPE.index('RK2')
self._config.max_prop = 5.0
self._config.integration_direction = INTEG_DIR.index(
'FORWARD')
configList = [
('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
'The attribute that will be used as vectors for the warping.',
(input_array_choice_mixin.DEFAULT_SELECTION_STRING,)),
('Max propagation:', 'max_prop', 'base:float', 'text',
'The streamline will propagate up to this lenth.'),
('Integration direction:', 'integration_direction', 'base:int', 'choice',
'Select an integration direction.',
INTEG_DIR_TEXTS),
('Integrator type:', 'integrator', 'base:int', 'choice',
'Select an integrator for the streamlines.',
INTEG_TYPE_TEXTS)]
self._streamTracer = vtk.vtkStreamTracer()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkStreamTracer' : self._streamTracer})
module_utils.setup_vtk_object_progress(self, self._streamTracer,
'Tracing stream lines.')
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._streamTracer
def execute_module(self):
self._streamTracer.Update()
if self.view_initialised:
choice = self._getWidget(0)
self.iac_execute_module(self._streamTracer, choice,
ARRAY_IDX)
def get_input_descriptions(self):
return ('VTK Vector dataset', 'VTK source geometry')
def set_input(self, idx, inputStream):
if idx == 0:
self._streamTracer.SetInput(inputStream)
else:
self._streamTracer.SetSource(inputStream)
def get_output_descriptions(self):
return ('Streamlines polydata',)
def get_output(self, idx):
return self._streamTracer.GetOutput()
def logic_to_config(self):
self._config.max_prop = \
self._streamTracer.GetMaximumPropagation()
self._config.integration_direction = \
self._streamTracer.GetIntegrationDirection()
self._config.integrator = self._streamTracer.GetIntegratorType()
# this will extract the possible choices
self.iac_logic_to_config(self._streamTracer, ARRAY_IDX)
def config_to_logic(self):
self._streamTracer.SetMaximumPropagation(self._config.max_prop)
self._streamTracer.SetIntegrationDirection(self._config.integration_direction)
self._streamTracer.SetIntegratorType(self._config.integrator)
# it seems that array_idx == 1 refers to vectors
# array_idx 0 gives me only the x-component of multi-component
# arrays
self.iac_config_to_logic(self._streamTracer, ARRAY_IDX)
def config_to_view(self):
# first get our parent mixin to do its thing
ScriptedConfigModuleMixin.config_to_view(self)
choice = self._getWidget(0)
self.iac_config_to_view(choice)
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class extractHDomes(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageMathSubtractH = vtk.vtkImageMathematics()
self._imageMathSubtractH.SetOperationToAddConstant()
self._reconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D()
# second input is marker
self._reconstruct.SetInput(1, self._imageMathSubtractH.GetOutput())
self._imageMathSubtractR = vtk.vtkImageMathematics()
self._imageMathSubtractR.SetOperationToSubtract()
self._imageMathSubtractR.SetInput(1, self._reconstruct.GetOutput())
module_utils.setup_vtk_object_progress(self, self._imageMathSubtractH,
'Preparing marker image.')
module_utils.setup_vtk_object_progress(self, self._reconstruct,
'Performing reconstruction.')
module_utils.setup_vtk_object_progress(self, self._imageMathSubtractR,
'Subtracting reconstruction.')
self._config.h = 50
configList = [
('H-dome height:', 'h', 'base:float', 'text',
'The required difference in brightness between an h-dome and\n'
'its surroundings.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'ImageMath Subtract H' : self._imageMathSubtractH,
'ImageGreyscaleReconstruct3D' : self._reconstruct,
'ImageMath Subtract R' : self._imageMathSubtractR})
self.sync_module_logic_with_config()
def 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._imageMathSubtractH
del self._reconstruct
del self._imageMathSubtractR
def get_input_descriptions(self):
return ('Input image (VTK)',)
def set_input(self, idx, inputStream):
self._imageMathSubtractH.SetInput(0, inputStream)
# first input of the reconstruction is the image
self._reconstruct.SetInput(0, inputStream)
self._imageMathSubtractR.SetInput(0, inputStream)
def get_output_descriptions(self):
return ('h-dome extraction (VTK image)',)
def get_output(self, idx):
return self._imageMathSubtractR.GetOutput()
def logic_to_config(self):
self._config.h = - self._imageMathSubtractH.GetConstantC()
def config_to_logic(self):
self._imageMathSubtractH.SetConstantC( - self._config.h)
def execute_module(self):
self._imageMathSubtractR.Update()
| Python |
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class transformVolumeData(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageReslice = vtk.vtkImageReslice()
self._imageReslice.SetInterpolationModeToCubic()
self._imageReslice.SetAutoCropOutput(1)
# initialise any mixins we might have
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageReslice' : self._imageReslice})
module_utils.setup_vtk_object_progress(self, self._imageReslice,
'Resampling volume')
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._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:
if inputStream == None:
# disconnect
self._imageReslice.SetResliceTransform(None)
else:
# resliceTransform transforms the resampling grid, which
# is equivalent to transforming the volume with its inverse
self._imageReslice.SetResliceTransform(
inputStream.GetInverse())
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 |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class extractImageComponents(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._extract = vtk.vtkImageExtractComponents()
module_utils.setup_vtk_object_progress(self, self._extract,
'Extracting components.')
self._config.component1 = 0
self._config.component2 = 1
self._config.component3 = 2
self._config.numberOfComponents = 1
self._config.fileLowerLeft = False
configList = [
('Component 1:', 'component1', 'base:int', 'text',
'Zero-based index of first component to extract.'),
('Component 2:', 'component2', 'base:int', 'text',
'Zero-based index of second component to extract.'),
('Component 3:', 'component3', 'base:int', 'text',
'Zero-based index of third component to extract.'),
('Number of components:', 'numberOfComponents', 'base:int',
'choice',
'Number of components to extract. Only this number of the '
'above-specified component indices will be used.',
('1', '2', '3'))]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageExtractComponents' : self._extract})
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._extract
def get_input_descriptions(self):
return ('Multi-component vtkImageData',)
def set_input(self, idx, inputStream):
self._extract.SetInput(inputStream)
def get_output_descriptions(self):
return ('Extracted component vtkImageData',)
def get_output(self, idx):
return self._extract.GetOutput()
def logic_to_config(self):
# numberOfComponents is 0-based !!
self._config.numberOfComponents = \
self._extract.GetNumberOfComponents()
self._config.numberOfComponents -= 1
c = self._extract.GetComponents()
self._config.component1 = c[0]
self._config.component2 = c[1]
self._config.component3 = c[2]
def config_to_logic(self):
# numberOfComponents is 0-based !!
nc = self._config.numberOfComponents
nc += 1
if nc == 1:
self._extract.SetComponents(self._config.component1)
elif nc == 2:
self._extract.SetComponents(self._config.component1,
self._config.component2)
else:
self._extract.SetComponents(self._config.component1,
self._config.component2,
self._config.component3)
def execute_module(self):
self._extract.Update()
| 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 |
# this one was generated with:
# for i in *.py; do n=`echo $i | cut -f 1 -d .`; \
# echo -e "class $n:\n kits = ['vtk_kit']\n cats = ['Filters']\n" \
# >> blaat.txt; done
class appendPolyData:
kits = ['vtk_kit']
cats = ['Filters']
help = """DeVIDE encapsulation of the vtkAppendPolyDataFilter that
enables us to combine multiple PolyData structures into one.
DANGER WILL ROBINSON: contact the author, this module is BROKEN.
"""
class clipPolyData:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['polydata', 'clip', 'implicit']
help = \
"""Given an input polydata and an implicitFunction, this will clip
the polydata.
All points that are inside the implicit function are kept, everything
else is discarded. 'Inside' is defined as all points in the polydata
where the implicit function value is greater than 0.
"""
class closing:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological closing on the input image.
Dilation is followed by erosion. The structuring element is ellipsoidal
with user specified sizes in 3 dimensions. Specifying a size of 1 in any
dimension will disable processing in that dimension.
"""
class contour:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extract isosurface from volume data.
"""
class decimate:
kits = ['vtk_kit']
cats = ['Filters']
help = """Reduce number of triangles in surface mesh by merging triangles
in areas of low detail.
"""
class DICOMAligner:
kits = ['vtk_kit', 'wx_kit']
cats = ['DICOM','Filters']
keywords = ['align','reslice','rotate','orientation','dicom']
help = """Aligns a vtkImageData volume (as read from DICOM) to the
standard DICOM LPH (Left-Posterior-Head) coordinate system.
If alignment is not performed the image's "world" (patient LPH)
coordinates may be computed incorrectly (e.g. in Slice3DViewer).
The transformation reslices the original volume, then moves
the image origin as required. The new origin has to be at the centre
of the voxel with most negative LPH coordinates.
Example use case: Before aligning multiple MRI sequences
for fusion/averaging
(Module by Francois Malan)"""
class doubleThreshold:
kits = ['vtk_kit']
cats = ['Filters']
help = """Apply a lower and an upper threshold to the input image data.
"""
class EditMedicalMetaData:
kits = ['vtk_kit']
cats = ['Filters', 'Medical', 'DICOM']
help = """Edit Medical Meta Data structure. Use this to edit for
example the medical meta data output of a DICOMReader before
writing DICOM data to disk, or to create new meta data. You don't
have to supply an input.
"""
class extractGrid:
kits = ['vtk_kit']
cats = ['Filters']
help = """Subsamples input dataset.
This module makes use of the ParaView vtkPVExtractVOI class, which can
handle structured points, structured grids and rectilinear grids.
"""
class extractHDomes:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Extracts light structures, also known as h-domes.
The user specifies the parameter 'h' that indicates how much brighter the
light structures are than their surroundings. In short, this algorithm
performs a fast greyscale reconstruction of the input image from a marker
that is the image - h. The result of this reconstruction is subtracted
from the image.
See 'Morphological Grayscale Reconstruction in Image Analysis:
Applications and Efficient Algorithms', Luc Vincent, IEEE Trans. on Image
Processing, 1993.
"""
class extractImageComponents:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extracts one, two or three components from multi-component
image data.
Specify the indices of the components you wish to extract and the number
of components.
"""
class FastSurfaceToDistanceField:
kits = ['vtk_kit','vtktudoss_kit']
cats = ['Filters']
keywords = ['distance','distance field', 'mauch', 'polydata',
'implicit']
help = """Given an input surface (vtkPolyData), create a signed
distance field with the surface at distance 0. Uses Mauch's very
fast CPT / distance field implementation.
"""
class FitEllipsoidToMask:
kits = ['numpy_kit', 'vtk_kit']
cats = ['Filters']
keywords = ['PCA', 'eigen-analysis', 'principal components', 'ellipsoid']
help = """Given an image mask in VTK image data format, perform eigen-
analysis on the world coordinates of 'on' points.
Returns dictionary with eigen values in 'u', eigen vectors in 'v' and
world coordinates centroid of 'on' points.
"""
class glyphs:
kits = ['vtk_kit']
cats = ['Filters']
help = """Visualise vector field with glyphs.
After connecting this module, execute your network once, then you
can select the relevant vector attribute to glyph from the
'Vectors Selection' choice in the interface.
"""
class greyReconstruct:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs grey value reconstruction of mask I from marker J.
Theoretically, marker J is dilated and the infimum with mask I is
determined. This infimum now takes the place of J. This process is
repeated until stability.
This module uses a DeVIDE specific implementation of Luc Vincent's fast
hybrid algorithm for greyscale reconstruction.
"""
class ICPTransform:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['iterative closest point transform', 'map',
'register', 'registration']
help = """Use iterative closest point transform to map two
surfaces onto each other with an affine transform.
Three different transform modes are available:
<ul>
<li>Rigid: rotation + translation</li>
<li>Similarity: rigid + isotropic scaling</li>
<li>Affine: rigid + scaling + shear</li>
</ul>
The output of this class is a linear transform that can be used as
input to for example a transformPolydata class.
"""
class imageFillHoles:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Filter to fill holes.
In binary images, holes are image regions with 0-value that are completely
surrounded by regions of 1-value. This module can be used to fill these
holes. This filling also works on greyscale images.
In addition, the definition of a hole can be adapted by 'deactivating'
image borders so that 0-value regions that touch these deactivated borders
are still considered to be holes and will be filled.
This module is based on two DeVIDE-specific filters: a fast greyscale
reconstruction filter as per Luc Vincent and a special image border mask
generator filter.
"""
class imageFlip:
kits = ['vtk_kit']
cats = ['Filters']
help = """Flips image (volume) with regards to a single axis.
At the moment, this flips by default about Z. You can change this by
introspecting and calling the SetFilteredAxis() method via the
object inspection.
"""
class imageGaussianSmooth:
kits = ['vtk_kit']
cats = ['Filters']
help = """Performs 3D Gaussian filtering of the input volume.
"""
class imageGradientMagnitude:
kits = ['vtk_kit']
cats = ['Filters']
help = """Calculates the gradient magnitude of the input volume using
central differences.
"""
class imageGreyDilate:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale 3D dilation on the input.
"""
class imageGreyErode:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale 3D erosion on the input.
"""
class ImageLogic:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """Performs pointwise boolean logic operations on input images.
WARNING: vtkImageLogic in VTK 5.0 has a bug where it does require two
inputs even if performing a NOT or a NOP. This has been fixed in VTK CVS.
DeVIDE will upgrade to > 5.0 as soon as a new stable VTK is released.
"""
class imageMask:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """The input data (input 1) is masked with the mask (input 2).
The output image is identical to the input image wherever the mask has
a value. The output image is 0 everywhere else.
"""
class imageMathematics:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """Performs point-wise mathematical operations on one or two images.
The underlying logic can do far more than the UI shows at this moment.
Please let me know if you require more options.
"""
class imageMedian3D:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs 3D morphological median on input data.
"""
class landmarkTransform:
kits = ['vtk_kit']
cats = ['Filters']
help = """The landmarkTransform will calculate a 4x4 linear transform
that maps from a set of source landmarks to a set of target landmarks.
The mapping is optimised with a least-squares metric.
For convenience, there are two inputs that you can use in any
combination (either or both). All points that you supply (for
example the output of slice3dVWR modules) will be combined
internally into one list and then divided into two groups based on
the point names: the one group with names starting with 'source'
the other with 'target'. Points will then be matched up by name,
so 'source example 1' will be matched with 'target example 1'.
This module will supply a vtkTransform at its output. By
connecting the vtkTransform to a transformPolyData or a
transformVolume module, you'll be able to perform the actual
transformation.
See the "Performing landmark registration on two volumes" example in the
"Useful Patterns" section of the DeVIDE F1 central help.
"""
class marchingCubes:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extract surface from input volume using the Marching Cubes
algorithm.
"""
class morphGradient:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological gradient on the input image.
This is done by performing an erosion and a dilation of the input image
and then subtracting the erosion from the dilation. The structuring
element is ellipsoidal with user specified sizes in 3 dimensions.
Specifying a size of 1 in any dimension will disable processing in that
dimension.
This module can also return both half gradients: the inner (image -
erosion) and the outer (dilation - image).
"""
class opening:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological opening on the input image.
Erosion is followed by dilation. The structuring element is ellipsoidal
with user specified sizes in 3 dimensions. Specifying a size of 1 in any
dimension will disable processing in that dimension.
"""
class MIPRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Performs Maximum Intensity Projection on the input volume /
image.
"""
class polyDataConnect:
kits = ['vtk_kit']
cats = ['Filters']
help = """Perform connected components analysis on polygonal data.
In the default 'point seeded regions' mode:
Given a number of seed points, extract all polydata that is
directly or indirectly connected to those seed points. You could see
this as a polydata-based region growing.
"""
class polyDataNormals:
kits = ['vtk_kit']
cats = ['Filters']
help = """Calculate surface normals for input data mesh.
"""
class probeFilter:
kits = ['vtk_kit']
cats = ['Filters']
help = """Maps source values onto input dataset.
Input can be e.g. polydata and source a volume, in which case interpolated
values from the volume will be mapped on the vertices of the polydata,
i.e. the interpolated values will be associated as the attributes of the
polydata points.
"""
class RegionGrowing:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['region growing', 'threshold', 'automatic',
'segmentation']
help = """Perform 3D region growing with automatic thresholding
based on seed positions.
Given any number of seed positions (for example the first output
of a slice3dVWR), first calculate lower and upper thresholds
automatically as follows:
<ol>
<li>calculate mean intensity over all seed positions.</li>
<li>lower threshold = mean - auto_thresh_interval%
* [full input data scalar range].</li>
<li>upper threshold = mean + auto_thresh_interval% * [full input
data scalar range].</li>
</ol>
After the data has been thresholded with the automatic thresholds,
a 3D region growing is started from all seed positions.
"""
class resampleImage:
kits = ['vtk_kit']
cats = ['Filters']
help = """Resample an image using nearest neighbour, linear or cubic
interpolation.
"""
class seedConnect:
kits = ['vtk_kit']
cats = ['Filters']
help = """3D region growing.
Finds all points connected to the seed points that also have values
equal to the 'Input Connected Value'. This module casts all input to
unsigned char. The output is also unsigned char.
"""
class selectConnectedComponents:
kits = ['vtk_kit']
cats = ['Filters']
help = """3D region growing.
Finds all points connected to the seed points that have the same values
as at the seed points. This is primarily useful for selecting connected
components.
"""
class shellSplatSimple:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Simple configuration for ShellSplatting an input volume.
ShellSplatting is a fast direct volume rendering method. See
http://visualisation.tudelft.nl/Projects/ShellSplatting for more
information.
"""
class StreamerVTK:
kits = ['vtk_kit']
cats = ['Streaming']
keywords = ['streaming', 'streamer', 'hybrid']
help = """Use this module to terminate streaming subsets of
networks consisting of VTK modules producing image or poly data.
This module requests input in blocks to build up a complete output
dataset. Together with the hybrid scheduling in DeVIDE, this
can save loads of memory.
"""
class streamTracer:
kits = ['vtk_kit']
cats = ['Filters']
help = """Visualise a vector field with stream lines.
After connecting this module, execute your network once, then you
can select the relevant vector attribute to glyph from the
'Vectors Selection' choice in the interface.
"""
class surfaceToDistanceField:
kits = ['vtk_kit']
cats = ['Filters']
help = """Given an input surface (vtkPolyData), create an unsigned
distance field with the surface at distance 0.
The user must specify the dimensions and bounds of the output volume.
WARNING: this filter is *incredibly* slow, even for small volumes and
extremely simple geometry. Only use this if you know exactly what
you're doing.
"""
class transformImageToTarget:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['align','reslice','rotate','orientation','transform','resample']
help = """Transforms input volume by the supplied geometrical transform, and maps it onto a new coordinate frame (orientation, extent, spacing) specified by the
the specified target grid. The target is not overwritten, but a new volume is created with the desired orientation, dimensions and spacing.
This volume is then filled by probing the transformed source. Areas for which no values are found are zero-padded.
"""
class transformPolyData:
kits = ['vtk_kit']
cats = ['Filters']
help = """Given a transform, for example the output of the
landMarkTransform, this module will transform its input polydata.
"""
class transformVolumeData:
kits = ['vtk_kit']
cats = ['Filters']
help = """Transform volume according to 4x4 homogeneous transform.
"""
class ExpVolumeRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """EXPERIMENTAL Volume Render.
This is an experimental volume renderer module used to test out
new ideas. Handle with EXTREME caution, it might open portals to
other dimensions, letting through its evil minions into ours, and
forcing you to take a stand with only a crowbar at your disposal.
If you would rather just volume render some data, please use the
non-experimental VolumeRender module.
"""
class VolumeRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Use direct volume rendering to visualise input volume.
You can select between traditional raycasting, 2D texturing and 3D
texturing. The raycaster can only handler unsigned short or unsigned char
data, so you might have to use a vtkShiftScale module to preprocess.
You can supply your own opacity and colour transfer functions at the
second and third inputs. If you don't supply these, the module will
create opacity and/or colour ramps based on the supplied threshold.
"""
class warpPoints:
kits = ['vtk_kit']
cats = ['Filters']
help = """Warp input points according to their associated vectors.
After connecting this module up, you have to execute the network
once, then select the relevant vectors from the 'Vectors
Selection' choice in the interface.
"""
class wsMeshSmooth:
kits = ['vtk_kit']
cats = ['Filters']
help = """Module that runs vtkWindowedSincPolyDataFilter on its input data
for mesh smoothing.
"""
| 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 |
# todo:
# * vtkVolumeMapper::SetCroppingRegionPlanes(xmin,xmax,ymin,ymax,zmin,zmax)
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class MIPRender(
ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
#for o in self._objectDict.values():
#
# setup some config defaults
self._config.threshold = 1250
self._config.interpolation = 0 # nearest
# this is not in the interface yet, change by introspection
self._config.mip_colour = (0.0, 0.0, 1.0)
config_list = [
('Threshold:', 'threshold', 'base:float', 'text',
'Used to generate transfer function if none is supplied'),
('Interpolation:', 'interpolation', 'base:int', 'choice',
'Linear (high quality, slower) or nearest neighbour (lower '
'quality, faster) interpolation',
('Nearest Neighbour', 'Linear'))]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
self._create_pipeline()
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)
# get rid of our reference
del self._otf
del self._ctf
del self._volume_property
del self._volume_raycast_function
del self._volume_mapper
del self._volume
def get_input_descriptions(self):
return ('input image data', 'transfer functions')
def set_input(self, idx, inputStream):
if idx == 0:
if inputStream is None:
# disconnect this way, else we get:
# obj._volume_mapper.SetInput(None)
# TypeError: ambiguous call, multiple overloaded methods match the arguments
self._volume_mapper.SetInputConnection(0, None)
else:
self._volume_mapper.SetInput(inputStream)
else:
pass
def get_output_descriptions(self):
return ('vtkVolume',)
def get_output(self, idx):
return self._volume
def logic_to_config(self):
self._config.interpolation = \
self._volume_property.GetInterpolationType()
def config_to_logic(self):
self._otf.RemoveAllPoints()
t = self._config.threshold
p1 = t - t / 10.0
p2 = t + t / 5.0
print "MIP: %.2f - %.2f" % (p1, p2)
self._otf.AddPoint(p1, 0.0)
self._otf.AddPoint(p2, 1.0)
self._otf.AddPoint(self._config.threshold, 1.0)
self._ctf.RemoveAllPoints()
self._ctf.AddHSVPoint(p1, 0.0, 0.0, 0.0)
self._ctf.AddHSVPoint(p2, *self._config.mip_colour)
self._volume_property.SetInterpolationType(self._config.interpolation)
def execute_module(self):
self._volume_mapper.Update()
def _create_pipeline(self):
# setup our pipeline
self._otf = vtk.vtkPiecewiseFunction()
self._ctf = vtk.vtkColorTransferFunction()
self._volume_property = vtk.vtkVolumeProperty()
self._volume_property.SetScalarOpacity(self._otf)
self._volume_property.SetColor(self._ctf)
self._volume_property.ShadeOn()
self._volume_property.SetAmbient(0.1)
self._volume_property.SetDiffuse(0.7)
self._volume_property.SetSpecular(0.2)
self._volume_property.SetSpecularPower(10)
self._volume_raycast_function = vtk.vtkVolumeRayCastMIPFunction()
self._volume_mapper = vtk.vtkVolumeRayCastMapper()
# can also used FixedPoint, but then we have to use:
# SetBlendModeToMaximumIntensity() and not SetVolumeRayCastFunction
#self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
self._volume_mapper.SetVolumeRayCastFunction(
self._volume_raycast_function)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
self._volume = vtk.vtkVolume()
self._volume.SetProperty(self._volume_property)
self._volume.SetMapper(self._volume_mapper)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class morphGradient(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# main morph gradient
self._imageDilate = vtk.vtkImageContinuousDilate3D()
self._imageErode = vtk.vtkImageContinuousErode3D()
self._imageMath = vtk.vtkImageMathematics()
self._imageMath.SetOperationToSubtract()
self._imageMath.SetInput1(self._imageDilate.GetOutput())
self._imageMath.SetInput2(self._imageErode.GetOutput())
# inner gradient
self._innerImageMath = vtk.vtkImageMathematics()
self._innerImageMath.SetOperationToSubtract()
self._innerImageMath.SetInput1(None) # has to take image
self._innerImageMath.SetInput2(self._imageErode.GetOutput())
# outer gradient
self._outerImageMath = vtk.vtkImageMathematics()
self._outerImageMath.SetOperationToSubtract()
self._outerImageMath.SetInput1(self._imageDilate.GetOutput())
self._outerImageMath.SetInput2(None) # has to take image
module_utils.setup_vtk_object_progress(self, self._imageDilate,
'Performing greyscale 3D dilation')
module_utils.setup_vtk_object_progress(self, self._imageErode,
'Performing greyscale 3D erosion')
module_utils.setup_vtk_object_progress(self, self._imageMath,
'Subtracting erosion from '
'dilation')
module_utils.setup_vtk_object_progress(self, self._innerImageMath,
'Subtracting erosion from '
'image (inner)')
module_utils.setup_vtk_object_progress(self, self._outerImageMath,
'Subtracting image from '
'dilation (outer)')
self._config.kernelSize = (3, 3, 3)
configList = [
('Kernel size:', 'kernelSize', 'tuple:int,3', 'text',
'Size of the kernel in x,y,z dimensions.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageContinuousDilate3D' : self._imageDilate,
'vtkImageContinuousErode3D' : self._imageErode,
'vtkImageMathematics' : self._imageMath})
self.sync_module_logic_with_config()
def 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
del self._imageErode
del self._imageMath
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageDilate.SetInput(inputStream)
self._imageErode.SetInput(inputStream)
self._innerImageMath.SetInput1(inputStream)
self._outerImageMath.SetInput2(inputStream)
def get_output_descriptions(self):
return ('Morphological gradient (vtkImageData)',
'Morphological inner gradient (vtkImageData)',
'Morphological outer gradient (vtkImageData)')
def get_output(self, idx):
if idx == 0:
return self._imageMath.GetOutput()
if idx == 1:
return self._innerImageMath.GetOutput()
else:
return self._outerImageMath.GetOutput()
def logic_to_config(self):
# if the user's futzing around, she knows what she's doing...
# (we assume that the dilate/erode pair are in sync)
self._config.kernelSize = self._imageDilate.GetKernelSize()
def config_to_logic(self):
ks = self._config.kernelSize
self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2])
self._imageErode.SetKernelSize(ks[0], ks[1], ks[2])
def execute_module(self):
# we only execute the main gradient
self._imageMath.Update()
| Python |
# imageGaussianSmooth copyright (c) 2003 by Charl P. Botha cpbotha@ieee.org
# $Id: resampleImage.py 3229 2008-09-04 17:06:13Z cpbotha $
# performs image smoothing by convolving with a Gaussian
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
class resampleImage(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageResample = vtk.vtkImageResample()
module_utils.setup_vtk_object_progress(self, self._imageResample,
'Resampling image.')
# 0: nearest neighbour
# 1: linear
# 2: cubic
self._config.interpolationMode = 1
self._config.magFactors = [1.0, 1.0, 1.0]
self._view_frame = None
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)
# don't forget to call the close() method of the vtkPipeline mixin
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._imageResample
# and finally call our base dtor
ModuleBase.close(self)
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageResample.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageResample.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._imageResample.GetOutput()
def logic_to_config(self):
istr = self._imageResample.GetInterpolationModeAsString()
# we do it this way so that when the values in vtkImageReslice
# are changed, we won't be affected
self._config.interpolationMode = {'NearestNeighbor': 0,
'Linear': 1,
'Cubic': 3}[istr]
for i in range(3):
mfi = self._imageResample.GetAxisMagnificationFactor(i, None)
self._config.magFactors[i] = mfi
def config_to_logic(self):
if self._config.interpolationMode == 0:
self._imageResample.SetInterpolationModeToNearestNeighbor()
elif self._config.interpolationMode == 1:
self._imageResample.SetInterpolationModeToLinear()
else:
self._imageResample.SetInterpolationModeToCubic()
for i in range(3):
self._imageResample.SetAxisMagnificationFactor(
i, self._config.magFactors[i])
def view_to_config(self):
itc = self._view_frame.interpolationTypeChoice.GetSelection()
if itc < 0 or itc > 2:
# default when something weird happens to choice
itc = 1
self._config.interpolationMode = itc
txtTup = self._view_frame.magFactorXText.GetValue(), \
self._view_frame.magFactorYText.GetValue(), \
self._view_frame.magFactorZText.GetValue()
for i in range(3):
self._config.magFactors[i] = gen_utils.textToFloat(
txtTup[i], self._config.magFactors[i])
def config_to_view(self):
self._view_frame.interpolationTypeChoice.SetSelection(
self._config.interpolationMode)
txtTup = self._view_frame.magFactorXText, \
self._view_frame.magFactorYText, \
self._view_frame.magFactorZText
for i in range(3):
txtTup[i].SetValue(str(self._config.magFactors[i]))
def execute_module(self):
self._imageResample.Update()
def streaming_execute_module(self):
self._imageResample.GetOutput().Update()
def view(self, parent_window=None):
if self._view_frame is None:
self._createViewFrame()
# following ModuleBase convention to indicate that view is
# available.
self.view_initialised = True
# and make sure the view is up to date
self._module_manager.sync_module_view_with_logic(self)
# if the window was visible already. just raise it
self._view_frame.Show(True)
self._view_frame.Raise()
def _createViewFrame(self):
self._module_manager.import_reload(
'modules.filters.resources.python.resampleImageViewFrame')
import modules.filters.resources.python.resampleImageViewFrame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.filters.resources.python.resampleImageViewFrame.\
resampleImageViewFrame)
objectDict = {'vtkImageResample' : self._imageResample}
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)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtktudoss
class FastSurfaceToDistanceField(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._clean_pd = vtk.vtkCleanPolyData()
module_utils.setup_vtk_object_progress(
self, self._clean_pd,
'Cleaning up polydata')
self._cpt_df = vtktudoss.vtkCPTDistanceField()
module_utils.setup_vtk_object_progress(
self, self._cpt_df,
'Converting surface to distance field')
# connect the up
self._cpt_df.SetInputConnection(
self._clean_pd.GetOutputPort())
self._config.max_dist = 1.0
self._config.padding = 0.0
self._config.dimensions = (64, 64, 64)
configList = [
('Maximum distance:', 'max_dist', 'base:float',
'text',
'Maximum distance up to which field will be '
'calculated.'),
('Dimensions:', 'dimensions', 'tuple:int,3',
'tupleText',
'Resolution of resultant distance field.'),
('Padding:', 'padding', 'base:float', 'text',
'Padding of distance field around surface.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkCleanPolyData' : self._clean_pd,
'vtkCPTDistanceField' : self._cpt_df})
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._clean_pd
del self._cpt_df
def get_input_descriptions(self):
return ('Surface (vtkPolyData)',)
def set_input(self, idx, inputStream):
self._clean_pd.SetInput(inputStream)
def get_output_descriptions(self):
return ('Distance field (VTK Image Data)',)
def get_output(self, idx):
return self._cpt_df.GetOutput()
def logic_to_config(self):
self._config.max_dist = self._cpt_df.GetMaximumDistance()
self._config.padding = self._cpt_df.GetPadding()
self._config.dimensions = self._cpt_df.GetDimensions()
def config_to_logic(self):
self._cpt_df.SetMaximumDistance(self._config.max_dist)
self._cpt_df.SetPadding(self._config.padding)
self._cpt_df.SetDimensions(self._config.dimensions)
def execute_module(self):
self._cpt_df.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 |
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 |
# todo:
# * vtkVolumeMapper::SetCroppingRegionPlanes(xmin,xmax,ymin,ymax,zmin,zmax)
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class VolumeRender(
ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# at the first config_to_logic (at the end of the ctor), this will
# be set to 0
self._current_rendering_type = -1
# setup some config defaults
self._config.rendering_type = 0
self._config.interpolation = 1 # linear
self._config.ambient = 0.1
self._config.diffuse = 0.7
self._config.specular = 0.6
self._config.specular_power = 80
self._config.threshold = 1250
# this is not in the interface yet, change by introspection
self._config.mip_colour = (0.0, 0.0, 1.0)
config_list = [
('Rendering type:', 'rendering_type', 'base:int', 'choice',
'Direct volume rendering algorithm that will be used.',
('Raycast (fixed point)', 'GPU raycasting',
'2D Texture', '3D Texture',
'ShellSplatting', 'Raycast (old)')),
('Interpolation:', 'interpolation', 'base:int', 'choice',
'Linear (high quality, slower) or nearest neighbour (lower '
'quality, faster) interpolation',
('Nearest Neighbour', 'Linear')),
('Ambient:', 'ambient', 'base:float', 'text',
'Ambient lighting term.'),
('Diffuse:', 'diffuse', 'base:float', 'text',
'Diffuse lighting term.'),
('Specular:', 'specular', 'base:float', 'text',
'Specular lighting term.'),
('Specular power:', 'specular_power', 'base:float', 'text',
'Specular power lighting term (more focused high-lights).'),
('Threshold:', 'threshold', 'base:float', 'text',
'Used to generate transfer function ONLY if none is supplied')
]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
self._input_data = None
self._input_otf = None
self._input_ctf = None
self._volume_raycast_function = None
self._create_pipeline()
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)
# get rid of our reference
del self._volume_property
del self._volume_raycast_function
del self._volume_mapper
del self._volume
def get_input_descriptions(self):
return ('input image data',
'opacity transfer function',
'colour transfer function')
def set_input(self, idx, inputStream):
if idx == 0:
self._input_data = inputStream
elif idx == 1:
self._input_otf = inputStream
else:
self._input_ctf = inputStream
def get_output_descriptions(self):
return ('vtkVolume',)
def get_output(self, idx):
return self._volume
def logic_to_config(self):
self._config.rendering_type = self._current_rendering_type
self._config.interpolation = \
self._volume_property.GetInterpolationType()
self._config.ambient = self._volume_property.GetAmbient()
self._config.diffuse = self._volume_property.GetDiffuse()
self._config.specular = self._volume_property.GetSpecular()
self._config.specular_power = \
self._volume_property.GetSpecularPower()
def config_to_logic(self):
self._volume_property.SetInterpolationType(self._config.interpolation)
self._volume_property.SetAmbient(self._config.ambient)
self._volume_property.SetDiffuse(self._config.diffuse)
self._volume_property.SetSpecular(self._config.specular)
self._volume_property.SetSpecularPower(self._config.specular_power)
if self._config.rendering_type != self._current_rendering_type:
if self._config.rendering_type == 0:
# raycast fixed point
self._setup_for_fixed_point()
elif self._config.rendering_type == 1:
# gpu raycasting
self._setup_for_gpu_raycasting()
elif self._config.rendering_type == 2:
# 2d texture
self._setup_for_2d_texture()
elif self._config.rendering_type == 3:
# 3d texture
self._setup_for_3d_texture()
elif self._config.rendering_type == 4:
# shell splatter
self._setup_for_shell_splatting()
else:
# old raycaster (very picky about input types)
self._setup_for_raycast()
self._volume.SetMapper(self._volume_mapper)
self._current_rendering_type = self._config.rendering_type
def _setup_for_raycast(self):
self._volume_raycast_function = \
vtk.vtkVolumeRayCastCompositeFunction()
self._volume_mapper = vtk.vtkVolumeRayCastMapper()
self._volume_mapper.SetVolumeRayCastFunction(
self._volume_raycast_function)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_2d_texture(self):
self._volume_mapper = vtk.vtkVolumeTextureMapper2D()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_3d_texture(self):
self._volume_mapper = vtk.vtkVolumeTextureMapper3D()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_shell_splatting(self):
self._volume_mapper = vtkdevide.vtkOpenGLVolumeShellSplatMapper()
self._volume_mapper.SetOmegaL(0.9)
self._volume_mapper.SetOmegaH(0.9)
# high-quality rendermode
self._volume_mapper.SetRenderMode(0)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_fixed_point(self):
"""This doesn't seem to work. After processing is complete,
it stalls on actually rendering the volume. No idea.
"""
self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
self._volume_mapper.SetBlendModeToComposite()
#self._volume_mapper.SetBlendModeToMaximumIntensity()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_gpu_raycasting(self):
"""This doesn't seem to work. After processing is complete,
it stalls on actually rendering the volume. No idea.
"""
self._volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
self._volume_mapper.SetBlendModeToComposite()
#self._volume_mapper.SetBlendModeToMaximumIntensity()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def execute_module(self):
otf, ctf = self._create_tfs()
if self._input_otf is not None:
otf = self._input_otf
if self._input_ctf is not None:
ctf = self._input_ctf
self._volume_property.SetScalarOpacity(otf)
self._volume_property.SetColor(ctf)
self._volume_mapper.SetInput(self._input_data)
self._volume_mapper.Update()
def _create_tfs(self):
otf = vtk.vtkPiecewiseFunction()
ctf = vtk.vtkColorTransferFunction()
otf.RemoveAllPoints()
t = self._config.threshold
p1 = t - t / 10.0
p2 = t + t / 5.0
print "MIP: %.2f - %.2f" % (p1, p2)
otf.AddPoint(p1, 0.0)
otf.AddPoint(p2, 1.0)
otf.AddPoint(self._config.threshold, 1.0)
ctf.RemoveAllPoints()
ctf.AddHSVPoint(p1, 0.1, 0.7, 1.0)
#ctf.AddHSVPoint(p2, *self._config.mip_colour)
ctf.AddHSVPoint(p2, 0.65, 0.7, 1.0)
return (otf, ctf)
def _create_pipeline(self):
# setup our pipeline
self._volume_property = vtk.vtkVolumeProperty()
self._volume_property.ShadeOn()
self._volume_mapper = None
self._volume = vtk.vtkVolume()
self._volume.SetProperty(self._volume_property)
self._volume.SetMapper(self._volume_mapper)
| Python |
# imageGaussianSmooth copyright (c) 2003 by Charl P. Botha cpbotha@ieee.org
# $Id$
# performs image smoothing by convolving with a Gaussian
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
class imageGaussianSmooth(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageGaussianSmooth = vtk.vtkImageGaussianSmooth()
module_utils.setup_vtk_object_progress(self, self._imageGaussianSmooth,
'Smoothing image with Gaussian')
self._config.standardDeviation = (2.0, 2.0, 2.0)
self._config.radiusCutoff = (1.5, 1.5, 1.5)
self._view_frame = None
self._module_manager.sync_module_logic_with_config(self)
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
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._imageGaussianSmooth
# and finally call our base dtor
ModuleBase.close(self)
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageGaussianSmooth.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageGaussianSmooth.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._imageGaussianSmooth.GetOutput()
def logic_to_config(self):
self._config.standardDeviation = self._imageGaussianSmooth.\
GetStandardDeviations()
self._config.radiusCutoff = self._imageGaussianSmooth.\
GetRadiusFactors()
def config_to_logic(self):
self._imageGaussianSmooth.SetStandardDeviations(
self._config.standardDeviation)
self._imageGaussianSmooth.SetRadiusFactors(
self._config.radiusCutoff)
def view_to_config(self):
# continue with textToTuple in gen_utils
stdText = self._view_frame.stdTextCtrl.GetValue()
self._config.standardDeviation = gen_utils.textToTypeTuple(
stdText, self._config.standardDeviation, 3, float)
cutoffText = self._view_frame.radiusCutoffTextCtrl.GetValue()
self._config.radiusCutoff = gen_utils.textToTypeTuple(
cutoffText, self._config.radiusCutoff, 3, float)
def config_to_view(self):
stdText = '(%.2f, %.2f, %.2f)' % self._config.standardDeviation
self._view_frame.stdTextCtrl.SetValue(stdText)
cutoffText = '(%.2f, %.2f, %.2f)' % self._config.radiusCutoff
self._view_frame.radiusCutoffTextCtrl.SetValue(cutoffText)
def execute_module(self):
self._imageGaussianSmooth.Update()
def view(self, parent_window=None):
if self._view_frame is None:
self._createViewFrame()
# the logic is the bottom line in this case
self._module_manager.sync_module_view_with_logic(self)
# if the window was visible already. just raise it
self._view_frame.Show(True)
self._view_frame.Raise()
def _createViewFrame(self):
self._module_manager.import_reload(
'modules.filters.resources.python.imageGaussianSmoothViewFrame')
import modules.filters.resources.python.imageGaussianSmoothViewFrame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.filters.resources.python.imageGaussianSmoothViewFrame.\
imageGaussianSmoothViewFrame)
objectDict = {'vtkImageGaussianSmooth' : self._imageGaussianSmooth}
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)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.