code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
from module_mixins import simpleVTKClassModuleBase import vtk import vtkdevide class imageBorderMask(simpleVTKClassModuleBase): def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtkdevide.vtkImageBorderMask(), 'Creating border mask.', ('VTK Image Data',), ('Border Mask (vtkImageData)',))
[ [ 1, 0, 0.0714, 0.0714, 0, 0.66, 0, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.1429, 0.0714, 0, 0.66, 0.3333, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 1, 0, 0.2143, 0.0714, 0, ...
[ "from module_mixins import simpleVTKClassModuleBase", "import vtk", "import vtkdevide", "class imageBorderMask(simpleVTKClassModuleBase):\n\n def __init__(self, module_manager):\n simpleVTKClassModuleBase.__init__(\n self, module_manager,\n vtkdevide.vtkImageBorderMask(), 'Crea...
# $Id$ import fixitk as itk import gen_utils from module_base import ModuleBase import module_utils import module_utilsITK from module_mixins import ScriptedConfigModuleMixin class hessianDoG(ScriptedConfigModuleMixin, ModuleBase): """Calculates Hessian matrix of volume by convolution with second and cross derivatives of Gaussian kernel. $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.gaussianSigma = 0.7 self._config.normaliseAcrossScale = False configList = [ ('Gaussian sigma', 'gaussianSigma', 'base:float', 'text', 'Sigma in terms of image spacing.'), ('Normalise across scale', 'normaliseAcrossScale', 'base:bool', 'checkbox', 'Determine normalisation factor.')] ScriptedConfigModuleMixin.__init__(self, configList) # setup the pipeline g = itk.itkGradientMagnitudeRecursiveGaussianImageFilterF3F3_New() self._gradientMagnitude = g module_utilsITK.setupITKObjectProgress( self, g, 'itkGradientMagnitudeRecursiveGaussianImageFilter', 'Calculating gradient image') self._createWindow( {'Module (self)' : self, 'itkGradientMagnitudeRecursiveGaussianImageFilter' : self._gradientMagnitude}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gradientMagnitude def execute_module(self): self._gradientMagnitude.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._gradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._gradientMagnitude.GetOutput() def config_to_logic(self): self._gradientMagnitude.SetSigma(self._config.gaussianSigma) self._gradientMagnitude.SetNormalizeAcrossScale( self._config.normaliseAcrossScale) def logic_to_config(self): # durnit, there's no GetSigma(). Doh. self._config.normaliseAcrossScale = self._gradientMagnitude.\ GetNormalizeAcrossScale()
[ [ 1, 0, 0.0349, 0.0116, 0, 0.66, 0, 362, 0, 1, 0, 0, 362, 0, 0 ], [ 1, 0, 0.0465, 0.0116, 0, 0.66, 0.1667, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0581, 0.0116, 0, ...
[ "import fixitk as itk", "import gen_utils", "from module_base import ModuleBase", "import module_utils", "import module_utilsITK", "from module_mixins import ScriptedConfigModuleMixin", "class hessianDoG(ScriptedConfigModuleMixin, ModuleBase):\n \"\"\"Calculates Hessian matrix of volume by convolutio...
# EmphysemaViewerFrame by Corine Slagboom & Noeska Smit # Description # # Based on SkeletonAUIViewerFrame: # Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. import cStringIO from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx # wxPython 2.8.8.1 wx.aui bugs severely on GTK. See: # http://trac.wxwidgets.org/ticket/9716 # Until this is fixed, use this PyAUI to which I've added a # wx.aui compatibility layer. if wx.Platform == "__WXGTK__": from external import PyAUI wx.aui = PyAUI else: import wx.aui # one could have loaded a wxGlade created resource like this: #from resources.python import DICOMBrowserPanels #reload(DICOMBrowserPanels) class EmphysemaViewerFrame(wx.Frame): """wx.Frame child class used by Emphysemaviewer for its interface. This is an AUI-managed window, so we create the top-level frame, and then populate it with AUI panes. """ def __init__(self, parent, id=-1, title="", name=""): """Populates the menu and adds all required panels """ wx.Frame.__init__(self, parent, id=id, title=title, pos=wx.DefaultPosition, size=(1000,875), name=name) self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) file_menu = wx.Menu() self.id_file_open = wx.NewId() self.id_mask_open = wx.NewId() file_menu.Append(self.id_file_open, "&Open Volume\tCtrl-O", "Open a volume", wx.ITEM_NORMAL) file_menu.Append(self.id_mask_open, "&Open Mask\tCtrl-M", "Open a mask", wx.ITEM_NORMAL) self.id_mask_save = wx.NewId() file_menu.Append(self.id_mask_save, "&Save\tCtrl-S", "Save file", wx.ITEM_NORMAL) self.menubar.Append(file_menu, "&File") views_menu = wx.Menu() views_default_id = wx.NewId() views_menu.Append(views_default_id, "&Default\tCtrl-0", "Activate default view layout.", wx.ITEM_NORMAL) views_max_image_id = wx.NewId() views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1", "Activate maximum image view size layout.", wx.ITEM_NORMAL) self.menubar.Append(views_menu, "&Views") # tell FrameManager to manage this frame self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) self._mgr.AddPane(self._create_rwi_pane(), wx.aui.AuiPaneInfo(). Name("rwi").Caption("3D Renderer"). Center(). BestSize(wx.Size(600,800)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_controls_pane(), wx.aui.AuiPaneInfo(). Name("controls").Caption("Controls"). Top(). BestSize(wx.Size(1000,75)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_overlay_slices_pane(), wx.aui.AuiPaneInfo(). Name("overlay").Caption("Emphysema Overlay"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_original_slices_pane(), wx.aui.AuiPaneInfo(). Name("original").Caption("Original Scan"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self.SetMinSize(wx.Size(400, 300)) # first we save this default perspective with all panes # visible self._perspectives = {} self._perspectives['default'] = self._mgr.SavePerspective() # then we hide all of the panes except the renderer self._mgr.GetPane("controls").Hide() self._mgr.GetPane("overlay").Hide() self._mgr.GetPane("original").Hide() # save the perspective again self._perspectives['max_image'] = self._mgr.SavePerspective() # and put back the default perspective / view self._mgr.LoadPerspective(self._perspectives['default']) # finally tell the AUI manager to do everything that we've # asked self._mgr.Update() # we bind the views events here, because the functionality is # completely encapsulated in the frame and does not need to # round-trip to the DICOMBrowser main module. self.Bind(wx.EVT_MENU, self._handler_default_view, id=views_default_id) self.Bind(wx.EVT_MENU, self._handler_max_image_view, id=views_max_image_id) self.CreateStatusBar() self.SetStatusText("This is the statusbar ^^") def close(self): """Selfdestruct :) """ self.Destroy() def _create_rwi_pane(self): """Create a RenderWindowInteractor panel """ panel = wx.Panel(self, -1) self.rwi = wxVTKRenderWindowInteractor(panel, -1, (600,800)) self.button1 = wx.Button(panel, -1, "Reset Camera") self.button2 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button1) button_sizer.Add(self.button2) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.rwi, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_controls_pane(self): """Create a pane for the controls (containing the threshold sliders and buttons for setting default or calculated values) """ panel = wx.Panel(self, -1) self.upper_slider = wx.Slider(panel, -1, -950, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label = wx.StaticText(panel, -1, "Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label.SetForegroundColour(wx.Colour(127,0,255)) self.lower_slider = wx.Slider(panel, -1, -970, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label2 = wx.StaticText(panel, -1, "Severe Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label2.SetForegroundColour(wx.Colour(255,0,0)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.upper_slider) sizer.Add(self.label) sizer2 = wx.BoxSizer(wx.VERTICAL) sizer2.Add(self.lower_slider) sizer2.Add(self.label2) self.button5 = wx.Button(panel, -1, "-950 / -970 HU",pos=(8, 8), size=(175, 28)) self.button6 = wx.Button(panel, -1, "12% / 10% Lowest HU",pos=(8, 8), size=(175, 28)) button_sizer = wx.BoxSizer(wx.VERTICAL) button_sizer.Add(self.button5) button_sizer.Add(self.button6) slider_sizer = wx.BoxSizer(wx.HORIZONTAL) slider_sizer.Add(sizer) slider_sizer.Add(sizer2) slider_sizer.Add(button_sizer) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(slider_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_overlay_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.overlay = wxVTKRenderWindowInteractor(panel, -1, (400,400)) self.button3 = wx.Button(panel, -1, "Reset Camera") self.button4 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button3) button_sizer.Add(self.button4) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.overlay, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_original_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.original = wxVTKRenderWindowInteractor(panel, -1, (400,400)) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.original, 1, wx.EXPAND|wx.BOTTOM, 7) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def render(self): """Update embedded RWI, i.e. update the image. """ self.rwi.Render() self.overlay.Render() self.original.Render() def _handler_default_view(self, event): """Event handler for when the user selects View | Default from the main menu. """ self._mgr.LoadPerspective( self._perspectives['default']) def _handler_max_image_view(self, event): """Event handler for when the user selects View | Max Image from the main menu. """ self._mgr.LoadPerspective( self._perspectives['max_image'])
[ [ 1, 0, 0.0326, 0.0036, 0, 0.66, 0, 764, 0, 1, 0, 0, 764, 0, 0 ], [ 1, 0, 0.0362, 0.0036, 0, 0.66, 0.25, 201, 0, 1, 0, 0, 201, 0, 0 ], [ 1, 0, 0.0399, 0.0036, 0, 0....
[ "import cStringIO", "from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor", "import wx", "if wx.Platform == \"__WXGTK__\":\n from external import PyAUI\n wx.aui = PyAUI\nelse:\n import wx.aui", " from external import PyAUI", " wx.aui = PyAUI", " import wx.aui", ...
class EmphysemaViewer: kits = ['vtk_kit'] cats = ['Viewers'] help = """Module to visualize lungemphysema from a CT-thorax scan and a lung mask. EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The volume rendering shows 3 contours: the lungedges and 2 different contours of emphysema; a normal one and a severe one. There are two ways of setting the emphysema values. - The first way is choosing the 'default' values, which are literature-based. They are set on -950 HU (emphysema) and -970 HU (severe). - The other way is a computational way: The lowest 11% values, that are present in the data are marked as emphysema, the lowest 8,5% values are marked as severe emphysema. The theory behind this is the hypothesis that the histograms of emphysema patients differ from healthy people in a way that in emphysema patients there are relatively more lower values present. In both ways you can finetune the values, or completely change them (if you want to). After loading your image data and mask data, you can inspect the data and examine the severity of the emphysema of the patient. Controls:\n LMB: The left mouse button can be used to rotate objects in the 3D scene, or to poll Houndsfield Units in areas of interest (click and hold to see the values)\n RMB: For the slice viewers, you can set the window and level values by clicking and holding the right mouse button in a slice and moving your mouse. You can see the current window and level values in the bottom of the viewer. Outside of the slice, this zooms the camera in and out\n MMB: The middle mouse button enables stepping through the slices if clicked and held in the center of the slice. When clicking on de edges of a slice, this re-orients the entire slice. Outside of the slice, this pans the camera\n Scrollwheel: The scrollwheel can be used for zooming in and out of a scene, but also for sliceviewing if used with the CTRL- or SHIFT-key\n SHIFT: By holding the SHIFT-key, it is possible to use the mouse scrollwheel to scroll through the slices.\n CTRL: Holding the CTRL-key does the same, but enables stepping through the data in steps of 10 slices.\n """
[ [ 3, 0, 0.5185, 1, 0, 0.66, 0, 628, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.0741, 0.037, 1, 0.7, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 0.1111, 0.037, 1, 0.7, 0.5, ...
[ "class EmphysemaViewer:\n kits = ['vtk_kit']\n cats = ['Viewers']\n help = \"\"\"Module to visualize lungemphysema from a CT-thorax scan and a lung mask.\n\n EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The...
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # --------------------------------------- # Edited by Corine Slagboom & Noeska Smit to add possibility of adding overlay to the sliceviewer and some special synching. # And by edited we mean mutilated :) from module_kits.vtk_kit.utils import DVOrientationWidget import operator import vtk import wx class SyncSliceViewers: """Class to link a number of CMSliceViewer instances w.r.t. camera. FIXME: consider adding option to block certain slice viewers from participation. Is this better than just removing them? """ def __init__(self): # store all slice viewer instances that are being synced self.slice_viewers = [] # edit nnsmit self.slice_viewers2 = [] # end edit self.observer_tags = {} # if set to False, no syncing is done. # user is responsible for doing the initial sync with sync_all # after this variable is toggled from False to True self.sync = True def add_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this one only gets called for camera interaction (of course) t['istyle InteractionEvent'] = \ istyle.AddObserver('InteractionEvent', lambda o,e: self._observer_camera(slice_viewer)) # this gets call for all interaction with the slice # (cursoring, slice pushing, perhaps WL) for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) t['ipw%d WindowLevelEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('WindowLevelEvent', lambda o,e,i=idx: self._observer_window_level(slice_viewer,i)) self.slice_viewers.append(slice_viewer) # edit nnsmit # not the prettiest 'fix' in the book, but unfortunately short on time def add_slice_viewer2(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this gets call for all interaction with the slice for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) self.slice_viewers2.append(slice_viewer) #end edit def close(self): for sv in self.slice_viewers: self.remove_slice_viewer(sv) def _observer_camera(self, sv): """This observer will keep the cameras of all the participating slice viewers synched. It's only called when the camera is moved. """ if not self.sync: return cc = self.sync_cameras(sv) [sv.render() for sv in cc] def _observer_mousewheel_forward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelForward() vtk_o.InvokeEvent('InteractionEvent') def _observer_mousewheel_backward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelBackward() vtk_o.InvokeEvent('InteractionEvent') def _observer_ipw(self, slice_viewer, idx=0): """This is called whenever the user does ANYTHING with the IPW. """ if not self.sync: return cc = self.sync_ipws(slice_viewer, idx) [sv.render() for sv in cc] def _observer_window_level(self, slice_viewer, idx=0): """This is called whenever the window/level is changed. We don't have to render, because the SetWindowLevel() call does that already. """ if not self.sync: return self.sync_window_level(slice_viewer, idx) def remove_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: # first remove all observers that we might have added t = self.observer_tags[slice_viewer] istyle = slice_viewer.rwi.GetInteractorStyle() istyle.RemoveObserver( t['istyle InteractionEvent']) istyle.RemoveObserver( t['istyle MouseWheelForwardEvent']) istyle.RemoveObserver( t['istyle MouseWheelBackwardEvent']) for idx in range(3): ipw = slice_viewer.ipws[idx] ipw.RemoveObserver( t['ipw%d InteractionEvent' % (idx,)]) ipw.RemoveObserver( t['ipw%d WindowLevelEvent' % (idx,)]) # then delete our record of these observer tags del self.observer_tags[slice_viewer] # then delete our record of the slice_viewer altogether idx = self.slice_viewers.index(slice_viewer) del self.slice_viewers[idx] def sync_cameras(self, sv, dest_svs=None): """Sync all cameras to that of sv. Returns a list of changed SVs (so that you know which ones to render). """ cam = sv.renderer.GetActiveCamera() pos = cam.GetPosition() fp = cam.GetFocalPoint() vu = cam.GetViewUp() ps = cam.GetParallelScale() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if not other_sv is sv: other_ren = other_sv.renderer other_cam = other_ren.GetActiveCamera() other_cam.SetPosition(pos) other_cam.SetFocalPoint(fp) other_cam.SetViewUp(vu) # you need this too, else the parallel mode does not # synchronise. other_cam.SetParallelScale(ps) other_ren.UpdateLightsGeometryToFollowCamera() other_ren.ResetCameraClippingRange() changed_svs.append(other_sv) return changed_svs def sync_ipws(self, sv, idx=0, dest_svs=None): """Sync all slice positions to that of sv. Returns a list of changed SVs so that you know on which to call render. """ ipw = sv.ipws[idx] o,p1,p2 = ipw.GetOrigin(), \ ipw.GetPoint1(), ipw.GetPoint2() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: # nnsmit edit if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) # end edit other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() changed_svs.append(other_sv) # edit nnsmit # This fix is so nasty it makes me want to cry # TODO fix it properly :) if len(self.slice_viewers2) != 0: for other_sv in self.slice_viewers2: if other_sv is not sv: if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() other_sv.render() # end edit return changed_svs def sync_window_level(self, sv, idx=0, dest_svs=None): """Sync all window level settings with that of SV. Returns list of changed SVs: due to the SetWindowLevel call, these have already been rendered! """ ipw = sv.ipws[idx] w,l = ipw.GetWindow(), ipw.GetLevel() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: other_ipw = other_sv.ipws[idx] if w != other_ipw.GetWindow() or \ l != other_ipw.GetLevel(): other_ipw.SetWindowLevel(w,l,0) changed_svs.append(other_sv) return changed_svs def sync_all(self, sv, dest_svs=None): """Convenience function that performs all syncing possible of dest_svs to sv. It also take care of making only the necessary render calls. """ # FIXME: take into account all other slices too. c1 = set(self.sync_cameras(sv, dest_svs)) c2 = set(self.sync_ipws(sv, 0, dest_svs)) c3 = set(self.sync_window_level(sv, 0, dest_svs)) # we only need to call render on SVs that are in c1 or c2, but # NOT in c3, because WindowLevel syncing already does a # render. Use set operations for this: c4 = (c1 | c2) - c3 [isv.render() for isv in c4] ########################################################################### class CMSliceViewer: """Simple class for enabling 1 or 3 ortho slices in a 3D scene. """ def __init__(self, rwi, renderer): # nnsmit-edit self.overlay_active = 0; # end edit self.rwi = rwi self.renderer = renderer istyle = vtk.vtkInteractorStyleTrackballCamera() rwi.SetInteractorStyle(istyle) # we unbind the existing mousewheel handler so it doesn't # interfere rwi.Unbind(wx.EVT_MOUSEWHEEL) rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel) self.ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut = self.ipws[0].GetLookupTable() for ipw in self.ipws: ipw.SetInteractor(rwi) ipw.SetLookupTable(lut) # nnsmit-edit self.overlay_ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut2 = self.overlay_ipws[0].GetLookupTable() lut2.SetNumberOfTableValues(3) lut2.SetTableValue(0,0,0,0,0) lut2.SetTableValue(1,0.5,0,1,1) lut2.SetTableValue(2,1,0,0,1) lut2.Build() for ipw_overlay in self.overlay_ipws: ipw_overlay.SetInteractor(rwi) ipw_overlay.SetLookupTable(lut2) ipw_overlay.AddObserver('InteractionEvent', wx.EVT_MOUSEWHEEL) # now actually connect the sync_overlay observer for i,ipw in enumerate(self.ipws): ipw.AddObserver('InteractionEvent',lambda vtk_o, vtk_e, i=i: self.observer_sync_overlay(self.ipws,i)) # end edit # we only set the picker on the visible IPW, else the # invisible IPWs block picking! self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self.ipws[0].SetPicker(self.picker) self.outline_source = vtk.vtkOutlineCornerFilter() m = vtk.vtkPolyDataMapper() m.SetInput(self.outline_source.GetOutput()) a = vtk.vtkActor() a.SetMapper(m) a.PickableOff() self.outline_actor = a self.dv_orientation_widget = DVOrientationWidget(rwi) # this can be used by clients to store the current world # position self.current_world_pos = (0,0,0) self.current_index_pos = (0,0,0) # nnsmit-edit def observer_sync_overlay(self,ipws,ipw_idx): # get the primary IPW pipw = ipws[ipw_idx] # get the overlay IPW oipw = self.overlay_ipws[ipw_idx] # get plane geometry from primary o,p1,p2 = pipw.GetOrigin(),pipw.GetPoint1(),pipw.GetPoint2() # and apply to the overlay oipw.SetOrigin(o) oipw.SetPoint1(p1) oipw.SetPoint2(p2) oipw.UpdatePlacement() # end edit def close(self): self.set_input(None) self.dv_orientation_widget.close() self.set_overlay_input(None) def activate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(1) self.ipws[idx].SetPicker(self.picker) def deactivate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(0) self.ipws[idx].SetPicker(None) def get_input(self): return self.ipws[0].GetInput() def get_world_pos(self, image_pos): """Given image coordinates, return the corresponding world position. """ idata = self.get_input() if not idata: return None ispacing = idata.GetSpacing() iorigin = idata.GetOrigin() # calculate real coords world = map(operator.add, iorigin, map(operator.mul, ispacing, image_pos[0:3])) def set_perspective(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOff() def set_parallel(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOn() # nnsmit edit def set_opacity(self,opacity): lut = self.ipws[0].GetLookupTable() lut.SetAlphaRange(opacity, opacity) lut.Build() self.ipws[0].SetLookupTable(lut) # end edit def _handler_mousewheel(self, event): # event.GetWheelRotation() is + or - 120 depending on # direction of turning. if event.ControlDown(): delta = 10 elif event.ShiftDown(): delta = 1 else: # if user is NOT doing shift / control, we pass on to the # default handling which will give control to the VTK # mousewheel handlers. self.rwi.OnMouseWheel(event) return if event.GetWheelRotation() > 0: self._ipw1_delta_slice(+delta) else: self._ipw1_delta_slice(-delta) self.render() self.ipws[0].InvokeEvent('InteractionEvent') def _ipw1_delta_slice(self, delta): """Move to the delta slices fw/bw, IF the IPW is currently aligned with one of the axes. """ ipw = self.ipws[0] if ipw.GetPlaneOrientation() < 3: ci = ipw.GetSliceIndex() ipw.SetSliceIndex(ci + delta) def render(self): self.rwi.GetRenderWindow().Render() # nnsmit edit # synch those overlays: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) # end edit def reset_camera(self): self.renderer.ResetCamera() cam = self.renderer.GetActiveCamera() cam.SetViewUp(0,-1,0) def reset_to_default_view(self, view_index): """ @param view_index 2 for XY """ if view_index == 2: cam = self.renderer.GetActiveCamera() # then make sure it's up is the right way cam.SetViewUp(0,-1,0) # just set the X,Y of the camera equal to the X,Y of the # focal point. fp = cam.GetFocalPoint() cp = cam.GetPosition() if cp[2] < fp[2]: z = fp[2] + (fp[2] - cp[2]) else: z = cp[2] cam.SetPosition(fp[0], fp[1], z) # first reset the camera self.renderer.ResetCamera() # nnsmit edit # synch overlays as well: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): ipw_overlay.SetSliceIndex(0) for i, ipw in enumerate(self.ipws): ipw.SetWindowLevel(500,-800,0) self.render() # end edit def set_input(self, input): ipw = self.ipws[0] ipw.DisplayTextOn() if input == ipw.GetInput(): return if input is None: # remove outline actor, else this will cause errors when # we disable the IPWs (they call a render!) self.renderer.RemoveViewProp(self.outline_actor) self.outline_source.SetInput(None) self.dv_orientation_widget.set_input(None) for ipw in self.ipws: # argh, this disable causes a render ipw.SetEnabled(0) ipw.SetInput(None) else: self.outline_source.SetInput(input) self.renderer.AddViewProp(self.outline_actor) orientations = [2, 0, 1] active = [1, 0, 0] for i, ipw in enumerate(self.ipws): ipw.SetInput(input) ipw.SetWindowLevel(500,-800,0) ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) ipw.SetEnabled(active[i]) self.dv_orientation_widget.set_input(input) # nnsmit-edit # FIXME: Create pretty fix for this codeclone. def set_overlay_input(self, input): self.overlay_active = 1 ipw = self.overlay_ipws[0] if input == ipw.GetInput(): return if input is None: self.overlay_active = 0; for ipw_overlay in self.overlay_ipws: ipw_overlay.SetEnabled(0) ipw_overlay.SetInput(None) else: active = [1, 0, 0] orientations = [2, 0, 1] for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) ipw_overlay.SetInput(input) ipw_overlay.SetPlaneOrientation(orientations[i]) # axial ipw_overlay.SetEnabled(active[i]) self.render() # end edit
[ [ 1, 0, 0.0137, 0.0017, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.0154, 0.0017, 0, 0.66, 0.2, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 1, 0, 0.0172, 0.0017, 0, 0.6...
[ "from module_kits.vtk_kit.utils import DVOrientationWidget", "import operator", "import vtk", "import wx", "class SyncSliceViewers:\n \"\"\"Class to link a number of CMSliceViewer instances w.r.t.\n camera.\n\n FIXME: consider adding option to block certain slice viewers from\n participation. I...
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',))
[ [ 1, 0, 0.0526, 0.0526, 0, 0.66, 0, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0.5, 328, 0, 1, 0, 0, 328, 0, 0 ], [ 3, 0, 0.6053, 0.8421, 0, 0.6...
[ "from module_mixins import simpleVTKClassModuleBase", "import vtktud", "class imageKnutssonMapping(simpleVTKClassModuleBase):\n \"\"\"This is the minimum you need to wrap a single VTK object. This\n __doc__ string will be replaced by the __doc__ string of the encapsulated\n VTK object, i.e. vtkStrippe...
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()
[ [ 1, 0, 0.0125, 0.0125, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.025, 0.0125, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0375, 0.0125, 0, 0...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtktud", "class MyGlyph3D(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\...
# $Id: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $ class MyGaussian: kits = ['vtk_kit'] cats = ['User','Optic Flow'] keywords = ['gaussian', 'source']
[ [ 3, 0, 0.5625, 0.5, 0, 0.66, 0, 751, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.5, 0.125, 1, 0.87, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 0.625, 0.125, 1, 0.87, 0.5, ...
[ "class MyGaussian:\n kits = ['vtk_kit']\n cats = ['User','Optic Flow']\n keywords = ['gaussian', 'source']", " kits = ['vtk_kit']", " cats = ['User','Optic Flow']", " keywords = ['gaussian', 'source']" ]
# dummy __init__ so that this dir will be seen as package.
[]
[]
from module_mixins import simpleVTKClassModuleBase import vtktud class imageExtentUnionizer(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageExtentUnionizer(), 'Image Extent Unionizer.', ('vtkImageData',), ('vtkImageData',))
[ [ 1, 0, 0.0526, 0.0526, 0, 0.66, 0, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0.5, 328, 0, 1, 0, 0, 328, 0, 0 ], [ 3, 0, 0.6053, 0.8421, 0, 0.6...
[ "from module_mixins import simpleVTKClassModuleBase", "import vtktud", "class imageExtentUnionizer(simpleVTKClassModuleBase):\n \"\"\"This is the minimum you need to wrap a single VTK object. This\n __doc__ string will be replaced by the __doc__ string of the encapsulated\n VTK object, i.e. vtkStrippe...
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class gaussianKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a gaussian implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.standardDeviation = 1.0 self._config.support = 3.0 * self._config.standardDeviation # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the gaussian kernel (0-2).'), ('Standard deviation: ', 'standardDeviation', 'base:float', 'text', 'The standard deviation (width) of the gaussian kernel.'), ('Support: ', 'support', 'base:float', 'text', 'The support of the gaussian kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._gaussianKernel = vtktud.vtkGaussianKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkGaussianKernel' : self._gaussianKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gaussianKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._gaussianKernel def config_to_logic(self): # sanity check if self._config.standardDeviation < 0.0: self._config.standardDeviation = 0.0 if self._config.support < 0.0: self._config.support = 0.0 self._gaussianKernel.SetOrder( self._config.order ) self._gaussianKernel.SetStandardDeviation( self._config.standardDeviation ) self._gaussianKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._gaussianKernel.GetOrder() self._config.standardDeviation = self._gaussianKernel.GetStandardDeviation() self._config.support = self._gaussianKernel.GetSupport()
[ [ 1, 0, 0.0345, 0.0115, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.046, 0.0115, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0575, 0.0115, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtktud", "class gaussianKernel(ScriptedConfigModuleMixin, ModuleBase):\n \"\"\"First test of a gaussian implicit kernel\n \n $Revision: 1.1 $\n \"\"\"\n\n def __init__(s...
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx class myImageClip(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._clipper = vtk.vtkImageClip() module_utils.setup_vtk_object_progress(self, self._clipper, 'Reading PNG images.') self._config.outputWholeExtent = (0,-1,0,-1,0,-1) configList = [ ('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text', 'The size of the clip volume.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageClip' : self._clipper}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._clipper def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): if idx == 0: self._clipper.SetInput(inputStream) else: raise Exception def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._clipper.GetOutput() def logic_to_config(self): self._config.outputWholeExtent = self._clipper.GetOutputWholeExtent() def config_to_logic(self): self._clipper.SetOutputWholeExtent( self._config.outputWholeExtent, None ) def execute_module(self): self._clipper.Update()
[ [ 1, 0, 0.0149, 0.0149, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0299, 0.0149, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0448, 0.0149, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import wx", "class myImageClip(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n s...
# $Id$ class simplestVTKExample: kits = ['vtk_kit'] cats = ['User'] class isolated_points_check: kits = ['vtk_kit'] cats = ['User'] class testModule: kits = ['vtk_kit'] cats = ['User']
[ [ 3, 0, 0.2667, 0.2, 0, 0.66, 0, 969, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.2667, 0.0667, 1, 0.03, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 0.3333, 0.0667, 1, 0.03, ...
[ "class simplestVTKExample:\n kits = ['vtk_kit']\n cats = ['User']", " kits = ['vtk_kit']", " cats = ['User']", "class isolated_points_check:\n kits = ['vtk_kit']\n cats = ['User']", " kits = ['vtk_kit']", " cats = ['User']", "class testModule:\n kits = ['vtk_kit']\n cats = ...
from module_mixins import simpleVTKClassModuleBase import vtktud class imageCopyPad(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageCopyPad(), 'Extending image by copying border voxels.', ('vtkImageData',), ('vtkImageData',))
[ [ 1, 0, 0.0526, 0.0526, 0, 0.66, 0, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0.5, 328, 0, 1, 0, 0, 328, 0, 0 ], [ 3, 0, 0.6053, 0.8421, 0, 0.6...
[ "from module_mixins import simpleVTKClassModuleBase", "import vtktud", "class imageCopyPad(simpleVTKClassModuleBase):\n \"\"\"This is the minimum you need to wrap a single VTK object. This\n __doc__ string will be replaced by the __doc__ string of the encapsulated\n VTK object, i.e. vtkStripper in thi...
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()
[ [ 1, 0, 0.0132, 0.0132, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0263, 0.0132, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0395, 0.0132, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtktud", "import wx", "class imageSepConvolution(ScriptedConfigModuleMixin, ModuleBase):\n \"\"\"\n lksajflksjdf\n \"\"\"\n \n def __init__(self, module_manage...
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageCurvatureMagnitude(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageCurvatureMagnitude = vtktud.vtkImageCurvatureMagnitude() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageCurvatureMagnitude' : self._imageCurvatureMagnitude}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageCurvatureMagnitude def get_input_descriptions(self): return ('vtkImageData', 'vtkImageData', 'vtkImageData','vtkImageData', 'vtkImageData') def set_input(self, idx, inputStream): self._imageCurvatureMagnitude.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageCurvatureMagnitude.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageCurvatureMagnitude.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
[ [ 1, 0, 0.0143, 0.0143, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0286, 0.0143, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0429, 0.0143, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtktud", "class imageCurvatureMagnitude(ModuleBase, NoConfigModuleMixin):\n\n def __init__(self, module_manager):\n # initialise our base class\n Modul...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class DilateExample(ScriptedConfigModuleMixin, ModuleBase): """Performs a greyscale 3D dilation on the input. $Revision: 1.2 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() module_utils.setup_vtk_object_progress(self, self._imageDilate, 'Performing greyscale 3D dilation') self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkImageContinuousDilate3D' : self._imageDilate}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.logic_to_config() self.config_to_view() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageDilate def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return (self._imageDilate.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageDilate.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageDilate.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageDilate.Update() #def view(self, parent_window=None): # # if the window was visible already. just raise it # self._viewFrame.Show(True) # self._viewFrame.Raise()
[ [ 1, 0, 0.0116, 0.0116, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0233, 0.0116, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0349, 0.0116, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class DilateExample(ScriptedConfigModuleMixin, ModuleBase):\n\n \"\"\"Performs a greyscale 3D dilation on the input.\n \n $Revision: 1.2 $\n \"...
# $Id: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $ class DilateExample: kits = ['vtk_kit'] cats = ['User','Cartilage3D']
[ [ 3, 0, 0.8, 0.6, 0, 0.66, 0, 481, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.8, 0.2, 1, 0.27, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 1, 0.2, 1, 0.27, 1, 533, 0...
[ "class DilateExample:\n kits = ['vtk_kit']\n cats = ['User','Cartilage3D']", " kits = ['vtk_kit']", " cats = ['User','Cartilage3D']" ]
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',))
[ [ 1, 0, 0.0455, 0.0455, 0, 0.66, 0, 67, 0, 1, 0, 0, 67, 0, 0 ], [ 1, 0, 0.0909, 0.0455, 0, 0.66, 0.5, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 3, 0, 0.5227, 0.7273, 0, 0.66,...
[ "from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase", "import vtk", "class simplestVTKExample(SimpleVTKClassModuleBase):\n \"\"\"This is the minimum you need to wrap a single VTK object. This\n __doc__ string will be replaced by the __doc__ string of the encapsulated\n VTK object, i.e. vt...
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class cubicBCSplineKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a cubic B-Spline implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.support = 4.0 self._config.B = 0.0; self._config.C = 0.5; # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the cubic B-Spline kernel (0-2).'), ('B: ', 'B', 'base:float', 'text', 'B'), ('C: ', 'C', 'base:float', 'text', 'C'), ('Support: ', 'support', 'base:float', 'text', 'The support of the cubic B-Spline kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._cubicBCSplineKernel = vtktud.vtkCubicBCSplineKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkCubicBCSplineKernel' : self._cubicBCSplineKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._cubicBCSplineKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._cubicBCSplineKernel def config_to_logic(self): # sanity check if self._config.support < 0.0: self._config.support = 0.0 self._cubicBCSplineKernel.SetOrder( self._config.order ) self._cubicBCSplineKernel.SetB( self._config.B ) self._cubicBCSplineKernel.SetC( self._config.C ) self._cubicBCSplineKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._cubicBCSplineKernel.GetOrder() self._config.B = self._cubicBCSplineKernel.GetB() self._config.C = self._cubicBCSplineKernel.GetC() self._config.support = self._cubicBCSplineKernel.GetSupport()
[ [ 1, 0, 0.0333, 0.0111, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0444, 0.0111, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0556, 0.0111, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtktud", "class cubicBCSplineKernel(ScriptedConfigModuleMixin, ModuleBase):\n \"\"\"First test of a cubic B-Spline implicit kernel\n \n $Revision: 1.1 $\n \"\"\"\n\n def...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import wx import vtk class myTubeFilter(ScriptedConfigModuleMixin, ModuleBase): """Simple demonstration of ScriptedConfigModuleMixin-based wrapping of a single VTK object. It would of course be even easier using simpleVTKClassModuleBase. $Revision: 1.1 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._tubeFilter = vtk.vtkTubeFilter() module_utils.setup_vtk_object_progress(self, self._tubeFilter, 'Generating tubes.') self._config.NumberOfSides = 3 self._config.Radius = 0.01 configList = [ ('Number of sides:', 'NumberOfSides', 'base:int', 'text', 'Number of sides that the tube should have.'), ('Tube radius:', 'Radius', 'base:float', 'text', 'Radius of the generated tube.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkTubeFilter' : self._tubeFilter}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._tubeFilter def get_input_descriptions(self): return ('vtkPolyData lines',) def set_input(self, idx, inputStream): self._tubeFilter.SetInput(inputStream) def get_output_descriptions(self): return ('vtkPolyData tubes', ) def get_output(self, idx): return self._tubeFilter.GetOutput() def logic_to_config(self): self._config.NumberOfSides = self._tubeFilter.GetNumberOfSides() self._config.Radius = self._tubeFilter.GetRadius() def config_to_logic(self): self._tubeFilter.SetNumberOfSides(self._config.NumberOfSides) self._tubeFilter.SetRadius(self._config.Radius) def execute_module(self): self._tubeFilter.GetOutput().Update()
[ [ 1, 0, 0.012, 0.012, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0241, 0.012, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0361, 0.012, 0, 0.66...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import wx", "import vtk", "class myTubeFilter(ScriptedConfigModuleMixin, ModuleBase):\n\n \"\"\"Simple demonstration of ScriptedConfigModuleMixin-based\n wrappin...
import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import math class BSplineRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._create_pipeline() self._view_frame = None def _create_pipeline(self): interpolator = itk.LinearInterpolateImageFunction\ [itk.Image.F3, itk.D].New() metric = itk.MeanSquaresImageToImageMetric\ [itk.Image.F3, itk.Image.F3].New() optimizer = itk.LBFGSOptimizer.New() transform = itk.BSplineDeformableTransform[itk.D, 3, 3].New() r = itk.ImageRegistrationMethod[itk.Image.F3, itk.Image.F3].\ New( Interpolator=interpolator.GetPointer(), Metric=metric.GetPointer(), Optimizer=optimizer.GetPointer(), Transform=transform.GetPointer()) self._interpolator = interpolator self._metric = metric self._optimizer = optimizer self._transform = transform self._registration = r itk_kit.utils.setupITKObjectProgress( self, self._registration, 'BSpline Registration', 'Performing registration') itk_kit.utils.setupITKObjectProgress( self, self._optimizer, 'LBFGSOptimizer', 'Optimizing') def get_input_descriptions(self): return ('Fixed image', 'Moved image') def set_input(self, idx, input_stream): if idx == 0: self._fixed_image = input_stream self._registration.SetFixedImage(input_stream) else: self._moving_image = input_stream self._registration.SetMovingImage(input_stream) def get_output_descriptions(self): return ('BSpline Transform',) def get_output(self, idx): return self._registration.GetTransform() def execute_module(self): # itk.Size[3]() # itk.ImageRegion[3]() # we want a 1 node border on low x,y,z and a 2 node border on # high x,y,z; so if we want a bspline grid of 5x5x5, we need a # bspline region of 8x8x8 grid_size_on_image = [5,5,5] fi_region = self._fixed_image.GetBufferedRegion() self._registration.SetFixedImageRegion(fi_region) fi_size1 = fi_region.GetSize() fi_size = [fi_size1.GetElement(i) for i in range(3)] spacing = 3 * [0] origin = 3 * [0] for i in range(3): spacing[i] = self._fixed_image.GetSpacing().GetElement(i) * \ math.floor( (fi_size[i] - 1) / float(grid_size_on_image[i] - 1)) origin[i] = self._fixed_image.GetOrigin().GetElement(i) \ - spacing[i] self._transform.SetGridSpacing(spacing) self._transform.SetGridOrigin(origin) bspline_region = itk.ImageRegion[3]() bspline_region.SetSize([i + 3 for i in grid_size_on_image]) self._transform.SetGridRegion(bspline_region) num_params = self._transform.GetNumberOfParameters() params = itk.Array[itk.D](num_params) params.Fill(0.0) self._transform.SetParameters(params) self._registration.SetInitialTransformParameters( self._transform.GetParameters()) self._optimizer.SetGradientConvergenceTolerance( 0.05 ) self._optimizer.SetLineSearchAccuracy( 0.9 ) self._optimizer.SetDefaultStepLength( 1.5 ) self._optimizer.TraceOn() self._optimizer.SetMaximumNumberOfFunctionEvaluations( 1000 ) self._registration.Update() def logic_to_config(self): pass def config_to_logic(self): pass
[ [ 1, 0, 0.0083, 0.0083, 0, 0.66, 0, 77, 0, 1, 0, 0, 77, 0, 0 ], [ 1, 0, 0.0165, 0.0083, 0, 0.66, 0.2, 452, 0, 1, 0, 0, 452, 0, 0 ], [ 1, 0, 0.0248, 0.0083, 0, 0.66,...
[ "import itk", "import module_kits.itk_kit as itk_kit", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import math", "class BSplineRegistration(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n ModuleBase.__init__(self, ...
# dumy __init__ so this directory can function as a package
[]
[]
# 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()
[ [ 1, 0, 0.0494, 0.0123, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0617, 0.0123, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0741, 0.0123, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class surfaceToDistanceField(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n ...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import input_array_choice_mixin # need this for constants reload(input_array_choice_mixin) from input_array_choice_mixin import InputArrayChoiceMixin class warpPoints(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase): _defaultVectorsSelectionString = 'Default Active Vectors' _userDefinedString = 'User Defined' def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) InputArrayChoiceMixin.__init__(self) self._config.scaleFactor = 1 configList = [ ('Scale factor:', 'scaleFactor', 'base:float', 'text', 'The warping will be scaled by this factor'), ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice', 'The attribute that will be used as vectors for the warping.', (self._defaultVectorsSelectionString, self._userDefinedString))] self._warpVector = vtk.vtkWarpVector() ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkWarpVector' : self._warpVector}) module_utils.setup_vtk_object_progress(self, self._warpVector, 'Warping points.') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._warpVector def execute_module(self): self._warpVector.Update() if self.view_initialised: # second element in configuration list choice = self._getWidget(1) self.iac_execute_module(self._warpVector, choice, 0) def get_input_descriptions(self): return ('VTK points/polydata with vector attribute',) def set_input(self, idx, inputStream): if inputStream is None: self._warpVector.SetInputConnection(0, None) else: self._warpVector.SetInput(inputStream) def get_output_descriptions(self): return ('Warped data',) def get_output(self, idx): # we only return something if we have something if self._warpVector.GetNumberOfInputConnections(0): return self._warpVector.GetOutput() else: return None def logic_to_config(self): self._config.scaleFactor = self._warpVector.GetScaleFactor() # this will extract the possible choices self.iac_logic_to_config(self._warpVector, 0) def config_to_view(self): # first get our parent mixin to do its thing ScriptedConfigModuleMixin.config_to_view(self) # the vector choice is the second configTuple choice = self._getWidget(1) self.iac_config_to_view(choice) def config_to_logic(self): self._warpVector.SetScaleFactor(self._config.scaleFactor) self.iac_config_to_logic(self._warpVector, 0)
[ [ 1, 0, 0.0485, 0.0097, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0583, 0.0097, 0, 0.66, 0.1429, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.068, 0.0097, 0, 0...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import input_array_choice_mixin # need this for constants", "reload(input_array_choice_mixin)", "from input_array_choice_mixin import InputArrayChoiceMixin", "class warpPo...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class ICPTransform(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # this has no progress feedback self._icp = vtk.vtkIterativeClosestPointTransform() self._config.max_iterations = 50 self._config.mode = 'RigidBody' self._config.align_centroids = True config_list = [ ('Transformation mode:', 'mode', 'base:str', 'choice', 'Rigid: rotation + translation;\n' 'Similarity: rigid + isotropic scaling\n' 'Affine: rigid + scaling + shear', ('RigidBody', 'Similarity', 'Affine')), ('Maximum number of iterations:', 'max_iterations', 'base:int', 'text', 'Maximum number of iterations for ICP.'), ('Align centroids before start', 'align_centroids', 'base:bool', 'checkbox', 'Align centroids before iteratively optimizing closest points? (required for large relative translations)') ] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkIterativeClosestPointTransform' : self._icp}) self.sync_module_logic_with_config() def close(self): ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._icp ModuleBase.close(self) def get_input_descriptions(self): return ('source vtkPolyData', 'target vtkPolyData') def set_input(self, idx, input_stream): if idx == 0: self._icp.SetSource(input_stream) else: self._icp.SetTarget(input_stream) def get_output_descriptions(self): return ('Linear transform',) def get_output(self, idx): return self._icp def logic_to_config(self): self._config.mode = \ self._icp.GetLandmarkTransform().GetModeAsString() self._config.max_iterations = \ self._icp.GetMaximumNumberOfIterations() self._config.align_centroids = self._icp.GetStartByMatchingCentroids() def config_to_logic(self): lmt = self._icp.GetLandmarkTransform() if self._config.mode == 'RigidBody': lmt.SetModeToRigidBody() elif self._config.mode == 'Similarity': lmt.SetModeToSimilarity() else: lmt.SetModeToAffine() self._icp.SetMaximumNumberOfIterations( self._config.max_iterations) self._icp.SetStartByMatchingCentroids(self._config.align_centroids) def execute_module(self): self._module_manager.set_progress( 10, 'Starting ICP.') self._icp.Update() self._module_manager.set_progress( 100, 'ICP complete.')
[ [ 1, 0, 0.0543, 0.0109, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0652, 0.0109, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0761, 0.0109, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class ICPTransform(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n # this has no...
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()
[ [ 1, 0, 0.0127, 0.0127, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0253, 0.0127, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.038, 0.0127, 0, 0.66...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class appendPolyData(NoConfigModuleMixin, ModuleBase):\n _numInputs = 5\n \n def __init__(self, module_manager):\n # initialise our base class\n ...
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()
[ [ 1, 0, 0.0139, 0.0139, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0278, 0.0139, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0417, 0.0139, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class imageGreyDilate(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n Modu...
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()
[ [ 1, 0, 0.0137, 0.0137, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0274, 0.0137, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0411, 0.0137, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class ShephardMethod(ScriptedConfigModuleMixin, ModuleBase):\n\n \"\"\"Apply Shepard Method to input.\n \n \"\"\"\n \n def __init__(self, module_manager):\n ...
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class polyDataNormals(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._pdNormals = vtk.vtkPolyDataNormals() module_utils.setup_vtk_object_progress(self, self._pdNormals, 'Calculating normals') NoConfigModuleMixin.__init__( self, {'vtkPolyDataNormals' : self._pdNormals}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._pdNormals def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._pdNormals.SetInput(inputStream) def get_output_descriptions(self): return (self._pdNormals.GetOutput().GetClassName(), ) def get_output(self, idx): return self._pdNormals.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._pdNormals.Update() def streaming_execute_module(self): self._pdNormals.Update()
[ [ 1, 0, 0.0156, 0.0156, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0312, 0.0156, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0469, 0.0156, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class polyDataNormals(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init_...
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()
[ [ 1, 0, 0.0145, 0.0145, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.029, 0.0145, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0435, 0.0145, 0, 0...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import wx", "import vtk", "class imageFlip(NoConfigModuleMixin, ModuleBase):\n\n \n def __init__(self, module_manager):\n # initialise our base class\n M...
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()
[ [ 1, 0, 0.0139, 0.0139, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0278, 0.0139, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0417, 0.0139, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class imageGreyErode(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n Modul...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk OPS = ['add', 'subtract', 'multiply', 'divide', 'invert', 'sin', 'cos', 'exp', 'log', 'abs', 'sqr', 'sqrt', 'min', 'max', 'atan', 'atan2', 'multiply by k', 'add c', 'conjugate', 'complex multiply', 'replace c by k'] OPS_DICT = {} for i,o in enumerate(OPS): OPS_DICT[o] = i class imageMathematics(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageMath = vtk.vtkImageMathematics() self._imageMath.SetInput1(None) self._imageMath.SetInput2(None) module_utils.setup_vtk_object_progress(self, self._imageMath, 'Performing image math') self._config.operation = 'subtract' self._config.constantC = 0.0 self._config.constantK = 1.0 configList = [ ('Operation:', 'operation', 'base:str', 'choice', 'The operation that should be performed.', tuple(OPS_DICT.keys())), ('Constant C:', 'constantC', 'base:float', 'text', 'The constant C used in some operations.'), ('Constant K:', 'constantK', 'base:float', 'text', 'The constant C used in some operations.')] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageMathematics' : self._imageMath}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageMath def get_input_descriptions(self): return ('VTK Image Data 1', 'VTK Image Data 2') def set_input(self, idx, inputStream): if idx == 0: self._imageMath.SetInput1(inputStream) else: self._imageMath.SetInput2(inputStream) def get_output_descriptions(self): return ('VTK Image Data Result',) def get_output(self, idx): return self._imageMath.GetOutput() def logic_to_config(self): o = self._imageMath.GetOperation() # search for o in _operations for name,idx in OPS_DICT.items(): if idx == o: break if idx == o: self._config.operation = name else: # default is subtract self._config.operation = 'Subtract' self._config.constantC = self._imageMath.GetConstantC() self._config.constantK = self._imageMath.GetConstantK() def config_to_logic(self): idx = OPS_DICT[self._config.operation] self._imageMath.SetOperation(idx) self._imageMath.SetConstantC(self._config.constantC) self._imageMath.SetConstantK(self._config.constantK) def execute_module(self): self._imageMath.Update() def streaming_execute_module(self): self._imageMath.Update()
[ [ 1, 0, 0.0091, 0.0091, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0182, 0.0091, 0, 0.66, 0.125, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0273, 0.0091, 0, 0...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "OPS = ['add', 'subtract', 'multiply', 'divide', 'invert',\n 'sin', 'cos', 'exp', 'log', 'abs', 'sqr', 'sqrt', 'min',\n 'max', 'atan', 'atan2', ...
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class transformImageToTarget(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._reslicer = vtk.vtkImageReslice() self._probefilter = vtk.vtkProbeFilter() #This is retarded - we (sometimes, see below) need the padder #to get the image extent big enough to satisfy the probe filter. #No apparent logical reason, but it throws an exception if we don't. self._padder = vtk.vtkImageConstantPad() # initialise any mixins we might have NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageReslice' : self._reslicer}) module_utils.setup_vtk_object_progress(self, self._reslicer, 'Transforming image (Image Reslice)') module_utils.setup_vtk_object_progress(self, self._probefilter, 'Performing remapping (Probe Filter)') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # Rdisconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._reslicer del self._probefilter del self._padder def get_input_descriptions(self): return ('Source VTK Image Data', 'VTK Transform', 'Target VTK Image (supplies extent and spacing)') def set_input(self, idx, inputStream): if idx == 0: self._imagedata = inputStream self._reslicer.SetInput(self._imagedata) elif idx == 1: if inputStream == None: # disconnect self._transform = vtk.vtkMatrix4x4() else: # resliceTransform transforms the resampling grid, which # is equivalent to transforming the volume with its inverse self._transform = inputStream.GetMatrix() self._transform.Invert() #This is required else: if inputStream != None: self._outputVolumeExample = inputStream else: # define output extent same as input self._outputVolumeExample = self._imagedata def _convert_input(self): self._reslicer.SetInput(self._imagedata) self._reslicer.SetResliceAxes(self._transform) self._reslicer.SetAutoCropOutput(1) self._reslicer.SetInterpolationModeToCubic() spacing_i = self._imagedata.GetSpacing() isotropic_sp = min(min(spacing_i[0],spacing_i[1]),spacing_i[2]) self._reslicer.SetOutputSpacing(isotropic_sp, isotropic_sp, isotropic_sp) self._reslicer.Update() source = self._reslicer.GetOutput() source_extent = source.GetExtent() output_extent = self._outputVolumeExample.GetExtent() if (output_extent[0] < source_extent[0]) or (output_extent[2] < source_extent[2]) or (output_extent[4] < source_extent[4]): raise Exception('Output extent starts at lower index than source extent. Assumed that both should be zero?') elif (output_extent[1] > source_extent[1]) or (output_extent[3] > source_extent[3]) or (output_extent[5] > source_extent[5]): extX = max(output_extent[1], source_extent[1]) extY = max(output_extent[3], source_extent[3]) extZ = max(output_extent[5], source_extent[5]) padX = extX - source_extent[1] padY = extY - source_extent[3] padZ = extZ - source_extent[5] print 'Zero-padding source by (%d, %d, %d) voxels to force extent to match/exceed input''s extent. Lame, eh?' % (padX, padY, padZ) self._padder.SetInput(source) self._padder.SetConstant(0.0) self._padder.SetOutputWholeExtent(source_extent[0],extX,source_extent[2],extY,source_extent[4],extZ) self._padder.Update() source = self._padder.GetOutput() #dataType = self._outputVolumeExample.GetScalarType() #if dataType == 2 | dataType == 4: output = vtk.vtkImageData() output.DeepCopy(self._outputVolumeExample) self._probefilter.SetInput(output) self._probefilter.SetSource(source) self._probefilter.Update() self._output = self._probefilter.GetOutput() def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._output def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._convert_input()
[ [ 1, 0, 0.0079, 0.0079, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0157, 0.0079, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0236, 0.0079, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class transformImageToTarget(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(self, module_...
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import wx import vtk class imageGradientMagnitude(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageGradientMagnitude = vtk.vtkImageGradientMagnitude() self._imageGradientMagnitude.SetDimensionality(3) module_utils.setup_vtk_object_progress(self, self._imageGradientMagnitude, 'Calculating gradient magnitude') NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageGradientMagnitude' : self._imageGradientMagnitude}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageGradientMagnitude def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageGradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return (self._imageGradientMagnitude.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageGradientMagnitude.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageGradientMagnitude.Update()
[ [ 1, 0, 0.0147, 0.0147, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0294, 0.0147, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0441, 0.0147, 0, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import wx", "import vtk", "class imageGradientMagnitude(NoConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n ...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class RegionGrowing(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._image_threshold = vtk.vtkImageThreshold() # seedconnect wants unsigned char at input self._image_threshold.SetOutputScalarTypeToUnsignedChar() self._image_threshold.SetInValue(1) self._image_threshold.SetOutValue(0) self._seed_connect = vtk.vtkImageSeedConnectivity() self._seed_connect.SetInputConnectValue(1) self._seed_connect.SetOutputConnectedValue(1) self._seed_connect.SetOutputUnconnectedValue(0) self._seed_connect.SetInput(self._image_threshold.GetOutput()) module_utils.setup_vtk_object_progress(self, self._seed_connect, 'Performing region growing') module_utils.setup_vtk_object_progress(self, self._image_threshold, 'Thresholding data') # we'll use this to keep a binding (reference) to the passed object self._input_points = None # this will be our internal list of points self._seed_points = [] self._config._thresh_interval = 5 config_list = [ ('Auto threshold interval:', '_thresh_interval', 'base:float', 'text', 'Used to calculate automatic threshold (unit %).')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkImageSeedConnectivity' : self._seed_connect, 'vtkImageThreshold' : self._image_threshold}) self.sync_module_logic_with_config() def close(self): ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._image_threshold self._seed_connect.SetInput(None) del self._seed_connect ModuleBase.close(self) def get_input_descriptions(self): return ('vtkImageData', 'Seed points') def set_input(self, idx, input_stream): if idx == 0: # will work for None and not-None self._image_threshold.SetInput(input_stream) else: if input_stream != self._input_points: self._input_points = input_stream def get_output_descriptions(self): return ('Region growing result (vtkImageData)',) def get_output(self, idx): return self._seed_connect.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def execute_module(self): self._sync_to_input_points() # calculate automatic thresholds (we can only do this if we have # seed points and input data) ii = self._image_threshold.GetInput() if ii and self._seed_points: ii.Update() mins, maxs = ii.GetScalarRange() ranges = maxs - mins sums = 0.0 for seed_point in self._seed_points: # we assume 0'th component! v = ii.GetScalarComponentAsDouble( seed_point[0], seed_point[1], seed_point[2], 0) sums = sums + v means = sums / float(len(self._seed_points)) lower_thresh = means - \ float(self._config._thresh_interval / 100.0) * \ float(ranges) upper_thresh = means + \ float(self._config._thresh_interval / 100.0) * \ float(ranges) print "Auto thresh: ", lower_thresh, " - ", upper_thresh self._image_threshold.ThresholdBetween(lower_thresh, upper_thresh) self._seed_connect.Update() def _sync_to_input_points(self): # extract a list from the input points temp_list = [] if self._input_points: for i in self._input_points: temp_list.append(i['discrete']) if temp_list != self._seed_points: self._seed_points = temp_list self._seed_connect.RemoveAllSeeds() # we need to call Modified() explicitly as RemoveAllSeeds() # doesn't. AddSeed() does, but sometimes the list is empty at # this stage and AddSeed() isn't called. self._seed_connect.Modified() for seedPoint in self._seed_points: self._seed_connect.AddSeed(seedPoint[0], seedPoint[1], seedPoint[2])
[ [ 1, 0, 0.0345, 0.0069, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0414, 0.0069, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0483, 0.0069, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class RegionGrowing(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n self._image_...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class opening(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() self._imageErode = vtk.vtkImageContinuousErode3D() self._imageDilate.SetInput(self._imageErode.GetOutput()) 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') 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}) 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 def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageErode.SetInput(inputStream) def get_output_descriptions(self): return ('Opened image (vtkImageData)',) def get_output(self, idx): return self._imageDilate.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._imageErode.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): self._imageErode.Update() self._imageDilate.Update()
[ [ 1, 0, 0.012, 0.012, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0241, 0.012, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0361, 0.012, 0, 0.66, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class opening(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase._...
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)
[ [ 1, 0, 0.0156, 0.0156, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0312, 0.0156, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0469, 0.0156, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "class extractGrid(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk import numpy class FitEllipsoidToMask(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._input_data = None self._output_dict = {} # polydata pipeline to make crosshairs self._ls1 = vtk.vtkLineSource() self._ls2 = vtk.vtkLineSource() self._ls3 = vtk.vtkLineSource() self._append_pd = vtk.vtkAppendPolyData() self._append_pd.AddInput(self._ls1.GetOutput()) self._append_pd.AddInput(self._ls2.GetOutput()) self._append_pd.AddInput(self._ls3.GetOutput()) 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 ('VTK image data',) def set_input(self, idx, input_stream): self._input_data = input_stream def get_output_descriptions(self): return ('Ellipsoid (eigen-analysis) parameters', 'Crosshairs polydata') def get_output(self, idx): if idx == 0: return self._output_dict else: return self._append_pd.GetOutput() def execute_module(self): ii = self._input_data if not ii: return # now we need to iterate through the whole input data ii.Update() iorigin = ii.GetOrigin() ispacing = ii.GetSpacing() maxx, maxy, maxz = ii.GetDimensions() numpoints = 0 points = [] for z in range(maxz): wz = z * ispacing[2] + iorigin[2] for y in range(maxy): wy = y * ispacing[1] + iorigin[1] for x in range(maxx): v = ii.GetScalarComponentAsDouble(x,y,z,0) if v > 0.0: wx = x * ispacing[0] + iorigin[0] points.append((wx,wy,wz)) # covariance matrix ############################## if len(points) == 0: self._output_dict.update({'u' : None, 'v' : None, 'c' : None, 'axis_lengths' : None, 'radius_vectors' : None}) return # determine centre (x,y,z) points2 = numpy.array(points) centre = numpy.average(points2, 0) cx,cy,cz = centre # subtract centre from all points points_c = points2 - centre covariance = numpy.cov(points_c.transpose()) # eigen-analysis (u eigenvalues, v eigenvectors) u,v = numpy.linalg.eig(covariance) # estimate length at 2.0 * standard deviation in both directions axis_lengths = [4.0 * numpy.sqrt(eigval) for eigval in u] radius_vectors = numpy.zeros((3,3), float) for i in range(3): radius_vectors[i] = v[i] * axis_lengths[i] / 2.0 self._output_dict.update({'u' :u, 'v' : v, 'c' : (cx,cy,cz), 'axis_lengths' : tuple(axis_lengths), 'radius_vectors' : radius_vectors}) # now modify output polydata ######################### lss = [self._ls1, self._ls2, self._ls3] for i in range(len(lss)): half_axis = radius_vectors[i] #axis_lengths[i] / 2.0 * v[i] ca = numpy.array((cx,cy,cz)) lss[i].SetPoint1(ca - half_axis) lss[i].SetPoint2(ca + half_axis) self._append_pd.Update() def pca(points): """PCA factored out of execute_module and made N-D. not being used yet. points is a list of M N-d tuples. returns eigenvalues (u), eigenvectors (v), axis_lengths and radius_vectors. """ # for a list of M N-d tuples, returns an array with M rows and N # columns points2 = numpy.array(points) # determine centre by averaging over 0th axis (over rows) centre = numpy.average(points2, 0) # subtract centre from all points points_c = points2 - centre covariance = numpy.cov(points_c.transpose()) # eigen-analysis (u eigenvalues, v eigenvectors) u,v = numpy.linalg.eig(covariance) # estimate length at 2.0 * standard deviation in both directions axis_lengths = [4.0 * numpy.sqrt(eigval) for eigval in u] N = len(u) radius_vectors = numpy.zeros((N,N), float) for i in range(N): radius_vectors[i] = v[i] * axis_lengths[i] / 2.0 output_dict = {'u' :u, 'v' : v, 'c' : centre, 'axis_lengths' : tuple(axis_lengths), 'radius_vectors' : radius_vectors} return output_dict
[ [ 1, 0, 0.0314, 0.0063, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0377, 0.0063, 0, 0.66, 0.1667, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.044, 0.0063, 0, 0...
[ "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "import numpy", "class FitEllipsoidToMask(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__...
# 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)
[ [ 1, 0, 0.034, 0.0068, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0408, 0.0068, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0476, 0.0068, 0, 0.66...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import IntrospectModuleMixin", "import module_utils", "import vtk", "class resampleImage(IntrospectModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
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()
[ [ 1, 0, 0.0104, 0.0104, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0208, 0.0104, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0312, 0.0104, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "class extractHDomes(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n \n ModuleBase.__init__(self, module_...
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)
[ [ 1, 0, 0.0086, 0.0086, 0, 0.66, 0, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 1, 0, 0.0172, 0.0086, 0, 0.66, 0.0909, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 1, 0, 0.0259, 0.0086, 0, ...
[ "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'...
# $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()
[ [ 1, 0, 0.0288, 0.0096, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0385, 0.0096, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0481, 0.0096, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class extractImageComponents(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import input_array_choice_mixin reload(input_array_choice_mixin) from input_array_choice_mixin import InputArrayChoiceMixin ARRAY_IDX = 1 # scale vector glyph with scalar, vector magnitude, or separately for each # direction (using vector components), or don't scale at all # default is SCALE_BY_VECTOR = 1 glyphScaleMode = ['SCALE_BY_SCALAR', 'SCALE_BY_VECTOR', 'SCALE_BY_VECTORCOMPONENTS', 'DATA_SCALING_OFF'] glyphScaleModeTexts = ['Scale by scalar attribute', 'Scale by vector magnitude', 'Scale with x,y,z vector components', 'Use only scale factor'] # colour by scale (magnitude of scaled vector), by scalar or by vector # default: COLOUR_BY_VECTOR = 1 glyphColourMode = ['COLOUR_BY_SCALE', 'COLOUR_BY_SCALAR', 'COLOUR_BY_VECTOR'] glyphColourModeTexts = ['Colour by scale', 'Colour by scalar attribute', 'Colour by vector magnitude'] # which data should be used for scaling, orientation and indexing # default: USE_VECTOR = 0 glyphVectorMode = ['USE_VECTOR', 'USE_NORMAL', 'VECTOR_ROTATION_OFF'] glyphVectorModeTexts = ['Use vector', 'Use normal', 'Do not orient'] # we can use different glyph types in the same visualisation # default: INDEXING_OFF = 0 # (we're not going to use this right now) glyphIndexMode = ['INDEXING_OFF', 'INDEXING_BY_SCALAR', 'INDEXING_BY_VECTOR'] class glyphs(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) InputArrayChoiceMixin.__init__(self) self._config.scaling = True self._config.scaleFactor = 1 self._config.scaleMode = glyphScaleMode.index('SCALE_BY_VECTOR') self._config.colourMode = glyphColourMode.index('COLOUR_BY_VECTOR') self._config.vectorMode = glyphVectorMode.index('USE_VECTOR') self._config.mask_on_ratio = 5 self._config.mask_random = True configList = [ ('Scale glyphs:', 'scaling', 'base:bool', 'checkbox', 'Should the size of the glyphs be scaled?'), ('Scale factor:', 'scaleFactor', 'base:float', 'text', 'By how much should the glyph size be scaled if scaling is ' 'active?'), ('Scale mode:', 'scaleMode', 'base:int', 'choice', 'Should scaling be performed by vector, scalar or only factor?', glyphScaleModeTexts), ('Colour mode:', 'colourMode', 'base:int', 'choice', 'Colour is determined based on scalar or vector magnitude.', glyphColourModeTexts), ('Vector mode:', 'vectorMode', 'base:int', 'choice', 'Should vectors or normals be used for scaling and orientation?', glyphVectorModeTexts), ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice', 'The attribute that will be used as vectors for the warping.', (input_array_choice_mixin.DEFAULT_SELECTION_STRING,)), ('Mask on ratio:', 'mask_on_ratio', 'base:int', 'text', 'Every Nth point will be glyphed.'), ('Random masking:', 'mask_random', 'base:bool', 'checkbox', 'Pick random distribution of Nth points.')] self._mask_points = vtk.vtkMaskPoints() module_utils.setup_vtk_object_progress(self, self._mask_points, 'Masking points.') self._glyphFilter = vtk.vtkGlyph3D() asrc = vtk.vtkArrowSource() self._glyphFilter.SetSource(0, asrc.GetOutput()) self._glyphFilter.SetInput(self._mask_points.GetOutput()) module_utils.setup_vtk_object_progress(self, self._glyphFilter, 'Creating glyphs.') ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkGlyph3D' : self._glyphFilter}) 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._mask_points del self._glyphFilter def execute_module(self): self._glyphFilter.Update() if self.view_initialised: choice = self._getWidget(5) self.iac_execute_module(self._glyphFilter, choice, ARRAY_IDX) def get_input_descriptions(self): return ('VTK Vector dataset',) def set_input(self, idx, inputStream): self._mask_points.SetInput(inputStream) def get_output_descriptions(self): return ('3D glyphs',) def get_output(self, idx): return self._glyphFilter.GetOutput() def logic_to_config(self): self._config.scaling = bool(self._glyphFilter.GetScaling()) self._config.scaleFactor = self._glyphFilter.GetScaleFactor() self._config.scaleMode = self._glyphFilter.GetScaleMode() self._config.colourMode = self._glyphFilter.GetColorMode() self._config.vectorMode = self._glyphFilter.GetVectorMode() self._config.mask_on_ratio = \ self._mask_points.GetOnRatio() self._config.mask_random = bool(self._mask_points.GetRandomMode()) # this will extract the possible choices self.iac_logic_to_config(self._glyphFilter, ARRAY_IDX) def config_to_view(self): # first get our parent mixin to do its thing ScriptedConfigModuleMixin.config_to_view(self) # the vector choice is the second configTuple choice = self._getWidget(5) self.iac_config_to_view(choice) def config_to_logic(self): self._glyphFilter.SetScaling(self._config.scaling) self._glyphFilter.SetScaleFactor(self._config.scaleFactor) self._glyphFilter.SetScaleMode(self._config.scaleMode) self._glyphFilter.SetColorMode(self._config.colourMode) self._glyphFilter.SetVectorMode(self._config.vectorMode) self._mask_points.SetOnRatio(self._config.mask_on_ratio) self._mask_points.SetRandomMode(int(self._config.mask_random)) self.iac_config_to_logic(self._glyphFilter, ARRAY_IDX)
[ [ 1, 0, 0.0298, 0.006, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0357, 0.006, 0, 0.66, 0.0667, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0417, 0.006, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import input_array_choice_mixin", "reload(input_array_choice_mixin)", "from input_array_choice_mixin import InputArrayChoiceMixin", "ARRAY_IDX = 1", "glyphScaleMode = ['...
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()
[ [ 1, 0, 0.011, 0.011, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.022, 0.011, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.033, 0.011, 0, 0.66, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtktudoss", "class FastSurfaceToDistanceField(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initia...
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import vtkdevide class selectConnectedComponents(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._imageCast = vtk.vtkImageCast() self._imageCast.SetOutputScalarTypeToUnsignedLong() self._selectccs = vtkdevide.vtkSelectConnectedComponents() self._selectccs.SetInput(self._imageCast.GetOutput()) module_utils.setup_vtk_object_progress(self, self._selectccs, 'Marking selected components') module_utils.setup_vtk_object_progress(self, self._imageCast, 'Casting data to unsigned long') # we'll use this to keep a binding (reference) to the passed object self._inputPoints = None # this will be our internal list of points self._seedPoints = [] # now setup some defaults before our sync self._config.outputConnectedValue = 1 self._config.outputUnconnectedValue = 0 configList = [ ('Output Connected Value:', 'outputConnectedValue', 'base:int', 'text', 'This value will be assigned to all points in the ' 'selected connected components.'), ('Output Unconnected Value:', 'outputUnconnectedValue', 'base:int', 'text', 'This value will be assigned to all points NOT in the ' 'selected connected components.') ] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageCast' : self._imageCast, 'vtkSelectConnectedComponents' : self._selectccs}) 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._imageCast del self._selectccs def get_input_descriptions(self): return ('VTK Connected Components (unsigned long)', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: # will work for None and not-None self._imageCast.SetInput(inputStream) else: if inputStream != self._inputPoints: self._inputPoints = inputStream def get_output_descriptions(self): return ('Selected connected components (vtkImageData)',) def get_output(self, idx): return self._selectccs.GetOutput() def logic_to_config(self): self._config.outputConnectedValue = self._selectccs.\ GetOutputConnectedValue() self._config.outputUnconnectedValue = self._selectccs.\ GetOutputUnconnectedValue() def config_to_logic(self): self._selectccs.SetOutputConnectedValue(self._config.\ outputConnectedValue) self._selectccs.SetOutputUnconnectedValue(self._config.\ outputUnconnectedValue) def execute_module(self): self._sync_to_input_points() self._imageCast.Update() self._selectccs.Update() def _sync_to_input_points(self): # 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._selectccs.RemoveAllSeeds() # we need to call Modified() explicitly as RemoveAllSeeds() # doesn't. AddSeed() does, but sometimes the list is empty at # this stage and AddSeed() isn't called. self._selectccs.Modified() for seedPoint in self._seedPoints: self._selectccs.AddSeed(seedPoint[0], seedPoint[1], seedPoint[2])
[ [ 1, 0, 0.0078, 0.0078, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0155, 0.0078, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0233, 0.0078, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "class selectConnectedComponents(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n\n # call parent constructor\n ...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import vtk DEFAULT_SELECTION_STRING = 'Default active array' class InputArrayChoiceMixin: def __init__(self): self._config.vectorsSelection = DEFAULT_SELECTION_STRING self._config.input_array_names = [] self._config.actual_input_array = None def iac_logic_to_config(self, input_array_filter, array_idx=1): """VTK documentation doesn't really specify what the parameter to GetInputArrayInformation() expects. If you know, please let me know. It *seems* like it should match the one given to SetInputArrayToProcess. """ names = [] # this is the new way of checking input connections if input_array_filter.GetNumberOfInputConnections(0): pd = input_array_filter.GetInput().GetPointData() if pd: # get a list of attribute names for i in range(pd.GetNumberOfArrays()): names.append(pd.GetArray(i).GetName()) self._config.input_array_names = names inf = input_array_filter.GetInputArrayInformation(array_idx) vs = inf.Get(vtk.vtkDataObject.FIELD_NAME()) self._config.actual_input_array = vs def iac_config_to_view(self, choice_widget): # find out what the choices CURRENTLY are (except for the # default and the "user defined") choiceNames = [] ccnt = choice_widget.GetCount() for i in range(ccnt): # cast unicode strings to python default strings choice_string = str(choice_widget.GetString(i)) if choice_string != DEFAULT_SELECTION_STRING: choiceNames.append(choice_string) names = self._config.input_array_names if choiceNames != names: # this means things have changed, we have to rebuild # the choice choice_widget.Clear() choice_widget.Append(DEFAULT_SELECTION_STRING) for name in names: choice_widget.Append(name) if self._config.actual_input_array: si = choice_widget.FindString(self._config.actual_input_array) if si == -1: # string not found, that means the user has been playing # behind our backs, (or he's loading a valid selection # from DVN) so we add it to the choice as well choice_widget.Append(self._config.actual_input_array) choice_widget.SetStringSelection(self._config.actual_input_array) else: choice_widget.SetSelection(si) else: # no vector selection, so default choice_widget.SetSelection(0) def iac_config_to_logic(self, input_array_filter, array_idx=1, port=0, conn=0): """Makes sure 'vectorsSelection' from self._config is applied to the used vtkGlyph3D filter. For some filters (vtkGlyph3D) array_idx needs to be 1, for others (vtkWarpVector, vtkStreamTracer) it needs to be 0. """ if self._config.vectorsSelection == \ DEFAULT_SELECTION_STRING: # default: idx, port, connection, fieldassociation (points), name input_array_filter.SetInputArrayToProcess( array_idx, port, conn, 0, None) else: input_array_filter.SetInputArrayToProcess( array_idx, port, conn, 0, self._config.vectorsSelection) def iac_execute_module( self, input_array_filter, choice_widget, array_idx): """Hook to be called by the class that uses this mixin to ensure that after the first execute with a displayed view, the choice widget has been updated. See glyph module for an example. """ self.iac_logic_to_config(input_array_filter, array_idx) self.iac_config_to_view(choice_widget)
[ [ 1, 0, 0.0463, 0.0093, 0, 0.66, 0, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 14, 0, 0.0648, 0.0093, 0, 0.66, 0.5, 636, 1, 0, 0, 0, 0, 3, 0 ], [ 3, 0, 0.5278, 0.8981, 0, 0.66...
[ "import vtk", "DEFAULT_SELECTION_STRING = 'Default active array'", "class InputArrayChoiceMixin:\n\n def __init__(self):\n self._config.vectorsSelection = DEFAULT_SELECTION_STRING\n self._config.input_array_names = []\n self._config.actual_input_array = None\n\n def iac_logic_to_confi...
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk IMAGE_DATA = 0 POLY_DATA = 1 class StreamerVTK(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._image_data_streamer = vtk.vtkImageDataStreamer() self._poly_data_streamer = vtk.vtkPolyDataStreamer() NoConfigModuleMixin.__init__(self, {'module (self)' : self, 'vtkImageDataStreamer' : self._image_data_streamer, 'vtkPolyDataStreamer' : self._poly_data_streamer}) module_utils.setup_vtk_object_progress(self, self._image_data_streamer, 'Streaming image data') self._current_mode = None self.sync_module_logic_with_config() def close(self): NoConfigModuleMixin.close(self) del self._image_data_streamer del self._poly_data_streamer def get_input_descriptions(self): return ('VTK image or poly data',) def set_input(self, idx, input_stream): if hasattr(input_stream, 'IsA'): if input_stream.IsA('vtkImageData'): self._image_data_streamer.SetInput(input_stream) self._current_mode = IMAGE_DATA elif input_stream.IsA('vtkPolyData'): self._poly_data_streamer.SetInput(input_stream) self._current_mode = POLY_DATA def get_output_descriptions(self): return('VTK image or poly data',) def get_output(self, idx): if self._current_mode == IMAGE_DATA: return self._image_data_streamer.GetOutput() elif self._current_mode == POLY_DATA: return self._poly_data_streamer.GetOutput() else: return None def execute_module(self): pass def streaming_execute_module(self): sp = self._module_manager.get_app_main_config().streaming_pieces if self._current_mode == IMAGE_DATA: self._image_data_streamer.SetNumberOfStreamDivisions(sp) self._image_data_streamer.Update() elif self._current_mode == POLY_DATA: self._poly_data_streamer.SetNumberOfStreamDivisions(sp) self._poly_data_streamer.Update()
[ [ 1, 0, 0.0137, 0.0137, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0274, 0.0137, 0, 0.66, 0.1667, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0411, 0.0137, 0, ...
[ "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "IMAGE_DATA = 0", "POLY_DATA = 1", "class StreamerVTK(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\...
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()
[ [ 1, 0, 0.0135, 0.0135, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.027, 0.0135, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0405, 0.0135, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class transformVolumeData(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(self, module_man...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import wx import vtk class closing(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() self._imageErode = vtk.vtkImageContinuousErode3D() self._imageErode.SetInput(self._imageDilate.GetOutput()) 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') 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}) 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 def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return ('Closed image (vtkImageData)',) def get_output(self, idx): return self._imageErode.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): self._imageDilate.Update() self._imageErode.Update()
[ [ 1, 0, 0.0119, 0.0119, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0238, 0.0119, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0357, 0.0119, 0, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import wx", "import vtk", "class closing(ScriptedConfigModuleMixin, ModuleBase):\n\n \n def __init__(self, module_manager):\n # initialise our base class\...
# 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 PerturbPolyPoints: kits = ['vtk_kit'] cats = ['Filters'] keywords = ['polydata','move','perturb','random','noise','shuffle'] help = """Randomly perturbs each polydata vertex in a uniformly random direction""" 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. """
[ [ 3, 0, 0.0174, 0.0147, 0, 0.66, 0, 238, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.0128, 0.0018, 1, 0.48, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 0.0147, 0.0018, 1, 0.48, ...
[ "class appendPolyData:\n kits = ['vtk_kit']\n cats = ['Filters']\n help = \"\"\"DeVIDE encapsulation of the vtkAppendPolyDataFilter that\n enables us to combine multiple PolyData structures into one.\n\n DANGER WILL ROBINSON: contact the author, this module is BROKEN.\n \"\"\"", " kits = ['vt...
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class clipPolyData(NoConfigModuleMixin, ModuleBase): """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. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._clipPolyData = vtk.vtkClipPolyData() module_utils.setup_vtk_object_progress(self, self._clipPolyData, 'Calculating normals') NoConfigModuleMixin.__init__( self, {'vtkClipPolyData' : self._clipPolyData}) 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._clipPolyData def get_input_descriptions(self): return ('PolyData', 'Implicit Function') def set_input(self, idx, inputStream): if idx == 0: self._clipPolyData.SetInput(inputStream) else: self._clipPolyData.SetClipFunction(inputStream) def get_output_descriptions(self): return (self._clipPolyData.GetOutput().GetClassName(), ) def get_output(self, idx): return self._clipPolyData.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._clipPolyData.Update()
[ [ 1, 0, 0.0137, 0.0137, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0274, 0.0137, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0411, 0.0137, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class clipPolyData(NoConfigModuleMixin, ModuleBase):\n \"\"\"Given an input polydata and an implicitFunction, this will clip\n the polydata.\n\n All poi...
# Modified by FrancoisMalan 2011-12-06 so that it can handle an input with larger # extent than its source. Changes constitute the padder module and pad_source method import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class probeFilter(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # what a lame-assed filter, we have to make dummy inputs! # if we don't have a dummy input (but instead a None input) it # bitterly complains when we do a GetOutput() (it needs the input # to know the type of the output) - and GetPolyDataOutput() also # doesn't work. # NB: this does mean that our probeFilter NEEDS a PolyData as # probe geometry! ss = vtk.vtkSphereSource() ss.SetRadius(0) self._dummyInput = ss.GetOutput() #This is also retarded - we (sometimes, see below) need the "padder" #to get the image extent big enough to satisfy the probe filter. #No apparent logical reason, but it throws an exception if we don't. self._padder = vtk.vtkImageConstantPad() self._source = None self._input = None self._probeFilter = vtk.vtkProbeFilter() self._probeFilter.SetInput(self._dummyInput) NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkProbeFilter' : self._probeFilter}) module_utils.setup_vtk_object_progress(self, self._probeFilter, 'Mapping source on input') 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._probeFilter del self._dummyInput del self._padder del self._source del self._input def get_input_descriptions(self): return ('Input', 'Source') def set_input(self, idx, inputStream): if idx == 0: self._input = inputStream else: self._source = inputStream def get_output_descriptions(self): return ('Input with mapped source values',) def get_output(self, idx): return self._probeFilter.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 pad_source(self): input_extent = self._input.GetExtent() source_extent = self._source.GetExtent() if (input_extent[0] < source_extent[0]) or (input_extent[2] < source_extent[2]) or (input_extent[4] < source_extent[4]): raise Exception('Output extent starts at lower index than source extent. Assumed that both should be zero?') elif (input_extent[1] > source_extent[1]) or (input_extent[3] > source_extent[3]) or (input_extent[5] > source_extent[5]): extX = max(input_extent[1], source_extent[1]) extY = max(input_extent[3], source_extent[3]) extZ = max(input_extent[5], source_extent[5]) padX = extX - source_extent[1] padY = extY - source_extent[3] padZ = extZ - source_extent[5] print 'Zero-padding source by (%d, %d, %d) voxels to force extent to match/exceed input''s extent. Lame, eh?' % (padX, padY, padZ) self._padder.SetInput(self._source) self._padder.SetConstant(0.0) self._padder.SetOutputWholeExtent(source_extent[0],extX,source_extent[2],extY,source_extent[4],extZ) self._padder.Update() self._source.DeepCopy(self._padder.GetOutput()) def execute_module(self): if self._source.IsA('vtkImageData') and self._input.IsA('vtkImageData'): self.pad_source() self._probeFilter.SetInput(self._input) self._probeFilter.SetSource(self._source) self._probeFilter.Update()
[ [ 1, 0, 0.0345, 0.0086, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0431, 0.0086, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0517, 0.0086, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class probeFilter(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(se...
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import vtkdevide class imageFillHoles(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._imageBorderMask = vtkdevide.vtkImageBorderMask() # input image value for border self._imageBorderMask.SetBorderMode(1) # maximum of output for interior self._imageBorderMask.SetInteriorMode(3) self._imageGreyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D() # we're going to use the dual, instead of inverting mask and image, # performing greyscale reconstruction, and then inverting the result # again. (we should compare results though) self._imageGreyReconstruct.SetDual(1) # marker J is second input self._imageGreyReconstruct.SetInput( 1, self._imageBorderMask.GetOutput()) module_utils.setup_vtk_object_progress(self, self._imageBorderMask, 'Creating image mask.') module_utils.setup_vtk_object_progress(self, self._imageGreyReconstruct, 'Performing reconstruction.') self._config.holesTouchEdges = (0,0,0,0,0,0) configList = [ ('Allow holes to touch edges:', 'holesTouchEdges', 'tuple:int,6', 'text', 'Indicate which edges (minX, maxX, minY, maxY, minZ, maxZ) may\n' 'be touched by holes. In other words, a hole touching such an\n' 'edge will not be considered background and will be filled.') ] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageBorderMask' : self._imageBorderMask, 'vtkImageGreyReconstruct' : self._imageGreyReconstruct}) 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._imageBorderMask del self._imageGreyReconstruct def get_input_descriptions(self): return ('VTK Image Data to be filled',) def set_input(self, idx, inputStream): self._imageBorderMask.SetInput(inputStream) # first input of the reconstruction is the image self._imageGreyReconstruct.SetInput(0, inputStream) def get_output_descriptions(self): return ('Filled VTK Image Data', 'Marker') def get_output(self, idx): if idx == 0: return self._imageGreyReconstruct.GetOutput() else: return self._imageBorderMask.GetOutput() def logic_to_config(self): borders = self._imageBorderMask.GetBorders() # if there is a border, a hole touching that edge is no hole self._config.holesTouchEdges = [int(not i) for i in borders] def config_to_logic(self): borders = [int(not i) for i in self._config.holesTouchEdges] self._imageBorderMask.SetBorders(borders) def execute_module(self): self._imageGreyReconstruct.Update()
[ [ 1, 0, 0.0094, 0.0094, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0189, 0.0094, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0283, 0.0094, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "class imageFillHoles(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\...
# 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)
[ [ 1, 0, 0.0427, 0.0085, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0513, 0.0085, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0598, 0.0085, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import IntrospectModuleMixin", "import module_utils", "import vtk", "class imageGaussianSmooth(IntrospectModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class seedConnect(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._imageCast = vtk.vtkImageCast() self._imageCast.SetOutputScalarTypeToUnsignedChar() self._seedConnect = vtk.vtkImageSeedConnectivity() self._seedConnect.SetInput(self._imageCast.GetOutput()) module_utils.setup_vtk_object_progress(self, self._seedConnect, 'Performing region growing') module_utils.setup_vtk_object_progress(self, self._imageCast, 'Casting data to unsigned char') # we'll use this to keep a binding (reference) to the passed object self._inputPoints = None # this will be our internal list of points self._seedPoints = [] # now setup some defaults before our sync self._config.inputConnectValue = 1 self._config.outputConnectedValue = 1 self._config.outputUnconnectedValue = 0 config_list = [ ('Input connect value:', 'inputConnectValue', 'base:int', 'text', 'Points connected to seed points with this value will be ' 'included.'), ('Output connected value:', 'outputConnectedValue', 'base:int', 'text', 'Included points will get this value.'), ('Output unconnected value:', 'outputUnconnectedValue', 'base:int', 'text', 'Non-included points will get this value.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkImageSeedConnectivity' : self._seedConnect, 'vtkImageCast' : self._imageCast}) 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) self.set_input(1, None) # don't forget to call the close() method of the vtkPipeline mixin ScriptedConfigModuleMixin.close(self) # get rid of our reference del self._imageCast self._seedConnect.SetInput(None) del self._seedConnect def get_input_descriptions(self): return ('vtkImageData', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: # will work for None and not-None self._imageCast.SetInput(inputStream) else: if inputStream != self._inputPoints: self._inputPoints = inputStream def get_output_descriptions(self): return ('Region growing result (vtkImageData)',) def get_output(self, idx): return self._seedConnect.GetOutput() def logic_to_config(self): self._config.inputConnectValue = self._seedConnect.\ GetInputConnectValue() self._config.outputConnectedValue = self._seedConnect.\ GetOutputConnectedValue() self._config.outputUnconnectedValue = self._seedConnect.\ GetOutputUnconnectedValue() def config_to_logic(self): self._seedConnect.SetInputConnectValue(self._config.inputConnectValue) self._seedConnect.SetOutputConnectedValue(self._config.\ outputConnectedValue) self._seedConnect.SetOutputUnconnectedValue(self._config.\ outputUnconnectedValue) def execute_module(self): self._sync_to_input_points() self._seedConnect.Update() # we can't stream this module, as it needs up to date seed points # before it begins. def _sync_to_input_points(self): # 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._seedConnect.RemoveAllSeeds() # we need to call Modified() explicitly as RemoveAllSeeds() # doesn't. AddSeed() does, but sometimes the list is empty at # this stage and AddSeed() isn't called. self._seedConnect.Modified() for seedPoint in self._seedPoints: self._seedConnect.AddSeed(seedPoint[0], seedPoint[1], seedPoint[2])
[ [ 1, 0, 0.0078, 0.0078, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0155, 0.0078, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0233, 0.0078, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class seedConnect(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n\n # call parent constructor\n ModuleBa...
# dumy __init__ so this directory can function as a package
[]
[]
# dumy __init__ so this directory can function as a package
[]
[]
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()
[ [ 1, 0, 0.0093, 0.0093, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0187, 0.0093, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.028, 0.0093, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class imageMask(ScriptedConfigModuleMixin, ModuleBase):\n\n \n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(self, ...
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()
[ [ 1, 0, 0.008, 0.008, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.016, 0.008, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.024, 0.008, 0, 0.66, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class morphGradient(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBa...
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)
[ [ 1, 0, 0.0097, 0.0097, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0194, 0.0097, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0291, 0.0097, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class wsMeshSmooth(ScriptedConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(self, modul...
# dumy __init__ so this directory can function as a package
[]
[]
__author__ = 'Francois' # PerturbPolyPoints.py by Francois Malan - 2012-12-06 # Randomly perturbs each polydata vertex by a uniformly sampled magnitude and random direction from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import vtk import numpy import math import random class PerturbPolyPoints(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self.sync_module_logic_with_config() self._config.perturbation_magnitude = 0.15 #tolerance (distance) for determining if a point lies on a plane self._config.use_gaussian = False config_list = [ ('Perturbation Magnitude:', 'perturbation_magnitude', 'base:float', 'text', 'The magnitude of the perturbation (upperlimit for uniform distribution, or twice the standard deviation for Gaussian distribution). ' 'The 2x scaling ensures that the typical perturbation magnitudes are similar.'), ('Gaussian distribution:', 'use_gaussian', 'base:bool', 'checkbox', 'Should a Gaussian distribution be used instead of a uniform distribution?'), ] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self}) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of GUI ScriptedConfigModuleMixin.close(self) def set_input(self, idx, input_stream): if idx == 0: self.source_poly = input_stream def get_input_descriptions(self): return ('vtkPolyData', ) def get_output_descriptions(self): return ('vtkPolyData', ) def get_output(self, idx): return self.output_poly def _normalize(self, vector): length = math.sqrt(numpy.dot(vector, vector)) if length == 0: return numpy.array([1,0,0]) return vector / length def _perturb_points(self, poly, magnitude): assert isinstance(poly, vtk.vtkPolyData) points = poly.GetPoints() n = poly.GetNumberOfPoints() for i in range(n): point = points.GetPoint(i) vector = numpy.array([random.random(),random.random(),random.random()]) - 0.5 direction = self._normalize(vector) magnitude = 0.0 if not self._config.use_gaussian: magnitude = random.random() * self._config.perturbation_magnitude else: magnitude = random.gauss(0.0, self._config.perturbation_magnitude/2.0) vector = direction * magnitude newpoint = numpy.array(point) + vector points.SetPoint(i, (newpoint[0],newpoint[1],newpoint[2])) def logic_to_config(self): pass def config_to_logic(self): pass def execute_module(self): self.output_poly = vtk.vtkPolyData() self.output_poly.DeepCopy(self.source_poly) self._perturb_points(self.output_poly, self._config.perturbation_magnitude)
[ [ 14, 0, 0.0108, 0.0108, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0645, 0.0108, 0, 0.66, 0.1429, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0753, 0.0108, 0, 0...
[ "__author__ = 'Francois'", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import vtk", "import numpy", "import math", "import random", "class PerturbPolyPoints(ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # i...
# 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()
[ [ 1, 0, 0.0233, 0.0058, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0291, 0.0058, 0, 0.66, 0.1111, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0349, 0.0058, 0, ...
[ "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(\n NoConfigModuleMixin, ModuleBase):\n\n def __init__...
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import IntrospectModuleMixin import module_kits.vtk_kit import module_utils import vtk import wx from module_kits.misc_kit.devide_types import MedicalMetaData class EditMedicalMetaData(IntrospectModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._input_mmd = None self._output_mmd = MedicalMetaData() self._output_mmd.medical_image_properties = \ vtk.vtkMedicalImageProperties() self._output_mmd.direction_cosines = \ vtk.vtkMatrix4x4() # if the value (as it appears in mk.vtk_kit.constants.mipk) # appears in the dict, its value refers to the user supplied # value. when the user resets a field, that key is removed # from the dict self._config.new_value_dict = {} # this is the list of relevant properties self.mip_attr_l = \ module_kits.vtk_kit.constants.medical_image_properties_keywords # this will be used to keep track of changes made to the prop # grid before they are applied to the config self._grid_value_dict = {} self._view_frame = None self.sync_module_logic_with_config() def close(self): IntrospectModuleMixin.close(self) if self._view_frame is not None: self._view_frame.Destroy() ModuleBase.close(self) def get_input_descriptions(self): return ('Medical Meta Data',) def set_input(self, idx, input_stream): self._input_mmd = input_stream def get_output_descriptions(self): return ('Medical Meta Data',) def get_output(self, idx): return self._output_mmd def execute_module(self): # 1. if self._input_mmd is set, copy from self._input_mmd to # self._output_mmd (mmd.deep_copy checks for None) self._output_mmd.deep_copy(self._input_mmd) # 2. show input_mmd.medical_image_properties values in the # 'current values' column of the properties grid, only if this # module's view has already been shown self._grid_sync_with_current() # 3. apply only changed fields from interface mip = self._output_mmd.medical_image_properties for key,val in self._config.new_value_dict.items(): getattr(mip, 'Set%s' % (key))(val) def logic_to_config(self): pass def config_to_logic(self): pass def config_to_view(self): if self._config.new_value_dict != self._grid_value_dict: self._grid_value_dict.clear() self._grid_value_dict.update(self._config.new_value_dict) # now sync grid_value_dict to actual GUI self._grid_sync_with_dict() def view_to_config(self): if self._config.new_value_dict == self._grid_value_dict: # these two are still equal, so we don't have to do # anything. Return False to indicate that nothing has # changed. return False # transfer all values from grid_value_dict to dict in config self._config.new_value_dict.clear() self._config.new_value_dict.update(self._grid_value_dict) def view(self): # all fields touched by user are recorded. when we get a new # input, these fields are left untouched. mmmkay? 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 _create_view_frame(self): import modules.filters.resources.python.EditMedicalMetaDataViewFrame reload(modules.filters.resources.python.EditMedicalMetaDataViewFrame) self._view_frame = module_utils.instantiate_module_view_frame( self, self._module_manager, modules.filters.resources.python.EditMedicalMetaDataViewFrame.\ EditMedicalMetaDataViewFrame) # resize the grid and populate it with the various property # names grid = self._view_frame.prop_grid grid.DeleteRows(0, grid.GetNumberRows()) grid.AppendRows(len(self.mip_attr_l)) for i in range(len(self.mip_attr_l)): grid.SetCellValue(i, 0, self.mip_attr_l[i]) # key is read-only grid.SetReadOnly(i, 0) # current value is also read-only grid.SetReadOnly(i, 1) # use special method to set new value (this also takes # care of cell colouring) self._grid_set_new_val(i, None) # make sure the first column fits neatly around the largest # key name grid.AutoSizeColumn(0) def handler_grid_cell_change(event): # event is a wx.GridEvent r,c = event.GetRow(), event.GetCol() grid = self._view_frame.prop_grid key = self.mip_attr_l[r] gval = grid.GetCellValue(r,c) if gval == '': # this means the user doesn't want this field to be # changed, so we have to remove it from the # _grid_value_dict and we have to adapt the cell del self._grid_value_dict[key] # we only use this to change the cell background self._grid_set_new_val(r, gval, value_change=False) else: # the user has changed the value, so set it in the # prop dictionary self._grid_value_dict[key] = gval # and make sure the background colour is changed # appropriately. self._grid_set_new_val(r, gval, value_change=False) grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, handler_grid_cell_change) object_dict = { 'Module (self)' : self} module_utils.create_standard_object_introspection( self, self._view_frame, self._view_frame.view_frame_panel, object_dict, None) # we don't want enter to OK and escape to cancel, as these are # used for confirming and cancelling grid editing operations module_utils.create_eoca_buttons(self, self._view_frame, self._view_frame.view_frame_panel, ok_default=False, cancel_hotkey=False) # follow ModuleBase convention to indicate that we now have # a view self.view_initialised = True self._grid_sync_with_current() def _grid_set_new_val(self, row, val, value_change=True): grid = self._view_frame.prop_grid if not val is None: if value_change: # this does not trigger the CELL_CHANGE handler grid.SetCellValue(row, 2, val) grid.SetCellBackgroundColour(row, 2, wx.WHITE) else: if value_change: # this does not trigger the CELL_CHANGE handler grid.SetCellValue(row, 2, '') grid.SetCellBackgroundColour(row, 2, wx.LIGHT_GREY) def _grid_sync_with_current(self): """If there's an input_mmd, read out all its data and populate the current values column. This method is called by the execute_data and also by _create_view_frame. """ # we only do this if we have a view if not self.view_initialised: return if not self._input_mmd is None and \ self._input_mmd.__class__ == \ MedicalMetaData: mip = self._input_mmd.medical_image_properties grid = self._view_frame.prop_grid for i in range(len(self.mip_attr_l)): key = self.mip_attr_l[i] val = getattr(mip, 'Get%s' % (key,))() if val == None: val = '' grid.SetCellValue(i, 1, val) def _grid_sync_with_dict(self): """Synchronise property grid with _grid_value_dict ivar. """ for kidx in range(len(self.mip_attr_l)): key = self.mip_attr_l[kidx] val = self._grid_value_dict.get(key,None) self._grid_set_new_val(kidx, val)
[ [ 1, 0, 0.0211, 0.0042, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0253, 0.0042, 0, 0.66, 0.1429, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0295, 0.0042, 0, ...
[ "from module_base import ModuleBase", "from module_mixins import IntrospectModuleMixin", "import module_kits.vtk_kit", "import module_utils", "import vtk", "import wx", "from module_kits.misc_kit.devide_types import MedicalMetaData", "class EditMedicalMetaData(IntrospectModuleMixin, ModuleBase):\n ...
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk import vtkdevide class greyReconstruct(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._greyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D() NoConfigModuleMixin.__init__( self, {'Module (self)' : self, 'vtkImageGreyscaleReconstruct3D' : self._greyReconstruct}) module_utils.setup_vtk_object_progress( self, self._greyReconstruct, 'Performing greyscale reconstruction') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._greyReconstruct def get_input_descriptions(self): return ('Mask image I (VTK)', 'Marker image J (VTK)') def set_input(self, idx, inputStream): if idx == 0: self._greyReconstruct.SetInput1(inputStream) else: self._greyReconstruct.SetInput2(inputStream) def get_output_descriptions(self): return ('Reconstructed image (VTK)', ) def get_output(self, idx): return self._greyReconstruct.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._greyReconstruct.Update()
[ [ 1, 0, 0.0141, 0.0141, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0282, 0.0141, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0423, 0.0141, 0, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "class greyReconstruct(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ...
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()
[ [ 1, 0, 0.0161, 0.0161, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0323, 0.0161, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0484, 0.0161, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import module_utils", "import vtk", "class transformPolyData(NoConfigModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__ini...
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class ImageLogic(ScriptedConfigModuleMixin, ModuleBase): # get these values from vtkImageMathematics.h _operations = ('AND', 'OR', 'XOR', 'NAND', 'NOR', 'NOT', 'NOP') def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._image_logic = vtk.vtkImageLogic() module_utils.setup_vtk_object_progress(self, self._image_logic, 'Performing image logic') self._image_cast = vtk.vtkImageCast() module_utils.setup_vtk_object_progress( self, self._image_cast, 'Casting scalar type before image logic') self._config.operation = 0 self._config.output_true_value = 1.0 # 'choice' widget with 'base:int' type will automatically get cast # to index of selection that user makes. config_list = [ ('Operation:', 'operation', 'base:int', 'choice', 'The operation that should be performed.', tuple(self._operations)), ('Output true value:', 'output_true_value', 'base:float', 'text', 'Output voxels that are TRUE will get this value.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkImageLogic' : self._image_logic}) self.sync_module_logic_with_config() def 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._image_logic del self._image_cast def get_input_descriptions(self): return ('VTK Image Data 1', 'VTK Image Data 2') def set_input(self, idx, inputStream): if idx == 0: self._image_logic.SetInput(0, inputStream) else: self._image_cast.SetInput(inputStream) def get_output_descriptions(self): return ('VTK Image Data Result',) def get_output(self, idx): return self._image_logic.GetOutput() def logic_to_config(self): self._config.operation = self._image_logic.GetOperation() self._config.output_true_value = \ self._image_logic.GetOutputTrueValue() def config_to_logic(self): self._image_logic.SetOperation(self._config.operation) self._image_logic.SetOutputTrueValue(self._config.output_true_value) def execute_module(self): if self._image_logic.GetInput(0) is not None: self._image_cast.SetOutputScalarType( self._image_logic.GetInput(0).GetScalarType()) else: raise RuntimeError( 'ImageLogic requires at least its first input to run.') if self._image_cast.GetInput() is not None: # both inputs, make sure image_cast is connected self._image_logic.SetInput(1, self._image_cast.GetOutput()) else: # only one input, disconnect image_cast self._image_logic.SetInput(1, None) self._image_logic.Update()
[ [ 1, 0, 0.0442, 0.0088, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0531, 0.0088, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0619, 0.0088, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class ImageLogic(ScriptedConfigModuleMixin, ModuleBase):\n\n\n # get these values from vtkImageMathematics.h\n _operations = ('AND', 'OR', 'XOR', 'NAND', 'NOR', 'NOT', 'NO...
# 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)
[ [ 1, 0, 0.0286, 0.0071, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0357, 0.0071, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0429, 0.0071, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class MIPRender(\n ScriptedConfigModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n # initialise our base class\n ModuleBase.__init__(self, ...
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class imageMedian3D(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of structuring element in pixels.')] self._imageMedian3D = vtk.vtkImageMedian3D() ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkImageMedian3D' : self._imageMedian3D}) module_utils.setup_vtk_object_progress(self, self._imageMedian3D, 'Filtering with median') 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._imageMedian3D def execute_module(self): self._imageMedian3D.Update() def streaming_execute_module(self): self._imageMedian3D.Update() def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageMedian3D.SetInput(inputStream) def get_output_descriptions(self): return (self._imageMedian3D.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageMedian3D.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageMedian3D.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageMedian3D.SetKernelSize(ks[0], ks[1], ks[2])
[ [ 1, 0, 0.0143, 0.0143, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0286, 0.0143, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0429, 0.0143, 0, 0.6...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "class imageMedian3D(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n # initialise our base class\n Mo...
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)
[ [ 1, 0, 0.0079, 0.0079, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0159, 0.0079, 0, 0.66, 0.1667, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0238, 0.0079, 0, ...
[ "import gen_utils", "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "EMODES = { \n 1:'Point seeded regions',\n 2:'Cell seeded regions',\n 3:'Specified regions',\n 4:'Largest region',\n 5:'A...
import operator from module_base import ModuleBase from module_mixins import IntrospectModuleMixin import module_utils import vtk import vtkdevide import wx from module_mixins import ColourDialogMixin class shellSplatSimple(IntrospectModuleMixin, ColourDialogMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) ColourDialogMixin.__init__( self, module_manager.get_module_view_parent_window()) # setup the whole VTK pipeline that we're going to use self._createPipeline() # this is a list of all the objects in the pipeline and will # be used by the object and pipeline introspection self._object_dict = {'splatMapper' : self._splatMapper, 'opacity TF' : self._otf, 'colour TF' : self._ctf, 'volumeProp' : self._volumeProperty, 'volume' : self._volume} # setup some config defaults # for segmetented data self._config.threshold = 1.0 # bony kind of colour self._config.colour = (1.0, 0.937, 0.859) # high quality, doh self._config.renderMode = 0 # default. if you don't understand, forget about it. :) self._config.gradientImageIsGradient = 0 # create the gui 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) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # get rid of our reference del self._splatMapper del self._otf del self._ctf del self._volumeProperty del self._volume del self._object_dict ColourDialogMixin.close(self) # we have to call this mixin close so that all inspection windows # can be taken care of. They should be taken care of in anycase # when the viewFrame is destroyed, but we like better safe than # sorry IntrospectModuleMixin.close(self) # take care of our own window if self._view_frame is not None: self._view_frame.Destroy() del self._view_frame def get_input_descriptions(self): return ('input image data', 'optional gradient image data') def set_input(self, idx, inputStream): if idx == 0: if inputStream is None: # we have to disconnect this way self._splatMapper.SetInputConnection(0, None) else: self._splatMapper.SetInput(inputStream) else: self._splatMapper.SetGradientImageData(inputStream) def get_output_descriptions(self): return ('Shell splat volume (vtkVolume)',) def get_output(self, idx): return self._volume def logic_to_config(self): # we CAN'T derive the threshold and colour from the opacity and colour # transfer functions (or we could, but it'd be terribly dirty) # but fortunately we don't really have to - logiToConfig is only really # for cases where the logic could return config information different # from that we programmed it with # this we can get self._config.renderMode = self._splatMapper.GetRenderMode() # this too self._config.gradientImageIsGradient = self._splatMapper.\ GetShellExtractor().\ GetGradientImageIsGradient() def config_to_logic(self): # only modify the transfer functions if they've actually changed if self._otf.GetSize() != 2 or \ self._otf.GetValue(self._config.threshold - 0.1) != 0.0 or \ self._otf.GetValue(self._config.threshold) != 1.0: # make a step in the opacity transfer function self._otf.RemoveAllPoints() self._otf.AddPoint(self._config.threshold - 0.1, 0.0) self._otf.AddPoint(self._config.threshold, 1.0) # sample the two points and check that they haven't changed too much tfCol1 = self._ctf.GetColor(self._config.threshold) colDif1 = [i for i in map(abs, map(operator.sub, self._config.colour, tfCol1)) if i > 0.001] tfCol2 = self._ctf.GetColor(self._config.threshold - 0.1) colDif2 = [i for i in map(abs, map(operator.sub, (0,0,0), tfCol2)) if i > 0.001] if self._ctf.GetSize() != 2 or colDif1 or colDif2: # make a step in the colour transfer self._ctf.RemoveAllPoints() r,g,b = self._config.colour # setting two points is not necessary, but we play it safe self._ctf.AddRGBPoint(self._config.threshold - 0.1, 0, 0, 0) self._ctf.AddRGBPoint(self._config.threshold, r, g, b) # set the rendering mode self._splatMapper.SetRenderMode(self._config.renderMode) # set the gradientImageIsGradient thingy self._splatMapper.GetShellExtractor().SetGradientImageIsGradient( self._config.gradientImageIsGradient) def view_to_config(self): # get the threshold try: threshold = float(self._view_frame.thresholdText.GetValue()) except: # this means the user did something stupid, so we revert # to what's in the config - this will also turn up back # in the input box, as the DeVIDE arch automatically syncs # view with logic after having applied changes threshold = self._config.threshold # store it in the config self._config.threshold = threshold # convert the colour in the input box to something we can use colour = self._colourDialog.GetColourData().GetColour() defaultColourTuple = (colour.Red() / 255.0, colour.Green() / 255.0, colour.Blue() / 255.0) colourTuple = self._convertStringToColour( self._view_frame.colourText.GetValue(), defaultColourTuple) # and put it in the right place self._config.colour = colourTuple self._config.renderMode = self._view_frame.\ renderingModeChoice.GetSelection() self._config.gradientImageIsGradient = \ self._view_frame.\ gradientImageIsGradientCheckBox.\ GetValue() def config_to_view(self): self._view_frame.thresholdText.SetValue("%.2f" % (self._config.threshold)) self._view_frame.colourText.SetValue( "(%.3f, %.3f, %.3f)" % self._config.colour) self._view_frame.renderingModeChoice.SetSelection( self._config.renderMode) self._view_frame.gradientImageIsGradientCheckBox.SetValue( self._config.gradientImageIsGradient) def execute_module(self): self._splatMapper.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 _colourButtonCallback(self, evt): # first we have to translate the colour which is in the textentry # and set it in the colourDialog colour = self._colourDialog.GetColourData().GetColour() defaultColourTuple = (colour.Red() / 255.0, colour.Green() / 255.0, colour.Blue() / 255.0) colourTuple = self._convertStringToColour( self._view_frame.colourText.GetValue(), defaultColourTuple) self.setColourDialogColour(colourTuple) c = self.getColourDialogColour() if c: self._view_frame.colourText.SetValue( "(%.2f, %.2f, %.2f)" % c) def _convertStringToColour(self, colourString, defaultColourTuple): """Attempt to convert colourString into tuple representation. Returns colour tuple. No scaling is done, i.e. 3 elements in the str tuple are converted to floats and returned as a 3-tuple. """ try: colourTuple = eval(colourString) if type(colourTuple) != tuple or len(colourTuple) != 3: raise Exception colourTuple = tuple([float(i) for i in colourTuple]) except: # if we can't convert, we just let the colour chooser use # its previous default colourTuple = defaultColourTuple return colourTuple def _createPipeline(self): # setup our pipeline self._splatMapper = vtkdevide.vtkOpenGLVolumeShellSplatMapper() self._splatMapper.SetOmegaL(0.9) self._splatMapper.SetOmegaH(0.9) # high-quality rendermode self._splatMapper.SetRenderMode(0) self._otf = vtk.vtkPiecewiseFunction() self._otf.AddPoint(0.0, 0.0) self._otf.AddPoint(0.9, 0.0) self._otf.AddPoint(1.0, 1.0) self._ctf = vtk.vtkColorTransferFunction() self._ctf.AddRGBPoint(0.0, 0.0, 0.0, 0.0) self._ctf.AddRGBPoint(0.9, 0.0, 0.0, 0.0) self._ctf.AddRGBPoint(1.0, 1.0, 0.937, 0.859) self._volumeProperty = vtk.vtkVolumeProperty() self._volumeProperty.SetScalarOpacity(self._otf) self._volumeProperty.SetColor(self._ctf) self._volumeProperty.ShadeOn() self._volumeProperty.SetAmbient(0.1) self._volumeProperty.SetDiffuse(0.7) self._volumeProperty.SetSpecular(0.2) self._volumeProperty.SetSpecularPower(10) self._volume = vtk.vtkVolume() self._volume.SetProperty(self._volumeProperty) self._volume.SetMapper(self._splatMapper) def _createViewFrame(self): mm = self._module_manager # import/reload the viewFrame (created with wxGlade) mm.import_reload( 'modules.filters.resources.python.shellSplatSimpleFLTViewFrame') # this line is harmless due to Python's import caching, but we NEED # to do it so that the Installer knows that this devide module # requires it and so that it's available in this namespace. import modules.filters.resources.python.shellSplatSimpleFLTViewFrame self._view_frame = module_utils.instantiate_module_view_frame( self, mm, modules.filters.resources.python.shellSplatSimpleFLTViewFrame.\ shellSplatSimpleFLTViewFrame) # setup introspection with default everythings module_utils.create_standard_object_introspection( self, self._view_frame, self._view_frame.viewFramePanel, self._object_dict, None) # create and configure the standard ECAS buttons module_utils.create_eoca_buttons(self, self._view_frame, self._view_frame.viewFramePanel) # now we can finally do our own stuff to wx.EVT_BUTTON(self._view_frame, self._view_frame.colourButtonId, self._colourButtonCallback)
[ [ 1, 0, 0.0033, 0.0033, 0, 0.66, 0, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 1, 0, 0.0066, 0.0033, 0, 0.66, 0.125, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0099, 0.0033, 0, 0...
[ "import operator", "from module_base import ModuleBase", "from module_mixins import IntrospectModuleMixin", "import module_utils", "import vtk", "import vtkdevide", "import wx", "from module_mixins import ColourDialogMixin", "class shellSplatSimple(IntrospectModuleMixin,\n Colo...
# glenoidMouldDesigner.py copyright 2003 Charl P. Botha http://cpbotha.net/ # $Id$ # devide module that designs glenoid moulds by making use of insertion # axis and model of scapula # this module doesn't satisfy the event handling requirements of DeVIDE yet # if you call update on the output PolyData, this module won't know to # execute, because at the moment main processing takes place in Python-land # this will be so at least until we convert the processing to a vtkSource # child that has the PolyData as output or until we fake it with Observers # This is not critical. import math from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import operator import vtk class glenoidMouldDesign(ModuleBase, NoConfigModuleMixin): drillGuideInnerDiameter = 3 drillGuideOuterDiameter = 5 drillGuideHeight = 10 def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # and mixin NoConfigModuleMixin.__init__(self) self._inputPolyData = None self._inputPoints = None self._inputPointsOID = None self._giaGlenoid = None self._giaHumerus = None self._glenoidEdge = None self._outputPolyData = vtk.vtkPolyData() # create the frame and display it proudly! self._viewFrame = self._createViewFrame( {'Output Polydata': self._outputPolyData}) def close(self): # disconnect all inputs self.set_input(0, None) self.set_input(1, None) # take care of critical instances self._outputPolyData = None # mixin close NoConfigModuleMixin.close(self) def get_input_descriptions(self): return('Scapula vtkPolyData', 'Insertion axis (points)') def set_input(self, idx, inputStream): if idx == 0: # will work for None and not-None self._inputPolyData = inputStream else: if inputStream is not self._inputPoints: if self._inputPoints: self._inputPoints.removeObserver(self._inputPointsOID) if inputStream: self._inputPointsOID = inputStream.addObserver( self._inputPointsObserver) self._inputPoints = inputStream # initial update self._inputPointsObserver(None) def get_output_descriptions(self): return ('Mould design (vtkPolyData)',) # for now def get_output(self, idx): return self._outputPolyData def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): if self._giaHumerus and self._giaGlenoid and \ len(self._glenoidEdge) >= 6 and self._inputPolyData: # _glenoidEdgeImplicitFunction # construct eight planes with the insertion axis as mid-line # the planes should go somewhat further proximally than the # proximal insertion axis point # first calculate the distal-proximal glenoid insertion axis gia = tuple(map(operator.sub, self._giaGlenoid, self._giaHumerus)) # and in one swift move, we normalize it and get the magnitude giaN = list(gia) giaM = vtk.vtkMath.Normalize(giaN) # extend gia with a few millimetres giaM += 5 gia = tuple([giaM * i for i in giaN]) stuff = [] yN = [0,0,0] zN = [0,0,0] angleIncr = 2.0 * vtk.vtkMath.Pi() / 8.0 for i in range(4): angle = float(i) * angleIncr vtk.vtkMath.Perpendiculars(gia, yN, zN, angle) # each ridge is 1 cm (10 mm) - we'll change this later y = [10.0 * j for j in yN] origin = map(operator.add, self._giaHumerus, y) point1 = map(operator.add, origin, [-2.0 * k for k in y]) point2 = map(operator.add, origin, gia) # now create the plane source ps = vtk.vtkPlaneSource() ps.SetOrigin(origin) ps.SetPoint1(point1) ps.SetPoint2(point2) ps.Update() plane = vtk.vtkPlane() plane.SetOrigin(ps.GetOrigin()) plane.SetNormal(ps.GetNormal()) pdn = vtk.vtkPolyDataNormals() pdn.SetInput(self._inputPolyData) cut = vtk.vtkCutter() cut.SetInput(pdn.GetOutput()) cut.SetCutFunction(plane) cut.GenerateCutScalarsOn() cut.SetValue(0,0) cut.Update() contour = cut.GetOutput() # now find line segment closest to self._giaGlenoid pl = vtk.vtkPointLocator() pl.SetDataSet(contour) pl.BuildLocator() startPtId = pl.FindClosestPoint(self._giaGlenoid) cellIds = vtk.vtkIdList() contour.GetPointCells(startPtId, cellIds) twoLineIds = cellIds.GetId(0), cellIds.GetId(1) ptIds = vtk.vtkIdList() cellIds = vtk.vtkIdList() # we'll use these to store tuples: # (ptId, (pt0, pt1, pt2), (n0, n1, n2)) lines = [[],[]] lineIdx = 0 for startLineId in twoLineIds: # we have a startLineId, a startPtId and polyData curStartPtId = startPtId curLineId = startLineId onGlenoid = True offCount = 0 while onGlenoid: contour.GetCellPoints(curLineId, ptIds) if ptIds.GetNumberOfIds() != 2: print 'aaaaaaaaaaaaack!' ptId0 = ptIds.GetId(0) ptId1 = ptIds.GetId(1) nextPointId = [ptId0, ptId1]\ [bool(ptId0 == curStartPtId)] contour.GetPointCells(nextPointId, cellIds) if cellIds.GetNumberOfIds() != 2: print 'aaaaaaaaaaaaaaaack2!' cId0 = cellIds.GetId(0) cId1 = cellIds.GetId(1) nextLineId = [cId0, cId1]\ [bool(cId0 == curLineId)] # get the normal for the current point n = contour.GetPointData().GetNormals().GetTuple3( curStartPtId) # get the current point pt0 = contour.GetPoints().GetPoint(curStartPtId) # store the real ptid, point coords and normal lines[lineIdx].append((curStartPtId, tuple(pt0), tuple(n))) if vtk.vtkMath.Dot(giaN, n) > -0.9: # this means that this point could be falling off # the glenoid, let's make a note of the incident offCount += 1 # if the last N points have been "off" the glenoid, # it could mean we've really fallen off! if offCount >= 40: del lines[lineIdx][-40:] onGlenoid = False # get ready for next iteration curStartPtId = nextPointId curLineId = nextLineId # closes: while onGlenoid lineIdx += 1 # closes: for startLineId in twoLineIds # we now have two line lists... we have to combine them and # make sure it still constitutes one long line lines[0].reverse() edgeLine = lines[0] + lines[1] # do line extrusion resulting in a list of 5-element tuples, # each tuple representing the 5 3-d vertices of a "house" houses = self._lineExtrudeHouse(edgeLine, plane) # we will dump ALL the new points in here newPoints = vtk.vtkPoints() newPoints.SetDataType(contour.GetPoints().GetDataType()) # but we're going to create 5 lines idLists = [vtk.vtkIdList() for i in range(5)] for house in houses: for vertexIdx in range(5): ptId = newPoints.InsertNextPoint(house[vertexIdx]) idLists[vertexIdx].InsertNextId(ptId) # create a cell with the 5 lines newCellArray = vtk.vtkCellArray() for idList in idLists: newCellArray.InsertNextCell(idList) newPolyData = vtk.vtkPolyData() newPolyData.SetLines(newCellArray) newPolyData.SetPoints(newPoints) rsf = vtk.vtkRuledSurfaceFilter() rsf.CloseSurfaceOn() #rsf.SetRuledModeToPointWalk() rsf.SetRuledModeToResample() rsf.SetResolution(128, 4) rsf.SetInput(newPolyData) rsf.Update() stuff.append(rsf.GetOutput()) # also add two housies to cap all the ends capHousePoints = vtk.vtkPoints() capHouses = [] if len(houses) > 1: # we only cap if there are at least two houses capHouses.append(houses[0]) capHouses.append(houses[-1]) capHouseIdLists = [vtk.vtkIdList() for dummy in capHouses] for capHouseIdx in range(len(capHouseIdLists)): house = capHouses[capHouseIdx] for vertexIdx in range(5): ptId = capHousePoints.InsertNextPoint(house[vertexIdx]) capHouseIdLists[capHouseIdx].InsertNextId(ptId) if capHouseIdLists: newPolyArray = vtk.vtkCellArray() for capHouseIdList in capHouseIdLists: newPolyArray.InsertNextCell(capHouseIdList) capPolyData = vtk.vtkPolyData() capPolyData.SetPoints(capHousePoints) capPolyData.SetPolys(newPolyArray) # FIXME: put back stuff.append(capPolyData) # closes: for i in range(4) ap = vtk.vtkAppendPolyData() # copy everything to output (for testing) for thing in stuff: ap.AddInput(thing) #ap.AddInput(stuff[0]) # seems to be important for vtkAppendPolyData ap.Update() # now cut it with the FBZ planes fbzSupPlane = self._fbzCutPlane(self._fbzSup, giaN, self._giaGlenoid) fbzSupClip = vtk.vtkClipPolyData() fbzSupClip.SetClipFunction(fbzSupPlane) fbzSupClip.SetValue(0) fbzSupClip.SetInput(ap.GetOutput()) fbzInfPlane = self._fbzCutPlane(self._fbzInf, giaN, self._giaGlenoid) fbzInfClip = vtk.vtkClipPolyData() fbzInfClip.SetClipFunction(fbzInfPlane) fbzInfClip.SetValue(0) fbzInfClip.SetInput(fbzSupClip.GetOutput()) cylinder = vtk.vtkCylinder() cylinder.SetCenter([0,0,0]) # we make the cut-cylinder slightly larger... it's only there # to cut away the surface edges, so precision is not relevant cylinder.SetRadius(self.drillGuideInnerDiameter / 2.0) # cylinder is oriented along y-axis (0,1,0) - # we need to calculate the angle between the y-axis and the gia # 1. calc dot product (|a||b|cos(\phi)) cylDotGia = - giaN[1] # 2. because both factors are normals, angle == acos phiRads = math.acos(cylDotGia) # 3. cp is the vector around which gia can be turned to # coincide with the y-axis cp = [0,0,0] vtk.vtkMath.Cross((-giaN[0], -giaN[1], -giaN[2]), (0.0, 1.0, 0.0), cp) # this transform will be applied to all points BEFORE they are # tested on the cylinder implicit function trfm = vtk.vtkTransform() # it's premultiply by default, so the last operation will get # applied FIRST: # THEN rotate it around the cp axis so it's relative to the # y-axis instead of the gia-axis trfm.RotateWXYZ(phiRads * vtk.vtkMath.RadiansToDegrees(), cp[0], cp[1], cp[2]) # first translate the point back to the origin trfm.Translate(-self._giaGlenoid[0], -self._giaGlenoid[1], -self._giaGlenoid[2]) cylinder.SetTransform(trfm) cylinderClip = vtk.vtkClipPolyData() cylinderClip.SetClipFunction(cylinder) cylinderClip.SetValue(0) cylinderClip.SetInput(fbzInfClip.GetOutput()) cylinderClip.GenerateClipScalarsOn() ap2 = vtk.vtkAppendPolyData() ap2.AddInput(cylinderClip.GetOutput()) # this will cap the just cut polydata ap2.AddInput(self._capCutPolyData(fbzSupClip)) ap2.AddInput(self._capCutPolyData(fbzInfClip)) # thees one she dosint werk so gooood #ap2.AddInput(self._capCutPolyData(cylinderClip)) # now add outer guide cylinder, NOT capped cs1 = vtk.vtkCylinderSource() cs1.SetResolution(32) cs1.SetRadius(self.drillGuideOuterDiameter / 2.0) cs1.CappingOff() cs1.SetHeight(self.drillGuideHeight) # 15 mm height cs1.SetCenter(0,0,0) cs1.Update() # inner cylinder cs2 = vtk.vtkCylinderSource() cs2.SetResolution(32) cs2.SetRadius(self.drillGuideInnerDiameter / 2.0) cs2.CappingOff() cs2.SetHeight(self.drillGuideHeight) # 15 mm height cs2.SetCenter(0,0,0) cs2.Update() # top cap tc = vtk.vtkDiskSource() tc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0) tc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0) tc.SetCircumferentialResolution(64) tcTrfm = vtk.vtkTransform() # THEN flip it so that its centre-line is the y-axis tcTrfm.RotateX(90) # FIRST translate the disc tcTrfm.Translate(0,0,- self.drillGuideHeight / 2.0) tcTPDF = vtk.vtkTransformPolyDataFilter() tcTPDF.SetTransform(tcTrfm) tcTPDF.SetInput(tc.GetOutput()) # bottom cap bc = vtk.vtkDiskSource() bc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0) bc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0) bc.SetCircumferentialResolution(64) bcTrfm = vtk.vtkTransform() # THEN flip it so that its centre-line is the y-axis bcTrfm.RotateX(90) # FIRST translate the disc bcTrfm.Translate(0,0, self.drillGuideHeight / 2.0) bcTPDF = vtk.vtkTransformPolyDataFilter() bcTPDF.SetTransform(bcTrfm) bcTPDF.SetInput(bc.GetOutput()) tubeAP = vtk.vtkAppendPolyData() tubeAP.AddInput(cs1.GetOutput()) tubeAP.AddInput(cs2.GetOutput()) tubeAP.AddInput(tcTPDF.GetOutput()) tubeAP.AddInput(bcTPDF.GetOutput()) # we have to transform this fucker as well csTrfm = vtk.vtkTransform() # go half the height + 2mm upwards from surface drillGuideCentre = - 1.0 * self.drillGuideHeight / 2.0 - 2 cs1Centre = map(operator.add, self._giaGlenoid, [drillGuideCentre * i for i in giaN]) # once again, this is performed LAST csTrfm.Translate(cs1Centre) # and this FIRST (we have to rotate the OTHER way than for # the implicit cylinder cutting, because the cylinder is # transformed from y-axis to gia, not the other way round) csTrfm.RotateWXYZ(-phiRads * vtk.vtkMath.RadiansToDegrees(), cp[0], cp[1], cp[2]) # actually perform the transform csTPDF = vtk.vtkTransformPolyDataFilter() csTPDF.SetTransform(csTrfm) csTPDF.SetInput(tubeAP.GetOutput()) csTPDF.Update() ap2.AddInput(csTPDF.GetOutput()) ap2.Update() self._outputPolyData.DeepCopy(ap2.GetOutput()) def view(self): if not self._viewFrame.Show(True): self._viewFrame.Raise() def _buildHouse(self, startPoint, startPointNormal, cutPlane): """Calculate the vertices of a single house. Given a point on the cutPlane, the normal at that point and the cutPlane normal, this method will calculate and return the five points (including the start point) defining the upside-down house. The house is of course oriented with the point normal projected onto the cutPlane (then normalized again) and the cutPlaneNormal. p3 +--+ p2 | | p4 +--+ p1 \/ p0 startPoint, startPointNormal and cutPlaneNormal are all 3-element Python tuples. Err, this now returns 6 points. The 6th is a convenience so that our calling function can easily check for negative volume. See _lineExtrudeHouse. """ # xo = x - o # t = xo dot normal # h = x - t * normal t = vtk.vtkMath.Dot(startPointNormal, cutPlane.GetNormal()) houseNormal = map(operator.sub, startPointNormal, [t * i for i in cutPlane.GetNormal()]) vtk.vtkMath.Normalize(houseNormal) houseNormal3 = [3.0 * i for i in houseNormal] cutPlaneNormal1_5 = [1.5 * i for i in cutPlane.GetNormal()] mp = map(operator.add, startPoint, houseNormal3) p1 = tuple(map(operator.add, mp, cutPlaneNormal1_5)) p2 = tuple(map(operator.add, p1, houseNormal3)) p4 = tuple(map(operator.sub, mp, cutPlaneNormal1_5)) p3 = tuple(map(operator.add, p4, houseNormal3)) p5 = tuple(map(operator.add, mp, houseNormal3)) return (tuple(startPoint), p1, p2, p3, p4, p5) def _capCutPolyData(self, clipPolyData): # set a vtkCutter up exactly like the vtkClipPolyData cutter = vtk.vtkCutter() cutter.SetCutFunction(clipPolyData.GetClipFunction()) cutter.SetInput(clipPolyData.GetInput()) cutter.SetValue(0, clipPolyData.GetValue()) cutter.SetGenerateCutScalars(clipPolyData.GetGenerateClipScalars()) cutStripper = vtk.vtkStripper() cutStripper.SetInput(cutter.GetOutput()) cutStripper.Update() cutPolyData = vtk.vtkPolyData() cutPolyData.SetPoints(cutStripper.GetOutput().GetPoints()) cutPolyData.SetPolys(cutStripper.GetOutput().GetLines()) cpd = vtk.vtkCleanPolyData() cpd.SetInput(cutPolyData) tf = vtk.vtkTriangleFilter() tf.SetInput(cpd.GetOutput()) tf.Update() return tf.GetOutput() def _fbzCutPlane(self, fbz, giaN, giaGlenoid): """Calculate cut-plane corresponding to fbz. fbz is a list containing the two points defining a single FBZ (forbidden zone). giaN is the glenoid-insertion axis normal. giaGlenoid is the user-selected gia point on the glenoid. This method will return a cut-plane to enforce the given fbz such that giaGlenoid is on the inside of the implicit plane. """ fbzV = map(operator.sub, fbz[0], fbz[1]) fbzPN = [0,0,0] vtk.vtkMath.Cross(fbzV, giaN, fbzPN) vtk.vtkMath.Normalize(fbzPN) fbzPlane = vtk.vtkPlane() fbzPlane.SetOrigin(fbz[0]) fbzPlane.SetNormal(fbzPN) insideVal = fbzPlane.EvaluateFunction(giaGlenoid) if insideVal < 0: # eeep, it's outside, so flip the planeNormal fbzPN = [-1.0 * i for i in fbzPN] fbzPlane.SetNormal(fbzPN) return fbzPlane def _glenoidEdgeImplicitFunction(self, giaGlenoid, edgePoints): """Given the on-glenoid point of the glenoid insertion axis and 6 points (in sequence) around the glenoid edge, this will construct a vtk implicit function that can be used to check whether surface points are inside or outside. """ def _lineExtrudeHouse(self, edgeLine, cutPlane): """Extrude the house (square with triangle as roof) along edgeLine. edgeLine is a list of tuples where each tuple is: (ptId, (p0, p1, p2), (n0, n1, n2)) with P the point coordinate and N the normal at that point. The normal determines the orientation of the housy. The result is just a line extrusion, i.e. no surfaces yet. In order to do that, run the output (after it has been converted to a polydata) through a vtkRuledSurfaceFilter. This method returns a list of 5-element tuples. """ newEdgeLine = [] prevHousePoint0 = None prevHousePoint5 = None for point in edgeLine: housePoints = self._buildHouse(point[1], point[2], cutPlane) if prevHousePoint0: v0 = map(operator.sub, housePoints[0], prevHousePoint0) v1 = map(operator.sub, housePoints[5], prevHousePoint5) # bad-assed trick to test for negative volume if vtk.vtkMath.Dot(v0, v1) < 0.0: negativeVolume = 1 else: negativeVolume = 0 else: negativeVolume = 0 if not negativeVolume: newEdgeLine.append(housePoints[:5]) # we only store it as previous if we actually add it prevHousePoint0 = housePoints[0] prevHousePoint5 = housePoints[5] return newEdgeLine def _inputPointsObserver(self, obj): # extract a list from the input points if self._inputPoints: # extract the two points with labels 'GIA Glenoid' # and 'GIA Humerus' giaGlenoid = [i['world'] for i in self._inputPoints if i['name'] == 'GIA Glenoid'] giaHumerus = [i['world'] for i in self._inputPoints if i['name'] == 'GIA Humerus'] glenoidEdge = [i['world'] for i in self._inputPoints if i['name'] == 'Glenoid Edge Point'] if giaGlenoid and giaHumerus and \ len(glenoidEdge) >= 6: # we only apply these points to our internal parameters # if they're valid and if they're new self._giaGlenoid = giaGlenoid[0] self._giaHumerus = giaHumerus[0] self._glenoidEdge = glenoidEdge[:6]
[ [ 1, 0, 0.021, 0.0016, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0226, 0.0016, 0, 0.66, 0.2, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0242, 0.0016, 0, 0.66...
[ "import math", "from module_base import ModuleBase", "from module_mixins import NoConfigModuleMixin", "import operator", "import vtk", "class glenoidMouldDesign(ModuleBase, NoConfigModuleMixin):\n\n drillGuideInnerDiameter = 3\n drillGuideOuterDiameter = 5\n drillGuideHeight = 10\n\n def __ini...
# __init__.py by Charl P. Botha <cpbotha@ieee.org> # $Id$ # used to be module list, now dummy file
[]
[]
# $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()
[ [ 1, 0, 0.0297, 0.0099, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0396, 0.0099, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0495, 0.0099, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import wx", "class BMPReader(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
# $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()
[ [ 1, 0, 0.0435, 0.0145, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.058, 0.0145, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0725, 0.0145, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import FilenameViewModuleMixin", "import module_utils", "import vtk", "class vtpRDR(FilenameViewModuleMixin, ModuleBase):\n def __init__(self, module_manager):\n\n # call parent constructor\n ModuleBase.__init__(self, module_manager)...
# $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()
[ [ 1, 0, 0.0395, 0.0132, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0526, 0.0132, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0658, 0.0132, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import wx", "class metaImageRDR(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
# $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()
[ [ 1, 0, 0.03, 0.01, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.04, 0.01, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.05, 0.01, 0, 0.66, 0.4, ...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import wx", "class pngRDR(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
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()
[ [ 1, 0, 0.0102, 0.0102, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0204, 0.0102, 0, 0.66, 0.2, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0306, 0.0102, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin", "import module_utils", "import vtk", "import wx", "class JPEGReader(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n ...
# 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)
[ [ 1, 0, 0.0152, 0.003, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0182, 0.003, 0, 0.66, 0.1, 909, 0, 1, 0, 0, 909, 0, 0 ], [ 1, 0, 0.0228, 0.0061, 0, 0.66,...
[ "from module_base import ModuleBase", "from module_kits.misc_kit import misc_utils", "from module_mixins import \\\n IntrospectModuleMixin", "import module_utils", "import gdcm", "import vtk", "import vtkgdcm", "import wx", "from module_kits.misc_kit.devide_types import MedicalMetaData", "clas...
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class plyRDR(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._reader = vtk.vtkPLYReader() # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', '(Stanford) Polygon File Format (*.ply)|*.ply|All files (*)|*', {'vtkPLYReader': self._reader, 'Module (self)' : self}) module_utils.setup_vtk_object_progress( self, self._reader, 'Reading PLY PolyData') # 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 ('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 vtkPLYReader to try and execute if len(self._reader.GetFileName()): self._reader.Update()
[ [ 1, 0, 0.0423, 0.0141, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0563, 0.0141, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0704, 0.0141, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import FilenameViewModuleMixin", "import module_utils", "import vtk", "class plyRDR(FilenameViewModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n\n # call parent constructor\n ModuleBase.__init__(self, module_manage...
# 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 plyRDR: kits = ['vtk_kit'] cats = ['Readers'] help = """Reader for the Polygon File Format (Stanford Triangle Format) 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. """
[ [ 3, 0, 0.0656, 0.075, 0, 0.66, 0, 439, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.0375, 0.0063, 1, 0.82, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 1, 0.0437, 0.0063, 1, 0.82, ...
[ "class BMPReader:\n kits = ['vtk_kit']\n cats = ['Readers']\n help = \"\"\"Reads a series of BMP files.\n\n Set the file pattern by making use of the file browsing dialog. Replace\n the increasing index by a %d format specifier. %03d can be used for\n example, in which case %d will be replaced b...
# 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)
[ [ 1, 0, 0.0161, 0.0032, 0, 0.66, 0, 714, 0, 1, 0, 0, 714, 0, 0 ], [ 1, 0, 0.0194, 0.0032, 0, 0.66, 0.0909, 909, 0, 1, 0, 0, 909, 0, 0 ], [ 1, 0, 0.0226, 0.0032, 0, ...
[ "import gen_utils", "from module_kits.misc_kit import misc_utils", "import os", "from module_base import ModuleBase", "from module_mixins import \\\n IntrospectModuleMixin, FileOpenDialogModuleMixin", "import module_utils", "import stat", "import wx", "import vtk", "import vtkdevide", "impor...
# dumy __init__ so this directory can function as a package
[]
[]
# dumy __init__ so this directory can function as a package
[]
[]
# dumy __init__ so this directory can function as a package
[]
[]
# 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()
[ [ 1, 0, 0.0526, 0.0105, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.0632, 0.0105, 0, 0.66, 0.25, 676, 0, 2, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0737, 0.0105, 0, 0....
[ "from module_base import ModuleBase", "from module_mixins import ScriptedConfigModuleMixin, WX_OPEN", "import module_utils", "import vtk", "class TIFFReader(ScriptedConfigModuleMixin, ModuleBase):\n \n def __init__(self, module_manager):\n ModuleBase.__init__(self, module_manager)\n\n se...
# $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()
[ [ 1, 0, 0.0375, 0.0125, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.05, 0.0125, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0625, 0.0125, 0, 0.66...
[ "from module_base import ModuleBase", "from module_mixins import FilenameViewModuleMixin", "import module_utils", "import vtk", "class vtiRDR(FilenameViewModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n\n # call parent constructor\n ModuleBase.__init__(self, module_manage...
# $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()
[ [ 1, 0, 0.0435, 0.0145, 0, 0.66, 0, 745, 0, 1, 0, 0, 745, 0, 0 ], [ 1, 0, 0.058, 0.0145, 0, 0.66, 0.25, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 1, 0, 0.0725, 0.0145, 0, 0.6...
[ "from module_base import ModuleBase", "from module_mixins import FilenameViewModuleMixin", "import module_utils", "import vtk", "class vtkStructPtsRDR(FilenameViewModuleMixin, ModuleBase):\n\n def __init__(self, module_manager):\n\n # call parent constructor\n ModuleBase.__init__(self, modu...
# snippet to save polydata of all selected objects to disc, transformed with # the currently active object motion for that object. This snippet should be # run within a slice3dVWR introspection context. # $Id$ import os import tempfile import vtk className = obj.__class__.__name__ if className == 'slice3dVWR': # find all polydata objects so = obj._tdObjects._getSelectedObjects() polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and pd.GetClassName() == 'vtkPolyData'] # now find their actors objectsDict = obj._tdObjects._tdObjectsDict actors = [objectsDict[pd]['vtkActor'] for pd in polyDatas] # combining this with the previous statement is more effort than it's worth names = [objectsDict[pd]['objectName'] for pd in polyDatas] # now iterate through both, writing each transformed polydata trfm = vtk.vtkTransform() mtrx = vtk.vtkMatrix4x4() trfmPd = vtk.vtkTransformPolyDataFilter() trfmPd.SetTransform(trfm) vtpWriter = vtk.vtkXMLPolyDataWriter() vtpWriter.SetInput(trfmPd.GetOutput()) tempdir = tempfile.gettempdir() for pd,actor,name in zip(polyDatas,actors,names): actor.GetMatrix(mtrx) trfm.Identity() trfm.SetMatrix(mtrx) trfmPd.SetInput(pd) filename = os.path.join(tempdir, '%s.vtp' % (name,)) vtpWriter.SetFileName(filename) print "Writing %s." % (filename,) vtpWriter.Write() else: print "This snippet must be run from a slice3dVWR introspection window."
[ [ 1, 0, 0.1304, 0.0217, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1522, 0.0217, 0, 0.66, 0.25, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.1739, 0.0217, 0, 0....
[ "import os", "import tempfile", "import vtk", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n\n # find all polydata objects\n so = obj._tdObjects._getSelectedObjects()\n polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and\n pd.GetClassName() == 'vt...
import vtk className = obj.__class__.__name__ if className == 'slice3dVWR': rw = obj.threedFrame.threedRWI.GetRenderWindow() rw.SetStereoTypeToCrystalEyes() #rw.SetStereoTypeToRedBlue() rw.SetStereoRender(1) rw.Render() else: print "This snippet must be run from a slice3dVWR introspection window."
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 14, 0, 0.2308, 0.0769, 0, 0.66, 0.5, 131, 7, 0, 0, 0, 0, 0, 0 ], [ 4, 0, 0.6923, 0.6923, 0, 0.66...
[ "import vtk", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n rw = obj.threedFrame.threedRWI.GetRenderWindow()\n rw.SetStereoTypeToCrystalEyes()\n #rw.SetStereoTypeToRedBlue()\n rw.SetStereoRender(1)\n rw.Render()\n\nelse:", " rw = obj.threedFrame.threedRWI.GetRenderWi...
# $Id$ # to use a shader on an actor, do this first before export: # a = vtk.vtkRIBProperty() # a.SetVariable('Km', 'float') # a.SetParameter('Km', '1') # a.SetDisplacementShader('dented') # actor.SetProperty(a) import os import tempfile import vtk className = obj.__class__.__name__ if className == 'slice3dVWR': rw = obj._threedRenderer.GetRenderWindow() e = vtk.vtkRIBExporter() e.SetRenderWindow(rw) tempdir = tempfile.gettempdir() outputfilename = os.path.join(tempdir, 'slice3dVWRscene') e.SetFilePrefix(outputfilename) e.SetTexturePrefix(outputfilename) obj._orientationWidget.Off() e.Write() obj._orientationWidget.On() print "Wrote file to %s.rib." % (outputfilename,) else: print "You have to run this from the introspection window of a slice3dVWR."
[ [ 1, 0, 0.3226, 0.0323, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3548, 0.0323, 0, 0.66, 0.25, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.3871, 0.0323, 0, 0....
[ "import os", "import tempfile", "import vtk", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n rw = obj._threedRenderer.GetRenderWindow()\n\n e = vtk.vtkRIBExporter()\n e.SetRenderWindow(rw)\n tempdir = tempfile.gettempdir()\n outputfilename = os.path.join(tempdir, 'slic...
# this is an extremely simple example of a DeVIDE snippet # Open the Python shell (under Window in the Main Window), click on the # "Load Snippet" button and select this file. # it will print the directory where devide is installed and then show # the main application help print devideApp.get_appdir() devideApp.showHelp()
[ [ 8, 0, 0.8889, 0.1111, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 1, 0.1111, 0, 0.66, 1, 840, 3, 0, 0, 0, 0, 0, 1 ] ]
[ "print(devideApp.get_appdir())", "devideApp.showHelp()" ]
# this snippet will rotate the camera in the slice3dVWR that you have # selected whilst slowly increasing the isovalue of the marchingCubes that # you have selected and dump every frame as a PNG to the temporary directory # this is ideal for making movies of propagating surfaces in distance fields # 1. right click on a slice3dVWR in the graphEditor # 2. select "Mark Module" from the drop-down menu # 3. accept "slice3dVWR" as suggestion for the mark index name # 4. do the same for your marchingCubes (select 'marchingCubes' as index name) # 5. execute this snippet import os import tempfile import vtk import wx # get the slice3dVWR marked by the user sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR') mc = devideApp.ModuleManager.getMarkedModule('marchingCubes') if sv and mc: # bring the window to the front sv.view() # make sure it actually happens wx.Yield() w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(sv._threedRenderer.GetRenderWindow()) pngWriter = vtk.vtkPNGWriter() pngWriter.SetInput(w2i.GetOutput()) tempdir = tempfile.gettempdir() fprefix = os.path.join(tempdir, 'devideFrame') camera = sv._threedRenderer.GetActiveCamera() for i in range(160): print i mc._contourFilter.SetValue(0,i / 2.0) camera.Azimuth(5) sv.render3D() # make sure w2i knows it's a new image w2i.Modified() pngWriter.SetFileName('%s%03d.png' % (fprefix, i)) pngWriter.Write() print "The frames have been written as %s*.png." % (fprefix,) else: print "You have to mark a slice3dVWR module and a marchingCubes module!"
[ [ 1, 0, 0.24, 0.02, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.26, 0.02, 0, 0.66, 0.1667, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.28, 0.02, 0, 0.66, 0....
[ "import os", "import tempfile", "import vtk", "import wx", "sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')", "mc = devideApp.ModuleManager.getMarkedModule('marchingCubes')", "if sv and mc:\n # bring the window to the front\n sv.view()\n # make sure it actually happens\n wx.Yield(...
# convert old-style (up to DeVIDE 8.5) to new-style DVN network files # # usage: # load your old network in DeVIDE 8.5, then execute this snippet in # the main Python introspection window. To open the main Python # introspection window, select from the main DeVIDE menu: "Window | # Python Shell". In the window that opens, select "File | Open file # to current edit" from the main menu to load the file. Now select # "File | Run current edit" to execute. import ConfigParser import os import wx # used to translate from old-style attributes to new-style conn_trans = { 'sourceInstanceName' : 'source_instance_name', 'inputIdx' : 'input_idx', 'targetInstanceName' : 'target_instance_name', 'connectionType' : 'connection_type', 'outputIdx' : 'output_idx' } def save_network(pms_dict, connection_list, glyph_pos_dict, filename): """Given the serialised network representation as returned by ModuleManager._serialiseNetwork, write the whole thing to disk as a config-style DVN file. """ cp = ConfigParser.ConfigParser() # create a section for each module for pms in pms_dict.values(): sec = 'modules/%s' % (pms.instanceName,) cp.add_section(sec) cp.set(sec, 'module_name', pms.moduleName) cp.set(sec, 'module_config_dict', pms.moduleConfig.__dict__) cp.set(sec, 'glyph_position', glyph_pos_dict[pms.instanceName]) sec = 'connections' for idx, pconn in enumerate(connection_list): sec = 'connections/%d' % (idx,) cp.add_section(sec) attrs = pconn.__dict__.keys() for a in attrs: cp.set(sec, conn_trans[a], getattr(pconn, a)) cfp = file(filename, 'wb') cp.write(cfp) cfp.close() mm = devide_app.get_module_manager() mm.log_message('Wrote NEW-style network %s.' % (filename,)) def save_current_network(): """Pop up file selector to ask for filename, then save new-style network to that filename. """ ge = devide_app._interface._graph_editor filename = wx.FileSelector( "Choose filename for NEW-style DVN", ge._last_fileselector_dir, "", "dvn", "NEW-style DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*", wx.SAVE) if filename: # make sure it has a dvn extension if os.path.splitext(filename)[1] == '': filename = '%s.dvn' % (filename,) glyphs = ge._get_all_glyphs() pms_dict, connection_list, glyph_pos_dict = ge._serialiseNetwork(glyphs) save_network(pms_dict, connection_list, glyph_pos_dict, filename) save_current_network()
[ [ 1, 0, 0.1358, 0.0123, 0, 0.66, 0, 272, 0, 1, 0, 0, 272, 0, 0 ], [ 1, 0, 0.1481, 0.0123, 0, 0.66, 0.1667, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1605, 0.0123, 0, ...
[ "import ConfigParser", "import os", "import wx", "conn_trans = {\n 'sourceInstanceName' : 'source_instance_name',\n 'inputIdx' : 'input_idx',\n 'targetInstanceName' : 'target_instance_name',\n 'connectionType' : 'connection_type',\n 'outputIdx' : 'output_idx'\n }", ...
import vtk import wx className = obj.__class__.__name__ if className == 'slice3dVWR': sds = obj.sliceDirections.getSelectedSliceDirections() if len(sds) > 0: opacityText = wx.GetTextFromUser( 'Enter a new opacity value (0.0 to 1.0) for all selected ' 'slices.') opacity = -1.0 try: opacity = float(opacityText) except ValueError: pass if opacity < 0.0 or opacity > 1.0: print "Invalid opacity." else: for sd in sds: for ipw in sd._ipws: prop = ipw.GetTexturePlaneProperty() prop.SetOpacity(opacity) else: print "Please select the slices whose opacity you want to set." else: print "You have to run this from a slice3dVWR introspect window."
[ [ 1, 0, 0.0286, 0.0286, 0, 0.66, 0, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 1, 0, 0.0571, 0.0286, 0, 0.66, 0.3333, 666, 0, 1, 0, 0, 666, 0, 0 ], [ 14, 0, 0.1143, 0.0286, 0, ...
[ "import vtk", "import wx", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n\n sds = obj.sliceDirections.getSelectedSliceDirections()\n \n if len(sds) > 0:\n\n opacityText = wx.GetTextFromUser(\n 'Enter a new opacity value (0.0 to 1.0) for all selected '", " ...
# $Id$ import os import tempfile import vtk className = obj.__class__.__name__ if className == 'slice3dVWR': rw = obj._threedRenderer.GetRenderWindow() try: e = vtk.vtkGL2PSExporter() except AttributeError: print "Your VTK was compiled without GL2PS support." else: e.SetRenderWindow(rw) tempdir = tempfile.gettempdir() outputfilename = os.path.join(tempdir, 'slice3dVWRscene') e.SetFilePrefix(outputfilename) e.SetSortToBSP() e.SetDrawBackground(0) e.SetCompress(0) obj._orientationWidget.Off() e.Write() obj._orientationWidget.On() print "Wrote file to %s." % (outputfilename,) else: print "You have to run this from the introspection window of a slice3dVWR."
[ [ 1, 0, 0.1, 0.0333, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1333, 0.0333, 0, 0.66, 0.25, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.1667, 0.0333, 0, 0.66,...
[ "import os", "import tempfile", "import vtk", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n rw = obj._threedRenderer.GetRenderWindow()\n try:\n e = vtk.vtkGL2PSExporter()\n except AttributeError:\n print(\"Your VTK was compiled without GL2PS support.\")\n ...
# snippet to be ran in the introspection window of a slice3dVWR to # export the whole scene as a RIB file. Before you can do this, # both BACKGROUND_RENDERER and GRADIENT_BACKGROUND in slice3dVWR.py # should be set to False. obj._orientation_widget.Off() rw = obj._threedRenderer.GetRenderWindow() re = vtk.vtkRIBExporter() re.SetRenderWindow(rw) re.SetFilePrefix('/tmp/slice3dVWR') re.Write()
[ [ 8, 0, 0.5455, 0.0909, 0, 0.66, 0, 420, 3, 0, 0, 0, 0, 0, 1 ], [ 14, 0, 0.6364, 0.0909, 0, 0.66, 0.2, 273, 3, 0, 0, 0, 454, 10, 1 ], [ 14, 0, 0.7273, 0.0909, 0, 0....
[ "obj._orientation_widget.Off()", "rw = obj._threedRenderer.GetRenderWindow()", "re = vtk.vtkRIBExporter()", "re.SetRenderWindow(rw)", "re.SetFilePrefix('/tmp/slice3dVWR')", "re.Write()" ]
# EXPERIMENTAL. DO NOT USE UNLESS YOU ARE JORIK. (OR JORIS) import vtk className = obj.__class__.__name__ if className == 'slice3dVWR': ipw = obj.sliceDirections._sliceDirectionsDict.values()[0]._ipws[0] if ipw.GetInput(): mins, maxs = ipw.GetInput().GetScalarRange() else: mins, maxs = 1, 1000000 lut = vtk.vtkLookupTable() lut.SetTableRange(mins, maxs) lut.SetHueRange(0.1, 1.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) lut.SetAlphaRange(1.0, 1.0) lut.Build() ipw.SetUserControlledLookupTable(1) ipw.SetLookupTable(lut) else: print "You have to mark a slice3dVWR module!"
[ [ 1, 0, 0.1111, 0.037, 0, 0.66, 0, 665, 0, 1, 0, 0, 665, 0, 0 ], [ 14, 0, 0.1852, 0.037, 0, 0.66, 0.5, 131, 7, 0, 0, 0, 0, 0, 0 ], [ 4, 0, 0.6111, 0.8148, 0, 0.66, ...
[ "import vtk", "className = obj.__class__.__name__", "if className == 'slice3dVWR':\n ipw = obj.sliceDirections._sliceDirectionsDict.values()[0]._ipws[0]\n \n if ipw.GetInput():\n mins, maxs = ipw.GetInput().GetScalarRange()\n else:\n mins, maxs = 1, 1000000", " ipw = obj.sliceDire...
# to use this code: # 1. load into slice3dVWR introspection window # 2. execute with ctrl-enter or File | Run current edit # 3. in the bottom window type lm1 = get_lookmark() # 4. do stuff # 5. to restore lookmark, do set_lookmark(lm1) # keep on bugging me to: # 1. fix slice3dVWR # 2. build this sort of functionality into the GUI # cpbotha def get_plane_infos(): # get out all plane orientations and normals plane_infos = [] for sd in obj.sliceDirections._sliceDirectionsDict.values(): # each sd has at least one IPW ipw = sd._ipws[0] plane_infos.append((ipw.GetOrigin(), ipw.GetPoint1(), ipw.GetPoint2(), ipw.GetWindow(), ipw.GetLevel())) return plane_infos def set_plane_infos(plane_infos): # go through existing sliceDirections, sync if info available sds = obj.sliceDirections._sliceDirectionsDict.values() for i in range(len(sds)): sd = sds[i] if i < len(plane_infos): pi = plane_infos[i] ipw = sd._ipws[0] ipw.SetOrigin(pi[0]) ipw.SetPoint1(pi[1]) ipw.SetPoint2(pi[2]) ipw.SetWindowLevel(pi[3], pi[4], 0) ipw.UpdatePlacement() sd._syncAllToPrimary() def get_camera_info(): cam = obj._threedRenderer.GetActiveCamera() p = cam.GetPosition() vu = cam.GetViewUp() fp = cam.GetFocalPoint() ps = cam.GetParallelScale() return (p, vu, fp, ps) def get_lookmark(): return (get_plane_infos(), get_camera_info()) def set_lookmark(lookmark): # first setup the camera ci = lookmark[1] cam = obj._threedRenderer.GetActiveCamera() cam.SetPosition(ci[0]) cam.SetViewUp(ci[1]) cam.SetFocalPoint(ci[2]) # required for parallel projection cam.SetParallelScale(ci[3]) # also needed to adapt correctly to new camera ren = obj._threedRenderer ren.UpdateLightsGeometryToFollowCamera() ren.ResetCameraClippingRange() # now do the planes set_plane_infos(lookmark[0]) obj.render3D() def reset_to_default_view(view_index): """ @param view_index 0 for YZ, 1 for ZX, 2 for XY """ cam = obj._threedRenderer.GetActiveCamera() fp = cam.GetFocalPoint() cp = cam.GetPosition() if view_index == 0: cam.SetViewUp(0,1,0) if cp[0] < fp[0]: x = fp[0] + (fp[0] - cp[0]) else: x = cp[0] # safety check so we don't put cam in focal point # (renderer gets into unusable state!) if x == fp[0]: x = fp[0] + 1 cam.SetPosition(x, fp[1], fp[2]) elif view_index == 1: cam.SetViewUp(0,0,1) if cp[1] < fp[1]: y = fp[1] + (fp[1] - cp[1]) else: y = cp[1] if y == fp[1]: y = fp[1] + 1 cam.SetPosition(fp[0], y, fp[2]) elif view_index == 2: # then make sure it's up is the right way cam.SetViewUp(0,1,0) # just set the X,Y of the camera equal to the X,Y of the # focal point. if cp[2] < fp[2]: z = fp[2] + (fp[2] - cp[2]) else: z = cp[2] if z == fp[2]: z = fp[2] + 1 cam.SetPosition(fp[0], fp[1], z) # first reset the camera obj._threedRenderer.ResetCamera() obj.render3D()
[ [ 2, 0, 0.1429, 0.0714, 0, 0.66, 0, 881, 0, 0, 1, 0, 0, 0, 7 ], [ 14, 1, 0.127, 0.0079, 1, 0.39, 0, 929, 0, 0, 0, 0, 0, 5, 0 ], [ 6, 1, 0.1468, 0.0317, 1, 0.39, ...
[ "def get_plane_infos():\n # get out all plane orientations and normals\n plane_infos = []\n for sd in obj.sliceDirections._sliceDirectionsDict.values():\n # each sd has at least one IPW\n ipw = sd._ipws[0]\n plane_infos.append((ipw.GetOrigin(), ipw.GetPoint1(), ipw.GetPoint2(), ipw.Get...