Exemplo n.º 1
0
 def KeyPressed(self,obj,event):
      key = obj.GetKeySym()
      if key == 'space':
          #Disable the sphere Widget so as not to pick it
          self.SphereWidget.Off()
          #add a new sphere
          picker = vtk.vtkPointPicker()
          picker.SetTolerance(1E-3 * self.Centerlines.GetLength())
          eventPosition = obj.GetEventPosition()
          result = picker.Pick(float(eventPosition[0]),float(eventPosition[1]),0.0,self.vmtkRenderer.Renderer)
          if result == 0:
              #Reenable the sphere widget
              self.SphereWidget.On()
              return
          pickId = picker.GetPointId()
          #Only insert a new sphere if this id is not already in the list
          if self.SpheresIndices.IsId(pickId) == -1:
              self.CurrentSphereId = self.Spheres.GetPoints().InsertNextPoint(self.Centerlines.GetPoint(pickId))
              self.SpheresIndices.InsertNextId(pickId)
              interpolatedArray = self.Centerlines.GetPointData().GetArray("InterpolatedRadius")
              if interpolatedArray and (interpolatedArray.GetValue(pickId) != 0.):
                  self.SpheresRadii.InsertNextValue(interpolatedArray.GetValue(pickId))
              elif self.RadiusArray:
                  self.SpheresRadii.InsertNextValue(self.RadiusArray.GetValue(pickId))
              else:
                  self.SpheresRadii.InsertNextValue(self.Centerlines.GetLength()*0.01)
              self.Spheres.Modified()
              self.PlaceSphere()
         #Reenable the sphere widget
          self.SphereWidget.On()
          self.vmtkRenderer.RenderWindow.Render()
Exemplo n.º 2
0
    def mouseMoveEvent(self, obj, event):
        # picking the actor
        clickPos = self.GetInteractor().GetEventPosition()
        picker = vtk.vtkPointPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        actor_picked = picker.GetActor()
    
        if actor_picked != self.map_actor: # the map has not been picked, we do nothing
            self.OnMouseMove()
            return

        # updating the altitude text
        altitude = picker.GetDataSet().GetPointData().GetScalars().GetValue(picker.GetPointId())
        self.text_actor.SetCaption(str(altitude) + "m")
        self.text_actor.SetAttachmentPoint(picker.GetDataSet().GetPoints().GetPoint(picker.GetPointId()))
        self.GetInteractor().Render()

        # generating level line
        if(self.level_cutter == None):
            self._load_level_actor(picker.GetDataSet())  
            
        self._set_level_actor(altitude)

        self.OnMouseMove()
        return
Exemplo n.º 3
0
 def createRenderer(self, **args ):
     background_color = args.get( 'background_color', VTK_BACKGROUND_COLOR )
     self.renderer.SetBackground(*background_color)   
     self.textDisplayMgr = TextDisplayMgr( self.renderer ) 
     self.renderWindowInitSize = args.get( 'window_size', None ) 
     if self.renderWindowInitSize <> None:
         self.renderWindow.SetSize( self.renderWindowInitSize )                             
     self.pointPicker = vtk.vtkPointPicker()
     self.pointPicker.PickFromListOn()   
     try:        self.pointPicker.SetUseCells(True)  
     except:     print>>sys.stderr,  "Warning, vtkPointPicker patch not installed, picking will not work properly."
     self.pointPicker.InitializePickList()             
     self.renderWindowInteractor.SetPicker(self.pointPicker) 
     self.addObserver( self.renderer, 'ModifiedEvent', self.activateEvent )
     self.clipper = vtk.vtkBoxWidget()
     self.clipper.RotationEnabledOff()
     self.clipper.SetPlaceFactor( 1.0 ) 
     self.clipper.KeyPressActivationOff()
     self.clipper.SetInteractor( self.renderWindowInteractor )    
     self.clipper.SetHandleSize( 0.005 )
     self.clipper.SetEnabled( True )
     self.clipper.InsideOutOn()  
     self.clipper.AddObserver( 'StartInteractionEvent', self.startClip )
     self.clipper.AddObserver( 'EndInteractionEvent', self.endClip )
     self.clipper.AddObserver( 'InteractionEvent', self.executeClip )           
     self.clipOff() 
Exemplo n.º 4
0
 def createRenderer(self, **args):
     background_color = args.get('background_color', VTK_BACKGROUND_COLOR)
     self.renderer.SetBackground(*background_color)
     self.renderWindowInteractor.AddObserver('RightButtonPressEvent',
                                             self.onRightButtonPress)
     self.textDisplayMgr = TextDisplayMgr(self.renderer)
     self.pointPicker = vtk.vtkPointPicker()
     self.pointPicker.PickFromListOn()
     try:
         self.pointPicker.SetUseCells(True)
     except:
         print >> sys.stderr, "Warning, vtkPointPicker patch not installed, picking will not work properly."
     self.pointPicker.InitializePickList()
     self.renderWindowInteractor.SetPicker(self.pointPicker)
     self.addObserver(self.renderer, 'ModifiedEvent', self.activateEvent)
     self.clipper = vtk.vtkBoxWidget()
     self.clipper.RotationEnabledOff()
     self.clipper.SetPlaceFactor(1.0)
     self.clipper.KeyPressActivationOff()
     self.clipper.SetInteractor(self.renderWindowInteractor)
     self.clipper.SetHandleSize(0.005)
     self.clipper.SetEnabled(True)
     self.clipper.InsideOutOn()
     self.clipper.AddObserver('StartInteractionEvent', self.startClip)
     self.clipper.AddObserver('EndInteractionEvent', self.endClip)
     self.clipper.AddObserver('InteractionEvent', self.executeClip)
     self.clipOff()
Exemplo n.º 5
0
    def __init__(self, mesh, camera_position, focal_point, view_angle):
        self.mesh = mesh

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.mesh)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)

        self.camera = vtk.vtkCamera()

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetActiveCamera(self.camera)
        self.renderer.AddActor(self.actor)

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.SetOffScreenRendering(1)
        self.render_window.AddRenderer(self.renderer)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor.SetRenderWindow(self.render_window)

        self.picker = vtk.vtkPointPicker()
        self.interactor.SetPicker(self.picker)

        self.render_window.SetSize(_image_size,_image_size)
        self.camera.SetPosition(camera_position[0], camera_position[1], camera_position[2])
        self.camera.SetFocalPoint(focal_point[0], focal_point[1], focal_point[2])
        self.camera.SetViewAngle(view_angle)

        self.image_filter = vtk.vtkWindowToImageFilter()
        self.image_filter.SetInput(self.render_window)
Exemplo n.º 6
0
    def setup(self):

        self.CLselS = vtk.vtkSelectionSource()
        self.CLselS.SetContentType(
            4
        )  # vtkSelection:: #1 GLOBALIDS(nada) #3 VALUES(nada) #4 INDICES(varios)
        self.CLselS.SetFieldType(1)  # vtkSelection:: #0 CELL #1 POINT
        self.CLselS.SetContainingCells(
            0)  # para non extraer tamén as celdas que conteñen o punto dado

        self.CLselF = vtk.vtkExtractSelectedIds()
        self.CLselF.SetInputConnection(self.src.GetOutputPort())
        self.CLselF.SetSelectionConnection(self.CLselS.GetOutputPort())

        self.CLlabelsbM = vtk.vtkLabeledDataMapper()
        self.CLlabelsbM.SetInputConnection(self.CLselF.GetOutputPort())
        # self.CLlabelsbM.SetLabelFormat("%g")
        self.CLlabelsbM.SetLabelModeToLabelScalars()
        self.CLlabelsbM.GetLabelTextProperty().SetColor(Plot.label_color)

        self.CLlabelsbA = vtk.vtkActor2D()
        self.CLlabelsbA.SetMapper(self.CLlabelsbM)
        #        self.CLlabelsbA.SetVisibility(0)
        self.renderer.AddActor(self.CLlabelsbA)

        self.iren.AddObserver("LeftButtonPressEvent", self.ButtonPress)
        self.iren.AddObserver("LeftButtonReleaseEvent", self.ButtonRelease)

        self.picker = vtk.vtkPointPicker()
        #        picker.SetTolerance(0.005)
        self.picker.AddObserver("EndPickEvent", self.EndPick)
        self.iren.SetPicker(self.picker)
Exemplo n.º 7
0
    def create_cell_picker(self):
        """creates the vtk picker objects"""
        self.cell_picker = vtk.vtkCellPicker()
        self.node_picker = vtk.vtkPointPicker()

        self.area_picker = vtk.vtkAreaPicker()  # vtkRenderedAreaPicker?
        self.rubber_band_style = vtk.vtkInteractorStyleRubberBandPick()
        #vtk.vtkInteractorStyleRubberBand2D
        #vtk.vtkInteractorStyleRubberBand3D
        #vtk.vtkInteractorStyleRubberBandZoom
        #vtk.vtkInteractorStyleAreaSelectHover
        #vtk.vtkInteractorStyleDrawPolygon

        #vtk.vtkAngleWidget
        #vtk.vtkAngleRepresentation2D
        #vtk.vtkAngleRepresentation3D
        #vtk.vtkAnnotation
        #vtk.vtkArrowSource
        #vtk.vtkGlyph2D
        #vtk.vtkGlyph3D
        #vtk.vtkHedgeHog
        #vtk.vtkLegendBoxActor
        #vtk.vtkLegendScaleActor
        #vtk.vtkLabelPlacer

        self.cell_picker.SetTolerance(0.001)
        self.node_picker.SetTolerance(0.001)
Exemplo n.º 8
0
    def __init__(self,
                 vertices=True,
                 faces=True,
                 actors=True,
                 world_coords=True):
        """ Picking Manager helps with picking 3D objects

        Parameters
        -----------
        vertices : bool
            If True allows to pick vertex indices.
        faces : bool
            If True allows to pick face indices.
        actors : bool
            If True allows to pick actor indices.
        world_coords : bool
            If True allows to pick xyz position in world coordinates.
        """

        self.pickers = {}
        if vertices:
            self.pickers['vertices'] = vtk.vtkPointPicker()
        if faces:
            self.pickers['faces'] = vtk.vtkCellPicker()
        if actors:
            self.pickers['actors'] = vtk.vtkPropPicker()
        if world_coords:
            self.pickers['world_coords'] = vtk.vtkWorldPointPicker()
Exemplo n.º 9
0
    def __init_gui(self):
        interactor = wxVTKRenderWindowInteractor(self, -1, size=self.GetSize())

        scroll = wx.ScrollBar(self, -1, style=wx.SB_VERTICAL)
        self.scroll = scroll

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(self, -1, self.titulo))
        sizer.Add(interactor, 1, wx.EXPAND | wx.GROW)

        background_sizer = wx.BoxSizer(wx.HORIZONTAL)
        background_sizer.AddSizer(sizer, 1, wx.EXPAND | wx.GROW | wx.ALL, 2)
        background_sizer.Add(scroll, 0, wx.EXPAND | wx.GROW)
        self.SetSizer(background_sizer)
        background_sizer.Fit(self)

        self.Layout()
        self.Update()
        self.SetAutoLayout(1)

        self.interactor = interactor

        self.pega_pontos = False
        self.continua_pegar = True

        self.list_points = []
        self.list_points_ff = []
        self.list_points_ff_other = []

        style = vtk.vtkInteractorStyleTrackballCamera()
        self.picker = vtk.vtkPointPicker()

        pub.subscribe(self.altera_estado, 'Altera estado seleciona vertices')
Exemplo n.º 10
0
    def _create_view_frame(self):
        import resources.python.larynx_measurement_frame
        reload(resources.python.larynx_measurement_frame)

        self._view_frame = module_utils.instantiate_module_view_frame(
            self, self._module_manager,
            resources.python.larynx_measurement_frame.LarynxMeasurementFrame)

        module_utils.create_standard_object_introspection(
            self, self._view_frame, self._view_frame.view_frame_panel,
            {'Module (self)' : self})

        # now setup the VTK stuff
        if self._viewer is None and not self._view_frame is None:
            # vtkImageViewer() does not zoom but retains colour
            # vtkImageViewer2() does zoom but discards colour at
            # first window-level action.
            # vtkgdcm.vtkImageColorViewer() does both right!
            self._viewer = vtkgdcm.vtkImageColorViewer()
            self._viewer.SetupInteractor(self._view_frame.rwi)
            self._viewer.GetRenderer().SetBackground(0.3,0.3,0.3)
            self._set_image_viewer_dummy_input()

            pp = vtk.vtkPointPicker()
            pp.SetTolerance(0.0)
            self._view_frame.rwi.SetPicker(pp)
Exemplo n.º 11
0
    def __init__(self, main_wnd):
        # self.AddObserver('LeftButtonPressEvent', self.left_button_press_event)
        # self.AddObserver('MouseMoveEvent', self.mouse_move_event)
        # self.mouse_motion_flag = 0
        # self.ren = self.iren.FindPokedRenderer(0, 0)
        self.ren = main_wnd.render
        self.renWin = self.ren.GetRenderWindow()
        self.iren = self.renWin.GetInteractor()
        self.grid = main_wnd.grid

        self.actors = []
        self.node_ids = []

        self.picker = vtk.vtkPointPicker()

        self.picker_points = []
        # self.area_picker = vtk.vtkAreaPicker()
        self.area_picker = vtk.vtkRenderedAreaPicker()
        self.area_picker.SetRenderer(self.ren)

        self.Rotating = 0
        self.Panning = 0
        self.Zooming = 0
        self.SinglePick = 0
        self.BoxPick = 0
        self.SinglePickRelease = 0
        self.BoxPickRelease = 0

        self.iren.AddObserver('LeftButtonPressEvent', self.PickEvent)
        self.iren.AddObserver('LeftButtonReleaseEvent', self.PickEvent)
        self.iren.AddObserver("MiddleButtonPressEvent", self.MoveEvent)
        self.iren.AddObserver("MiddleButtonReleaseEvent", self.MoveEvent)
        self.iren.AddObserver("MouseMoveEvent", self.MouseMove)
        self.iren.AddObserver("KeyPressEvent", self.Keypress)
Exemplo n.º 12
0
    def setup_interactor(self, iren, win, style=None):
        '''
        Set up our unique PCL interactor style for a given vtkRenderWindowInteractor object
        attached to a given vtkRenderWindow

        # Parameters
        iren : vtkRenderWindowInteractor
            The vtkRenderWindowInteractor object to set up
        win : vtkRenderWindow
            A vtkRenderWindow object that the interactor is attached to
        '''
        if style is None:
            style = self._style

        win.AlphaBitPlanesOff()
        win.PointSmoothingOff()
        win.LineSmoothingOff()
        win.PolygonSmoothingOff()
        win.SwapBuffersOn()
        win.SetStereoTypeToAnaglyph()

        iren.SetRenderWindow(win)
        iren.SetInteractorStyle(style)
        iren.SetDesiredUpdateRate(30.0)

        iren.Initialize()

        if style != self._style:
            ppkr = vtk.vtkPointPicker()
            ppkr.SetTolerance(ppkr.GetTolerance() * 2)
            iren.SetPicker(ppkr)
Exemplo n.º 13
0
    def create_interactor(self):
        '''
        Create the internal Interactor object.
        '''
        self._interactor = vtk.vtkRendererWindowInteractor()

        self._win.AlphaBitPlanesOff()
        self._win.PointSmoothingOff()
        self._win.LineSmoothingOff()
        self._win.PolygonSmoothingOff()
        self._win.SwapBuffersOn()
        self._win.SetStereoTypeToAnaglyph()

        self._interactor.SetRenderWindow(self._win)
        self._interactor.SetInteractorStyle(self._style)
        self._interactor.SetDesiredUpdateRate(30.0)

        self._interactor.Initialize()
        self._timer_id = self._interactor.CreateRepeatingTimer(5000)

        ppkr = vtk.vtkPointPicker()
        ppkr.SetTolerance(ppkr.GetTolerance() * 2)
        self._interactor.SetPicker(ppkr)

        self._exit_main_loop_timer_callback = _ExitMainLoopTimerCallback(self)
        self._exit_main_loop_timer_callback.right_timer_id = -1
        self._interactor.AddObserver(vtk.vtkCommand.TimerEvent,
                                     self._exit_main_loop_timer_callback)

        self._exit_callback = _ExitCallBack(self)
        self._interactor.AddObserver(vtk.vtkCommand.ExitEvent,
                                     self._exit_callback)

        self.reset_stopped_flag()
Exemplo n.º 14
0
    def __init__(self, viewer):
        super().__init__(viewer)
        self.viewer = viewer
        self.picker = vtk.vtkPointPicker()

        self.RemoveObservers("LeftButtonPressEvent")
        self.AddObserver("LeftButtonPressEvent", self.OnInsertSeed)
Exemplo n.º 15
0
    def __init__(self, renderer, actors):
        CustomInteractorStyle.__init__(self)

        # Remember data we need for the interaction
        self.peaker = vtk.vtkPointPicker()
        self.renderer = renderer
        self.chosenActor = None
        self.actors = actors
Exemplo n.º 16
0
    def enable_point_picking(self,
                             callback=None,
                             show_message=True,
                             font_size=18,
                             color='pink',
                             point_size=10,
                             use_mesh=False,
                             show_point=True,
                             **kwargs):
        """Enable picking at points.

        Enable picking a point at the mouse location in the render view
        using the ``P`` key. This point is saved to the ``.picked_point``
        attrbute on the plotter. Pass a callback function that takes that
        point as an argument. The picked point can either be a point on the
        first intersecting mesh, or a point in the 3D window.

        If ``use_mesh`` is True, the callback function will be passed a pointer
        to the picked mesh and the point ID of the selected mesh.

        """
        if hasattr(self, 'notebook') and self.notebook:
            raise AssertionError(
                'Point picking not available in notebook plotting')

        def _end_pick_event(picker, event):
            self.picked_point = np.array(picker.GetPickPosition())
            self.picked_mesh = picker.GetDataSet()
            self.picked_point_id = picker.GetPointId()
            if show_point:
                self.add_mesh(self.picked_point,
                              color=color,
                              point_size=point_size,
                              name='_picked_point',
                              pickable=False,
                              reset_camera=False,
                              **kwargs)
            if hasattr(callback, '__call__'):
                if use_mesh:
                    try_callback(callback, self.picked_mesh,
                                 self.picked_point_id)
                else:
                    try_callback(callback, self.picked_point)

        point_picker = vtk.vtkPointPicker()
        point_picker.AddObserver(vtk.vtkCommand.EndPickEvent, _end_pick_event)

        self.enable_trackball_style()
        self.iren.SetPicker(point_picker)

        # Now add text about cell-selection
        if show_message:
            if show_message is True:
                show_message = "Press P to pick under the mouse"
            self.add_text(str(show_message),
                          font_size=font_size,
                          name='_point_picking_message')
        return
Exemplo n.º 17
0
    def __init__(self, parent):
        RenderFrame.__init__(self, parent)
        
        self.picker = vtk.vtkPointPicker()   # Picks points as mouse moves over plot
        self._Iren.SetPicker(self.picker)
        self.dot = Dot()                     # Dot in scene to show what was picked
        self.pickingEnabled = False          # Keep track of whether picking is on

        self.pointUpdateListeners = []
Exemplo n.º 18
0
    def PickCallback(self, obj):
        picker = vtk.vtkPointPicker()
        eventPosition = self.vmtkRenderer.RenderWindowInteractor.GetEventPosition(
        )
        result = picker.Pick(float(eventPosition[0]), float(eventPosition[1]),
                             0.0, self.vmtkRenderer.Renderer)
        # We treat result as a boolean value (which can also be nonetype if a selection outside the render windw is made)
        # If the value of result is False or None, then an invalid actor was selected in the scene.
        if result is None:
            return
        elif result == 0:
            return

        # find the value of "RegionId" stored in the vtkPolyData PointData array. This is a unique number
        # which is generated for each connected surface point by the allRegionConnectivity
        # vtkPolyDataConnectivityFilter function
        pickedPointId = picker.GetPointId()
        self.CurrentPickedActor = picker.GetActor()
        self.CurrentPickedPolyData = self.CurrentPickedActor.GetMapper(
        ).GetInputAsDataSet()
        regionId = self.CurrentPickedPolyData.GetPointData().GetArray(
            'RegionId').GetValue(pickedPointId)

        # extract only the desired region Id from the dataset
        isolatedFilter = vtk.vtkPolyDataConnectivityFilter()
        isolatedFilter.SetInputData(self.CurrentPickedPolyData)
        isolatedFilter.SetExtractionModeToSpecifiedRegions()
        isolatedFilter.AddSpecifiedRegion(regionId)

        # remove all points not in the extracted cells
        cleanedFilter = vtk.vtkCleanPolyData()
        cleanedFilter.SetInputConnection(isolatedFilter.GetOutputPort())
        cleanedFilter.Update()

        outputSurface = cleanedFilter.GetOutput()

        # create a new mapper and actor for this extracted surface object
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(outputSurface)
        mapper.ScalarVisibilityOff()
        mapper.Update()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(1.0, 0.0, 0.0)  # red color
        actor.GetProperty().SetDiffuse(1.0)
        actor.GetProperty().SetSpecular(0.2)
        actor.GetProperty().SetRepresentationToSurface()
        actor.GetProperty().EdgeVisibilityOff()

        # place the extracted surface object's actor instance in the necessary render windows
        # and lists to log it's selection
        self.PastPickedActorList.append(actor)
        self._OutputPolyDataList.append(outputSurface)
        self.vmtkRenderer.Renderer.AddActor(actor)
        self.vmtkRenderer.RenderWindow.Render()
        return
Exemplo n.º 19
0
    def plot(self, struct):

        # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision
        if not self.call_config(struct):
            return

        # creates self.src
        if not self.call_src():
            return

        self.add_outline_2(self.src)

        if self.has_field:
            self.add_labels_b_1()
            if self.data1.get('fielddomain') == 'cell':
                self.cellcenters = vtk.vtkCellCenters()
                self.cellcenters.SetInputConnection(self.src.GetOutputPort())
                self.add_labels_b_2([self.cellcenters])
            else:
                self.add_labels_b_2([self.src])

            # aqui para que apareza de ultimo
            # so con campo?
            self.add_search_1(self.search_callback,
                              self.search_callback_coords)

# wireframe
        self.wireM = vtk.vtkDataSetMapper()
        self.wireM.SetInputConnection(self.src.GetOutputPort())
        self.wireM.ScalarVisibilityOff()

        self.wireA = vtk.vtkActor()
        self.wireA.SetMapper(self.wireM)
        self.wireA.GetProperty().SetRepresentationToWireframe()
        self.wireA.GetProperty().SetColor(Plot.mesh_color)

        self.add_sw_2(self.wireA)

        self.rens[0].AddActor(self.wireA)

        self.set_iren()
        #MouseMoveEvent
        self.iren.AddObserver("LeftButtonPressEvent", self.ButtonEvent)
        #self.iren.AddObserver("LeftButtonReleaseEvent", self.ButtonEvent2)

        if self.data1.get('fielddomain') == 'cell':
            self.picker = vtk.vtkCellPicker()
        else:
            self.picker = vtk.vtkPointPicker()
        self.picker.AddObserver("EndPickEvent", self.EndPick)
        self.iren.SetPicker(self.picker)

        self.copy_params(struct)

        self.done = True
Exemplo n.º 20
0
 def __init__( self, **kwargs ):
     self.renWin = None
     self.renderer = None
     self.colormap = None
     self.mapper = None
     self.actor = None
     self.picker = vtk.vtkPointPicker()
     self.polydata = None
     self.marker_actor = None
     self.points_modified = False
     self.unlabeled_color = [ 1.0, 1.0, 1.0 ]
Exemplo n.º 21
0
 def leftButtonPressEvent(self, obj, event):
     print(obj)
     clickPos = self.GetInteractor().GetEventPosition()
     print(clickPos)
     #picker = self.GetInteractor().GetPicker()
     #print("Get current picker: ", picker)
     picker = vtk.vtkPointPicker()
     ren = self.GetInteractor().GetRenderWindow().GetRenderers(
     ).GetFirstRenderer()
     picker.Pick(clickPos[0], clickPos[1], 0, ren)
     print(picker.GetPointId())
     self.cbFunc(picker.GetPointId())
Exemplo n.º 22
0
    def PickCallback(self, obj):
        picker = vtk.vtkPointPicker()
        eventPosition = self.vmtkRenderer.RenderWindowInteractor.GetEventPosition()
        result = picker.Pick(float(eventPosition[0]),float(eventPosition[1]),0.0,self.vmtkRenderer.Renderer)
        # We treat result as a boolean value (which can also be nonetype if a selection outside the render windw is made)
        # If the value of result is False or None, then an invalid actor was selected in the scene. 
        if result is None:
            return
        elif result == 0:
            return

        # find the value of "RegionId" stored in the vtkPolyData PointData array. This is a unique number
        # which is generated for each connected surface point by the allRegionConnectivity 
        # vtkPolyDataConnectivityFilter function
        pickedPointId = picker.GetPointId()
        self.CurrentPickedActor = picker.GetActor()
        self.CurrentPickedPolyData = self.CurrentPickedActor.GetMapper().GetInputAsDataSet()
        regionId = self.CurrentPickedPolyData.GetPointData().GetArray('RegionId').GetValue(pickedPointId)
        
        # extract only the desired region Id from the dataset
        isolatedFilter = vtk.vtkPolyDataConnectivityFilter()
        isolatedFilter.SetInputData(self.CurrentPickedPolyData)
        isolatedFilter.SetExtractionModeToSpecifiedRegions()
        isolatedFilter.AddSpecifiedRegion(regionId)

        # remove all points not in the extracted cells
        cleanedFilter = vtk.vtkCleanPolyData()
        cleanedFilter.SetInputConnection(isolatedFilter.GetOutputPort())
        cleanedFilter.Update()

        outputSurface = cleanedFilter.GetOutput()

        # create a new mapper and actor for this extracted surface object
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(outputSurface)
        mapper.ScalarVisibilityOff()
        mapper.Update()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(1.0, 0.0, 0.0) # red color
        actor.GetProperty().SetDiffuse(1.0)
        actor.GetProperty().SetSpecular(0.2)
        actor.GetProperty().SetRepresentationToSurface()
        actor.GetProperty().EdgeVisibilityOff()

        # place the extracted surface object's actor instance in the necessary render windows
        # and lists to log it's selection        
        self.PastPickedActorList.append(actor)
        self._OutputPolyDataList.append(outputSurface)
        self.vmtkRenderer.Renderer.AddActor(actor)
        self.vmtkRenderer.RenderWindow.Render()
        return
Exemplo n.º 23
0
def LeftButtonPressed(obj, ev):

    pos = obj.GetEventPosition()

    picker = vtk.vtkPointPicker()
    picker.PickFromListOn()
    picker.AddPickList(landmarkActor)

    picker.Pick(pos[0], pos[1], 0, renderer)

    global pickedPoint
    pickedPoint = picker.GetPointId()
Exemplo n.º 24
0
    def _selectPoint(self, pt):
        picker = vtk.vtkPointPicker()
        if picker.Pick(pt.x(), pt.y(), 0, self._vtk_renderer):
            point_id = picker.GetPointId()
            self._selection.selectPoint(point_id)
            self._setSelectionProperties(self._selection)

            unstr_grid = self._selection.get()
            points = unstr_grid.GetPoints()
            nfo = self._buildPointInfo(points)
            self._selected_mesh_ent_info.setPointInfo(point_id, nfo)
            self._showSelectedMeshEntity()
Exemplo n.º 25
0
    def __init__(self, map_actor, text_actor):
        self.AddObserver("MouseMoveEvent", self.mouse_move_event)
        self.map_actor = map_actor
        self.text_actor = text_actor

        self.elevation_actor = vtk.vtkActor()
        self.sphere = vtk.vtkSphere()
        self.cutter = vtk.vtkCutter()
        self.stripper = vtk.vtkStripper()
        self.tube_filter = vtk.vtkTubeFilter()
        self.mapper = vtk.vtkDataSetMapper()
        self.picker = vtk.vtkPointPicker()
Exemplo n.º 26
0
 def add_articulation_sphere(self, pos2d):
     if not self.get_active_point_cloud(): return
     self.get_active_point_cloud().actor.SetPickable(True)
     picker = vtk.vtkPointPicker()
     if picker.Pick(pos2d[0], pos2d[1], 0, self.frame.ren):
         pos = picker.GetPickPosition()
         sphere = ArticulationSphere(pos=pos,
                         radius=ArticulationSphere.last_radius_update,
                         frame=self.frame, scene=self,
                         color=self.get_active_point_cloud().base_color)
         self.actor_to_sphere[sphere.actor] = sphere
     self.get_active_point_cloud().actor.SetPickable(False)
Exemplo n.º 27
0
 def __init__(self):
     self.renWin = None
     self.renderer: vtk.vtkRenderer = None
     self.mapper: vtk.vtkMapper = None
     self.colormap = None
     self.actor: vtk.vtkActor = None
     self.picker = vtk.vtkPointPicker()
     self.picker.SetUseCells(False)
     self.picker.SetTolerance(0.02)
     self.polydata: vtk.vtkPolyData = None
     self.marker_actor: vtk.vtkActor = None
     self.points_modified = False
     self.unlabeled_color = [1.0, 1.0, 1.0]
Exemplo n.º 28
0
 def mouseMoveEvent(self, obj, event):
     clickPos = self.GetInteractor().GetEventPosition()
     picker = vtk.vtkPointPicker()
     picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     point = picker.GetPointId()
     if (point != -1):
         altitude = self.grid.GetPointData().GetScalars().GetValue(point)
         self.textActor.SetInput("Altitude : " + str(altitude) + "m")
         altitudeSphere = vtk.vtkSphere()
         altitudeSphere.SetRadius(EARTH_RADIUS + altitude)
         self.cutter.SetCutFunction(altitudeSphere)
         self.renWin.Render()
     self.OnMouseMove()
     return
Exemplo n.º 29
0
    def __init__(self, width=1400, height=1000, title='VTK Viewer'):

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.render_window.SetSize(width, height)

        self.root = Tkinter.Tk()
        self.root.title(title)
        self.render_window_interactor = vtkTkRenderWindowInteractorNoCharEvent(
            self.root, rw=self.render_window, width=width, height=height)
        self.render_window_interactor.Initialize()
        self.render_window_interactor.pack(fill='both', expand=1)

        self.cam_trackball = vtk.vtkInteractorStyleTrackballCamera()
        self.cam_trackball.SetCurrentRenderer(self.renderer)
        self.render_window_interactor.SetInteractorStyle(self.cam_trackball)
        self.cam_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.key_callbacks = {}

        self.act_trackball = vtk.vtkInteractorStyleTrackballActor()
        self.act_trackball.SetCurrentRenderer(self.renderer)
        self.act_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.act_trackball.AddObserver('InteractionEvent', self.on_actor_move)
        self.actor_move_callbacks = []

        self.mouse_pick_interactor = vtk.vtkInteractorStyleUser()
        self.mouse_pick_interactor.SetCurrentRenderer(self.renderer)
        self.mouse_pick_interactor.AddObserver('KeyPressEvent',
                                               self.on_key_press)
        self.mouse_pick_interactor.AddObserver('LeftButtonPressEvent',
                                               lambda x, y: self.pick(True))

        self.rubber_band_interactor = vtk.vtkInteractorStyleRubberBand3D()
        self.rubber_band_interactor.SetCurrentRenderer(self.renderer)
        self.rubber_band_interactor.AddObserver('KeyPressEvent',
                                                self.on_key_press)
        self.rubber_band_interactor.AddObserver('SelectionChangedEvent',
                                                self.on_box_select)
        self.box_select_callbacks = []

        # Create pickers
        self.cell_picker = vtk.vtkCellPicker()
        self.cell_picker.AddObserver("EndPickEvent", self.on_pick)
        self.point_picker = vtk.vtkPointPicker()
        self.point_picker.AddObserver("EndPickEvent", self.on_pick)
        self.pick_callbacks = []
Exemplo n.º 30
0
    def __init__(self,
                 mesh,
                 camera_position,
                 focal_point,
                 view_angle,
                 image_size,
                 view_up=(0, 1, 0)):
        self.graphics = vtk.vtkGraphicsFactory()
        self.graphics.SetUseMesaClasses(1)
        #self.img_factory = vtk.vtkImagingFactory()
        #self.img_factory.SetUseMesaClasses(1)

        self.mesh = mesh
        self.image_size = image_size

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.mesh)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)

        self.camera = vtk.vtkCamera()

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetActiveCamera(self.camera)
        self.renderer.AddActor(self.actor)
        self.renderer.SetBackground(0, 0, 0)

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.SetOffScreenRendering(True)
        self.render_window.AddRenderer(self.renderer)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor.SetRenderWindow(self.render_window)

        self.picker = vtk.vtkPointPicker()
        self.interactor.SetPicker(self.picker)

        self.render_window.SetSize(self.image_size, self.image_size)
        self.camera.SetPosition(camera_position[0], camera_position[1],
                                camera_position[2])
        self.camera.SetFocalPoint(focal_point[0], focal_point[1],
                                  focal_point[2])
        self.camera.SetViewUp(view_up)
        self.camera.OrthogonalizeViewUp()
        self.camera.SetViewAngle(view_angle)

        self.image_filter = vtk.vtkWindowToImageFilter()
        self.image_filter.SetInput(self.render_window)
Exemplo n.º 31
0
 def pickPoint(self, obj, e):
     if self.__pickPointMode == True:
         print self.GetInteractor().GetEventPosition()
         clicked_point = self.GetInteractor().GetEventPosition()
         picker1 = vtk.vtkPointPicker()
         picker1.Pick(clicked_point[0], clicked_point[1], 0, ren)
         
         picker2 = vtk.vtkPropPicker()
         picker2.PickProp(clicked_point[0], clicked_point[1], ren)
         picked_prop = picker2.GetActor()
         if picked_prop != None:    
             picked_prop.GetProperty().SetColor(1.0, 1.0, 0.0)
         else:
             print "None is picked!"
     self.OnLeftButtonDown()
 def leftButtonPressEvent(self, obj, event):
     print(obj)
     clickPos = self.GetInteractor().GetEventPosition()
     print("click position: ", clickPos)
     #picker = self.GetInteractor().GetPicker()
     #print("Get current picker: ", picker)
     picker = vtk.vtkPointPicker()
     picker.SetTolerance(0.001)
     ren = self.GetInteractor().GetRenderWindow().GetRenderers(
     ).GetFirstRenderer()
     picker.Pick(clickPos[0], clickPos[1], 0, ren)
     print("picked id: ", picker.GetPointId())
     if (picker.GetPointId() == -1):
         return
     self.cbFunc(picker.GetPointId())
Exemplo n.º 33
0
Arquivo: app.py Projeto: jcdinis/POMES
    def __init__(self, parent, id,style):
        wx.Panel.__init__(self, parent, id, style=style)

        self.x0 = 0
        self.x1 = 0
        self.y0 = 0
        self.y1 = 0


        self.estruturas = None
        self.actor_estrutura = None


        self.renderer = vtk.vtkRenderer()
        self.Interactor = wxVTKRenderWindowInteractor(self,-1, size = self.GetSize())
        self.Interactor.GetRenderWindow().AddRenderer(self.renderer)
        self.Interactor.Render()

        istyle = vtk.vtkInteractorStyleTrackballCamera()

        self.Interactor.SetInteractorStyle(istyle)

        self.pd = None
        self.id_points = set()

        hbox=wx.BoxSizer(wx.VERTICAL)
        hbox.Add(wx.StaticText(self,-1, u'Global Counting Structure'))


        hbox.Add(self.Interactor,1, wx.EXPAND)
        self.SetSizer(hbox)

        self.pega_pontos = False
        istyle.AddObserver("LeftButtonPressEvent",self.Clik)
        istyle.AddObserver("LeftButtonReleaseEvent", self.Release)
        #istyle.AddObserver("MouseMoveEvent", self.OnMotion)
        pub.subscribe(self.altera_estado, 'Altera estado seleciona vertices')

        pub.subscribe(self.renderiza, 'recalcula surface')

        self.init_actor()
        self.adicionaeixos()
        #self.desenha_surface()
        self.renderer.ResetCamera()
        self.list_points=[]
        self.Picker=vtk.vtkPointPicker()
Exemplo n.º 34
0
 def iniVTK(self):
     self.last_added_sphere_ren1 = None
     self.newed_spheres = vtk.vtkCollection()
     self.sphere_radius_ren1 = 2.0
     self.bouttons_spheres = []
     self.slice_assembly = None
     self.image_roi = None
     self.im_importer = vtk.vtkImageImport()
     self.sphere = vtk.vtkSphereSource()
     self.sphere.SetRadius(2.0)
     self.sphere_mapper = vtk.vtkPolyDataMapper()
     self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort())
     self.sphere_actor_ren2 = vtk.vtkActor()
     self.sphere.SetCenter(show_height / 2, show_width / 2, 0)
     self.sphere_actor_ren2.SetMapper(self.sphere_mapper)
     self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0)
     self.vtk_widget.GetRenderWindow().SetSize(800, 400)
     self.image_actor = vtk.vtkImageActor()
     self.ren1 = vtk.vtkRenderer()
     self.ren2 = vtk.vtkRenderer()
     self.interactorStyle = BouttonInteractorStyle()
     self.vtk_widget.SetInteractorStyle(self.interactorStyle)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2)
     self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0)
     self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0)
     self.ren2.AddActor(self.sphere_actor_ren2)
     self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors()
     self.imageLevelFilter.SetLevel(400)
     self.imageLevelFilter.SetWindow(800)
     self.im_importer.SetNumberOfScalarComponents(1)
     self.im_importer.SetDataScalarTypeToUnsignedShort()
     self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1,
                                    0, 0)
     self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1,
                                     0, 0)
     self.imageLevelFilter.SetInputConnection(
         self.im_importer.GetOutputPort())
     self.image_actor.SetInput(self.imageLevelFilter.GetOutput())
     self.ren1_sphere_actors = vtk.vtkActorCollection()
     self.pointPicker = vtk.vtkPointPicker()
     self.actorPicker = vtk.vtkPropPicker()
     self.pickedActor = None
     self.ren1.AddActor(self.image_actor)
     self.ren2.AddActor(self.image_actor)
Exemplo n.º 35
0
    def __init__(self, width=1400, height=1000, title='VTK Viewer'):
        
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)
        
        self.render_window = vtk.vtkRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.render_window.SetSize(width, height)

        self.root = Tkinter.Tk()
        self.root.title(title)
        self.render_window_interactor = vtkTkRenderWindowInteractorNoCharEvent(self.root, rw=self.render_window, width=width, height=height)
        self.render_window_interactor.Initialize()
        self.render_window_interactor.pack(fill='both', expand=1)

        self.cam_trackball = vtk.vtkInteractorStyleTrackballCamera()
        self.cam_trackball.SetCurrentRenderer(self.renderer)
        self.render_window_interactor.SetInteractorStyle(self.cam_trackball)
        self.cam_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.key_callbacks = {}

        self.act_trackball = vtk.vtkInteractorStyleTrackballActor()
        self.act_trackball.SetCurrentRenderer(self.renderer)
        self.act_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.act_trackball.AddObserver('InteractionEvent', self.on_actor_move)
        self.actor_move_callbacks = []

        self.mouse_pick_interactor = vtk.vtkInteractorStyleUser()
        self.mouse_pick_interactor.SetCurrentRenderer(self.renderer)
        self.mouse_pick_interactor.AddObserver('KeyPressEvent', self.on_key_press)
        self.mouse_pick_interactor.AddObserver('LeftButtonPressEvent', lambda x, y: self.pick(True))

        self.rubber_band_interactor = vtk.vtkInteractorStyleRubberBand3D()
        self.rubber_band_interactor.SetCurrentRenderer(self.renderer)
        self.rubber_band_interactor.AddObserver('KeyPressEvent', self.on_key_press)
        self.rubber_band_interactor.AddObserver('SelectionChangedEvent', self.on_box_select)
        self.box_select_callbacks = []

        # Create pickers
        self.cell_picker = vtk.vtkCellPicker()
        self.cell_picker.AddObserver("EndPickEvent", self.on_pick)
        self.point_picker = vtk.vtkPointPicker()
        self.point_picker.AddObserver("EndPickEvent", self.on_pick)
        self.pick_callbacks = []
Exemplo n.º 36
0
 def iniVTK(self):
     self.last_added_sphere_ren1 = None
     self.newed_spheres = vtk.vtkCollection()
     self.sphere_radius_ren1 = 2.0
     self.bouttons_spheres = []
     self.slice_assembly = None
     self.image_roi = None
     self.im_importer = vtk.vtkImageImport()       
     self.sphere = vtk.vtkSphereSource()
     self.sphere.SetRadius(2.0)
     self.sphere_mapper = vtk.vtkPolyDataMapper()
     self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort())
     self.sphere_actor_ren2 = vtk.vtkActor()
     self.sphere.SetCenter(show_height / 2, show_width / 2, 0)
     self.sphere_actor_ren2.SetMapper(self.sphere_mapper)
     self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0)
     self.vtk_widget.GetRenderWindow().SetSize(800, 400)
     self.image_actor = vtk.vtkImageActor()
     self.ren1 = vtk.vtkRenderer()
     self.ren2 = vtk.vtkRenderer()
     self.interactorStyle = BouttonInteractorStyle()
     self.vtk_widget.SetInteractorStyle(self.interactorStyle)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2)
     self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0)
     self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0)
     self.ren2.AddActor(self.sphere_actor_ren2)
     self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors()
     self.imageLevelFilter.SetLevel(400)
     self.imageLevelFilter.SetWindow(800)
     self.im_importer.SetNumberOfScalarComponents(1)
     self.im_importer.SetDataScalarTypeToUnsignedShort()
     self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.imageLevelFilter.SetInputConnection(self.im_importer.GetOutputPort())
     self.image_actor.SetInput(self.imageLevelFilter.GetOutput())
     self.ren1_sphere_actors = vtk.vtkActorCollection()
     self.pointPicker = vtk.vtkPointPicker()
     self.actorPicker = vtk.vtkPropPicker()
     self.pickedActor = None
     self.ren1.AddActor(self.image_actor)
     self.ren2.AddActor(self.image_actor)
Exemplo n.º 37
0
 def add_articulation_sphere_to_closest_point(self, pos2d):
     picker = vtk.vtkPointPicker()
     if not picker.Pick(pos2d[0], pos2d[1], 0, self.frame.ren): return
     p = picker.GetPickPosition()
     k, node = min([(linalg.norm(node.pos - p),
                     (k, node)) for k, node in self.K.items()])[1]
     if k in self.node_to_sphere: return # already one
     sphere = ArticulationSphere(pos=node.pos, frame=self.frame,
                                 scene=self.scene,
                                 radius=node.radius * ART_SPHERE_SIZE_RATIO,
                                 color=self.base_color)
     sphere.add_callback('moved', self.update)
     sphere.add_callback('cut_above', self.cut_above)
     sphere.add_callback('cut_branch', self.cut_branch)
     sphere.add_callback('delete', self.delete_articulation_sphere)
     for name, f in self.additional_sphere_callbacks:
         sphere.add_callback(name, f)
     sphere.polytube_node = k
     self.node_to_sphere[k] = sphere
     self.scene.actor_to_sphere[sphere.actor] = sphere
    def __init__(self, master, cnf={}, **kw):


        # Below is a horrible hack to deal with a bug when python > 2.6 and vtk < 5.4, see:
        # http://www.vtk.org/pipermail/vtkusers/2008-September/096743.html
        #
        # We can't use the Tkinter.wantobjects=0 fix as it breaks other stuff
        # within Tkinter.
        #
        # Although this supposedly appeared in Py 2.3, it doesn't seem
        # to have made it into any packaged version before 2.6
        # The problem was fixed in the vtkLoadPythonTkWidgets file on 03/07/2009
        # which corresponds to vtk 5.4
        # 
        # To get around it, we poke a fixed version of vtkLoadPythonTkWidgets from our repository
        # into the module namespace
        vtk_version = map(int,vtk.vtkVersion.GetVTKVersion().split('.'))
        if (sys.version_info[0] >= 2 and sys.version_info[1] >= 6) and (vtk_version[0] <= 5 and vtk_version[1] <= 4):
            from viewer.vtkLoadPythonTkWidgets import vtkLoadPythonTkWidgets
            vtk.tk.vtkTkRenderWidget.vtkLoadPythonTkWidgets=vtkLoadPythonTkWidgets

        #
        # Now we can carry on and init the bass class.
        #
        vtk.tk.vtkTkRenderWidget.vtkTkRenderWidget.__init__(self,master, kw)

        # Base vtkTkRenderWidget uses a vtkCellPicker
        self._Picker=vtk.vtkPointPicker()

        # Here we set out own variables
        self.camera_x = 0.
        self.camera_y = 0.
        self.camera_z = 1.

        self.near = None
        self.far = None

        self.debug=0

        # Override the default bindings with some of our own
        self.UpdateBindings()
Exemplo n.º 39
0
    def __init__ (self, master, renwin):
        debug ("In Picker::__init__ ()")
        self.renwin = renwin
        self.master = master
        self.pointpicker = vtk.vtkPointPicker()
        self.cellpicker = vtk.vtkCellPicker()
        self.worldpicker = vtk.vtkWorldPointPicker()
        self.probe_point = vtk.vtkPoints()
        self.probe_data = vtk.vtkPolyData()
        self.pick_type_var = Tkinter.IntVar()
        self.tol_var = Tkinter.DoubleVar ()
        self.tol_var.set(self.pointpicker.GetTolerance())
        self.root = None
        self.txt = None

        # Use a set of axis to show the picked point.
        self.p_source = vtk.vtkAxes ()
        self.p_mapper = vtk.vtkPolyDataMapper ()
        self.p_actor = vtk.vtkActor ()

        self._initialize ()
Exemplo n.º 40
0
 def connect_articulation_sphere_to_closest_point(self, sphere, pos2d):
     if sphere.polytube_node is not None: return # already connected
     picker = vtk.vtkPointPicker()
     if not picker.Pick(pos2d[0], pos2d[1], 0, self.frame.ren): return
     p = picker.GetPickPosition()
     k, node = min([(linalg.norm(node.pos - p),
                     (k, node)) for k, node in self.K.items()])[1]
     new_node = self.K.add_node(pos=sphere.get_position(),
                               radius=(sphere.get_radius() /
                                       ART_SPHERE_SIZE_RATIO),
                               parent=k)
     self.K[k].children.add(new_node.id)
     self.node_to_sphere[new_node.id] = sphere
     sphere.polytube_node = new_node.id
     sphere.add_callback('moved', self.update)
     sphere.add_callback('cut_above', self.cut_above)
     sphere.add_callback('cut_branch', self.cut_branch)
     sphere.add_callback('delete', self.delete_articulation_sphere)
     for name, f in self.additional_sphere_callbacks:
         sphere.add_callback(name, f)
     self.generate()
Exemplo n.º 41
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, size=wx.Size(320, 320))
        self.SetBackgroundColour(wx.Colour(0, 0, 0))

        self.interaction_style = st.StyleStateManager()

        self.ball_reference = None
        self.initial_foco = None

        style =  vtk.vtkInteractorStyleTrackballCamera()
        self.style = style

        interactor = wxVTKRenderWindowInteractor(self, -1, size = self.GetSize())
        interactor.SetInteractorStyle(style)
        self.interactor = interactor

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.EXPAND)
        self.sizer = sizer
        self.SetSizer(sizer)
        self.Layout()

        # It would be more correct (API-wise) to call interactor.Initialize() and
        # interactor.Start() here, but Initialize() calls RenderWindow.Render().
        # That Render() call will get through before we can setup the
        # RenderWindow() to render via the wxWidgets-created context; this
        # causes flashing on some platforms and downright breaks things on
        # other platforms.  Instead, we call widget.Enable().  This means
        # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE,
        # that doesn't matter.
        interactor.Enable(1)

        ren = vtk.vtkRenderer()
        interactor.GetRenderWindow().AddRenderer(ren)
        self.ren = ren

        self.raycasting_volume = False

        self.onclick = False

        self.text = vtku.Text()
        self.text.SetValue("")
        self.ren.AddActor(self.text.actor)


        self.slice_plane = None

        self.view_angle = None

        self.__bind_events()
        self.__bind_events_wx()

        self.mouse_pressed = 0
        self.on_wl = False

        self.picker = vtk.vtkPointPicker()
        interactor.SetPicker(self.picker)
        self.seed_points = []

        self.points_reference = []

        self.measure_picker = vtk.vtkPropPicker()
        #self.measure_picker.SetTolerance(0.005)
        self.measures = []

        self._last_state = 0

        self.repositioned_axial_plan = 0
        self.repositioned_sagital_plan = 0
        self.repositioned_coronal_plan = 0
        self.added_actor = 0

        self._mode_cross = False
        self._to_show_ball = 0
        self._ball_ref_visibility = False
Exemplo n.º 42
0
    def initView(self, data, widget):
        super(SingleDataView, self).initView(data, widget)
        
        shapeList = data.getData().shape
        y, x = shapeList[-2], shapeList[-1]
        self.dimension = len(shapeList) == 2
        
        self.reslice_mapper = vtk.vtkImageResliceMapper()
        self.reslice_mapper.SetInput(self.image_resample.GetOutput())
        self.reslice_mapper.SliceFacesCameraOn()
        self.reslice_mapper.SliceAtFocalPointOn()
        self.reslice_mapper.JumpToNearestSliceOn()
        self.reslice_mapper.BorderOff()
        self.reslice_mapper.BackgroundOn()
        
        array = data.getData()
        self.minI = array.min()
        self.maxI = array.max()
#        self.minI = 0
#        self.maxI = 255
        image_property = vtk.vtkImageProperty()
        image_property.SetColorWindow(self.maxI - self.minI)
        image_property.SetColorLevel((self.maxI + self.minI) / 2.0)
        image_property.SetAmbient(0.0)
        image_property.SetDiffuse(1.0)
        image_property.SetOpacity(1.0)
        image_property.SetInterpolationTypeToLinear()
        
        self.image_slice = vtk.vtkImageSlice()
        self.image_slice.SetMapper(self.reslice_mapper)
        self.image_slice.SetProperty(image_property)
        
        self.renderer.AddViewProp(self.image_slice)
        
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.interactor_style = vtk.vtkInteractorStyleImage()
        self.interactor_style.SetInteractionModeToImage3D()
        self.window_interactor.SetInteractorStyle(self.interactor_style)
        self.render_window.SetInteractor(self.window_interactor)
        point_picker = vtk.vtkPointPicker()
        self.window_interactor.SetPicker(point_picker)
        
        self.render_window.GlobalWarningDisplayOff()
        self.render_window.Render()
        self.camera = self.renderer.GetActiveCamera()
        self.camera.ParallelProjectionOn()
        w, h = self.window_interactor.GetSize()
        if h * x * self.space[0] < w * y * self.space[1]:
            scale = y / 2.0 * self.space[1]
        else:
            scale = h * x  * self.space[0] / 2.0 / w
        self.camera.SetParallelScale(scale)
        point = self.camera.GetFocalPoint()
        dis = self.camera.GetDistance()
        self.camera.SetViewUp(0, -1, 0)
        self.camera.SetPosition(point[0], point[1], point[2] - dis)
        self.renderer.ResetCameraClippingRange()
        
        # View of image
        self.view = 2
                
        self.interactor_style.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
        self.interactor_style.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)
        self.interactor_style.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
        self.interactor_style.AddObserver("MiddleButtonPressEvent", self.MiddleButtonPressCallback)
        self.interactor_style.AddObserver("RightButtonPressEvent", self.RightButtonPressCallback)
        self.interactor_style.AddObserver("RightButtonReleaseEvent", self.RightButtonReleaseCallback)
        self.interactor_style.AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.interactor_style.AddObserver("CharEvent", self.CharCallback)
        
        #self.plugin[0].enable(self)
        self.updateAfter()
        
        self.render_window.Render()
mapper.SetInputConnection(checkers.GetOutputPort())
mapper.SliceAtFocalPointOn()
mapper.SliceFacesCameraOn()
imageSlice = vtk.vtkImageSlice()
imageSlice.SetMapper(mapper)
imageSlice.GetProperty().SetColorLevel(127.5)
imageSlice.GetProperty().SetColorWindow(255)
renderer=vtk.vtkRenderer()
renderer.AddViewProp(imageSlice)

window=vtk.vtkRenderWindow()
window.SetSize(size,size)
window.AddRenderer(renderer)

window.Render()
pp = vtk.vtkPointPicker()
cp = vtk.vtkCellPicker()
p  = vtk.vtkPicker()
errors = 0
for (i,j,cid,pid) in ((20,40,-1,-1),(160,100,821341,825800),(240,300,938658,943010)):
    pos=[i,j]

    # Test prop picker
    result = p.Pick(pos[0],pos[1],0,renderer)
    if (result != 0) != (pid != -1):
      errors += 1
      print("Picker at {} returns {} expected".format(pos,result) )

    # Test cell picker
    result = cp.Pick(pos[0],pos[1],0,renderer)
    if (result != 0) != (pid != -1):
Exemplo n.º 44
0
 def KeyPressed(self,obj,event):
     key = obj.GetKeySym()
     if key == 'l':
         self.DisplayedMesh = (self.DisplayedMesh+1)%3
         if self.DisplayedMesh == 0:
             self.MeshActor.GetMapper().SetInput(self.Mesh)
         elif self.DisplayedMesh == 1:
             self.MeshActor.GetMapper().SetInput(self.PreviewMesh)
         elif self.DisplayedMesh == 2:
             self.MeshActor.GetMapper().SetInput(self.ClippedMesh)
         self.vmtkRenderer.RenderWindow.Render()
     elif key =='c':
         self.ClipMesh()
         if self.DisplayedMesh == 1:
             self.MeshActor.GetMapper().SetInput(self.PreviewMesh)
         elif self.DisplayedMesh == 2:
             self.MeshActor.GetMapper().SetInput(self.ClippedMesh)
         self.vmtkRenderer.RenderWindow.Render()
     #elif key =='m':
         #self.ClipMeshLine()
         #if self.DisplayedMesh == 1:
             #self.MeshActor.GetMapper().SetInput(self.PreviewMesh)
         #elif self.DisplayedMesh == 2:
             #self.MeshActor.GetMapper().SetInput(self.ClippedMesh)
         #self.vmtkRenderer.RenderWindow.Render()
     elif key == 'space':
         #Disable the sphere Widget so as not to pick it
         self.SphereWidget.Off()
         #add a new sphere
         picker = vtk.vtkPointPicker()
         picker.SetTolerance(1E-3 * self.Centerlines.GetLength())
         eventPosition = obj.GetEventPosition()
         result = picker.Pick(float(eventPosition[0]),float(eventPosition[1]),0.0,self.vmtkRenderer.Renderer)
         if result == 0:
             #Reenable the sphere widget
             self.SphereWidget.On()
             return
         pickId = picker.GetPointId()
         #Only insert a new sphere if this id is not already in the list
         if self.SpheresIndices.IsId(pickId) == -1:
             self.CurrentSphereId = self.Spheres.GetPoints().InsertNextPoint(self.Centerlines.GetPoint(pickId))
             self.SpheresIndices.InsertNextId(pickId)
             interpolatedArray = self.Centerlines.GetPointData().GetArray("InterpolatedRadius")
             if interpolatedArray and (interpolatedArray.GetValue(pickId) != 0.):
                 self.SpheresRadii.InsertNextValue(interpolatedArray.GetValue(pickId))
             elif self.RadiusArray:
                 self.SpheresRadii.InsertNextValue(self.RadiusArray.GetValue(pickId))
             else:
                 self.SpheresRadii.InsertNextValue(self.Centerlines.GetLength()*0.01)
             self.Spheres.Modified()
             self.PlaceSphere()
         #Reenable the sphere widget
         self.SphereWidget.On()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'KP_Add' and self.CurrentSphereId != -1:
         #increase sphere radius
         newval = self.Spheres.GetPointData().GetScalars().GetValue(self.CurrentSphereId) + self.Centerlines.GetLength()*0.01
         self.Spheres.GetPointData().GetScalars().SetValue(self.CurrentSphereId,newval)
         self.Spheres.Modified()
         self.PlaceSphere()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'KP_Subtract' and self.CurrentSphereId != -1:
         #decrease sphere radius
         newval = self.Spheres.GetPointData().GetScalars().GetValue(self.CurrentSphereId) - self.Centerlines.GetLength()*0.01
         if newval> 0:
             self.Spheres.GetPointData().GetScalars().SetValue(self.CurrentSphereId,newval)
             self.Spheres.Modified()
             self.PlaceSphere()
             self.vmtkRenderer.RenderWindow.Render()
     elif key == 'n' and self.CurrentSphereId != -1:
         #skip to next sphere
         self.CurrentSphereId = (self.CurrentSphereId + 1) % self.Spheres.GetNumberOfPoints();
         self.PlaceSphere()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'v' and self.CurrentSphereId != -1:
         #skip to previous sphere
         self.CurrentSphereId = (self.CurrentSphereId - 1) % self.Spheres.GetNumberOfPoints();
         self.PlaceSphere()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'u':
         #undo
         self.InitializeSpheres()
         self.Spheres.Modified()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'd' and self.CurrentSphereId != -1:
         #delete the current sphere
         #if no spheres would be left initialize
         if self.Spheres.GetNumberOfPoints() == 1:
             self.InitializeSpheres()
         else:
             #Copy the spheres into a new structure
             oldPoints = vtk.vtkPoints()
             oldPoints.DeepCopy(self.Spheres.GetPoints())
             self.Spheres.Initialize()
             spherePoints = vtk.vtkPoints()
             for i in range(0,oldPoints.GetNumberOfPoints()):
                 if i != self.CurrentSphereId:
                     spherePoints.InsertNextPoint(oldPoints.GetPoint(i))
             self.Spheres.SetPoints(spherePoints)
             self.SpheresRadii.RemoveTuple(self.CurrentSphereId)
             self.Spheres.GetPointData().SetScalars(self.SpheresRadii)
             self.SpheresIndices.DeleteId(self.SpheresIndices.GetId(i))
             self.CurrentSphereId = (self.CurrentSphereId + 1) % self.Spheres.GetNumberOfPoints()
             self.PlaceSphere()
         self.vmtkRenderer.RenderWindow.Render()
         
     elif key == 'o':
         #Display the interpolated spheres
         self.InterpolatedSpheresActor.SetVisibility(not self.InterpolatedSpheresActor.GetVisibility())
         self.vmtkRenderer.RenderWindow.Render()
     elif key=='b':
         #Display/hide the polyball surface
         if self.PolyBallActor.GetVisibility():
             self.PolyBallActor.VisibilityOff()
         elif self.PolyBall != None:
             self.BuildPolyBallSurface()
             self.PolyBallActor.VisibilityOn()
             self.vmtkRenderer.RenderWindow.Render()
     elif key == 'x':
         #Switch between transparent/opaque mesh for better visualisation
         if self.MeshActor.GetProperty().GetOpacity() == 0.25:
             self.MeshActor.GetProperty().SetOpacity(1.)
         else:
             self.MeshActor.GetProperty().SetOpacity(0.25)
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'y':
         #Switch between transparent/opaque polyball for better visualisation
         if self.PolyBallActor.GetProperty().GetOpacity() == 0.25:
             self.PolyBallActor.GetProperty().SetOpacity(1.)
             self.MeshActor.VisibilityOff()
         else:
             self.PolyBallActor.GetProperty().SetOpacity(0.25)
             self.MeshActor.VisibilityOn()
         self.vmtkRenderer.RenderWindow.Render()
     elif key == 'f':
         self.PolyBallType = (self.PolyBallType + 1)%2
Exemplo n.º 45
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """ 
        
        texture_ispec = self.getInputSpec(  1 )                
        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()       
        self.sliceCenter = [ (xMax-xMin)/2, (yMax-yMin)/2, (zMax-zMin)/2  ]       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        dataType = self.input().GetScalarTypeAsString()
        self.setMaxScalarValue( self.input().GetScalarType() )
        self.colorByMappedScalars = False
        rangeBounds = self.getRangeBounds()

        dr = rangeBounds[1] - rangeBounds[0]
        range_offset = .2*dr
        self.range = [ rangeBounds[0] + range_offset, rangeBounds[1] - range_offset ]
        print "Data Type = %s, range = (%f,%f), range bounds = (%f,%f), max_scalar = %s" % ( dataType, self.range[0], self.range[1], rangeBounds[0], rangeBounds[1], self._max_scalar_value )
        self.probeFilter = None
        textureRange = self.range
        if texture_ispec and texture_ispec.input():
            self.probeFilter = vtk.vtkProbeFilter()
            textureRange = texture_ispec.input().GetScalarRange()
            self.probeFilter.SetSource( texture_ispec.input() )
            self.generateTexture = True

        if (self.surfacePicker == None):           
            self.surfacePicker  = vtk.vtkPointPicker()
                    
        self.levelSetFilter = vtk.vtkContourFilter()
        self.inputModule().inputToAlgorithm( self.levelSetFilter )
        self.levelSetMapper = vtk.vtkPolyDataMapper()
        self.levelSetMapper.SetColorModeToMapScalars()
        if ( self.probeFilter == None ):
            imageRange = self.getImageValues( self.range ) 
            self.levelSetMapper.SetInputConnection( self.levelSetFilter.GetOutputPort() ) 
            self.levelSetMapper.SetScalarRange( imageRange[0], imageRange[1] )
        else: 
            self.probeFilter.SetInputConnection( self.levelSetFilter.GetOutputPort() )
            self.levelSetMapper.SetInputConnection( self.probeFilter.GetOutputPort() ) 
            self.levelSetMapper.SetScalarRange( textureRange )
            
        if texture_ispec and texture_ispec.input():
            colormapManager = self.getColormapManager( index=1 )     
            colormapManager.setAlphaRange ( self.opacityRange ) 
            self.levelSetMapper.SetLookupTable( colormapManager.lut ) 
            self.levelSetMapper.UseLookupTableScalarRangeOn()
        else:
            colormapManager = self.getColormapManager()     
            colormapManager.setAlphaRange ( self.opacityRange ) 
            self.levelSetMapper.SetLookupTable( colormapManager.lut ) 
            self.levelSetMapper.UseLookupTableScalarRangeOn()
        
        self.updateLevels()
          
#        levelSetMapper.SetColorModeToMapScalars()  
#        levelSetActor = vtk.vtkLODActor() 
        self.levelSetActor = vtk.vtkActor() 
#            levelSetMapper.ScalarVisibilityOff() 
#            levelSetActor.SetProperty( self.levelSetProperty )              
        self.levelSetActor.SetMapper( self.levelSetMapper )

        self.cursorActor     = vtk.vtkActor()
        self.cursorProperty  = None 
        self.cursor = vtk.vtkSphereSource()
        self.cursor.SetRadius(2.0)
        self.cursor.SetThetaResolution(8)
        self.cursor.SetPhiResolution(8)
        
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.cursor.GetOutput())
        self.cursorActor.SetMapper(mapper)        
        self.createDefaultProperties() 
                                                            
#        pointData = self.levelSetFilter.GetOutput().GetPointData()
#        pointData.SetScalars( colorLevelData )
        
#        if pd <> None:
#            na = pd.GetNumberOfArrays()
#            print " ** Dataset has %d arrays. ** " % ( pd.GetNumberOfArrays() )
#            for i in range( na ): print "   ---  Array %d: %s " % ( i,  str( pd.GetArrayName(i) ) )
#        else: print " ** No point data. "
           
        self.renderer.AddActor( self.levelSetActor )
        self.surfacePicker.AddPickList( self.levelSetActor )
        self.surfacePicker.PickFromListOn()
        self.renderer.AddViewProp(self.cursorActor)
        self.cursorActor.SetProperty(self.cursorProperty)
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) 
        self.set3DOutput()                                              
Exemplo n.º 46
0
ren1.AddActor(aVertexActor)
aVertexActor.GetProperty().SetDiffuseColor(1,1,1)
ren1.AddActor(aPolyVertexActor)
aPolyVertexActor.GetProperty().SetDiffuseColor(1,1,1)
ren1.AddActor(aPentaActor)
aPentaActor.GetProperty().SetDiffuseColor(.2,.4,.7)
ren1.AddActor(aHexaActor)
aHexaActor.GetProperty().SetDiffuseColor(.7,.5,1)
ren1.ResetCamera()
ren1.GetActiveCamera().Azimuth(30)
ren1.GetActiveCamera().Elevation(20)
ren1.GetActiveCamera().Dolly(1.25)
ren1.ResetCameraClippingRange()
renWin.Render()
cellPicker = vtk.vtkCellPicker()
pointPicker = vtk.vtkPointPicker()
worldPicker = vtk.vtkWorldPointPicker()
cellCount = 0
pointCount = 0
ren1.IsInViewport(0,0)
x = 0
while x <= 265:
    y = 100
    while y <= 200:
        cellPicker.Pick(x,y,0,ren1)
        pointPicker.Pick(x,y,0,ren1)
        worldPicker.Pick(x,y,0,ren1)
        if (cellPicker.GetCellId() != "-1"):
            cellCount = cellCount + 1
            pass
        if (pointPicker.GetPointId() != "-1"):
Exemplo n.º 47
0
 def initView(self, data, widget):
     image_type = data.getITKImageType()
     self.image = data.getITKImage()
     self.space = data.getResolution().tolist()
     
     if len(self.space) == 3:
         self.space = [float(x) / self.space[-1] for x in self.space]
     
     self.image.SetSpacing(self.space)
     self.rescale_filter = itk.RescaleIntensityImageFilter[image_type, image_type].New()
     self.rescale_filter.SetOutputMinimum(0)
     self.rescale_filter.SetOutputMaximum(255)
     self.rescale_filter.SetInput(self.image)
     self.itk_vtk_converter = itk.ImageToVTKImageFilter[image_type].New()
     self.itk_vtk_converter.SetInput(self.rescale_filter.GetOutput())
     self.image_resample = vtk.vtkImageResample()
     self.image_resample.SetInput(self.itk_vtk_converter.GetOutput())
     
     data = self.parent.getData()
     image_type = data.getITKImageType()
     self.image2 = data.getITKImage()
     self.space2 = data.getResolution().tolist()
     
     if len(self.space2) == 3:
         self.space2 = [float(x) / self.space2[-1] for x in self.space2]
     self.image2.SetSpacing(self.space2)
     shapeList = data.getData().shape
     y, x = shapeList[-2], shapeList[-1]
     self.dimension = len(shapeList) == 2
     
     self.rescale_filter2 = itk.RescaleIntensityImageFilter[image_type, image_type].New()
     self.rescale_filter2.SetOutputMinimum(0)
     self.rescale_filter2.SetOutputMaximum(255)
     self.rescale_filter2.SetInput(self.image2)
     self.itk_vtk_converter2 = itk.ImageToVTKImageFilter[image_type].New()
     self.itk_vtk_converter2.SetInput(self.rescale_filter2.GetOutput())
     self.image_resample2 = vtk.vtkImageResample()
     self.image_resample2.SetInput(self.itk_vtk_converter2.GetOutput())
     
     self.checkers = vtk.vtkImageCheckerboard()
     self.checkers.SetInput1(self.image_resample.GetOutput())
     self.checkers.SetInput2(self.image_resample2.GetOutput())
     self.division = 3
     self.checkers.SetNumberOfDivisions(self.division, self.division, 0)
     
     self.renderer = vtk.vtkRenderer()
     self.render_window = widget.GetRenderWindow()
     self.render_window.AddRenderer(self.renderer)
     
     self.reslice_mapper = vtk.vtkImageResliceMapper()
     self.reslice_mapper.SetInput(self.checkers.GetOutput())
     self.reslice_mapper.SliceFacesCameraOn()
     self.reslice_mapper.SliceAtFocalPointOn()
     self.reslice_mapper.JumpToNearestSliceOn()
     self.reslice_mapper.BorderOff()
     self.reslice_mapper.BackgroundOn()
     
     array = data.getData()
     self.minI = 0
     self.maxI = 255
     image_property = vtk.vtkImageProperty()
     image_property.SetColorWindow(self.maxI - self.minI)
     image_property.SetColorLevel((self.maxI + self.minI) / 2.0)
     image_property.SetAmbient(0.0)
     image_property.SetDiffuse(1.0)
     image_property.SetOpacity(1.0)
     image_property.SetInterpolationTypeToLinear()
     
     self.image_slice = vtk.vtkImageSlice()
     self.image_slice.SetMapper(self.reslice_mapper)
     self.image_slice.SetProperty(image_property)
     
     self.renderer.AddViewProp(self.image_slice)
     
     self.window_interactor = vtk.vtkRenderWindowInteractor()
     self.interactor_style = vtk.vtkInteractorStyleImage()
     self.interactor_style.SetInteractionModeToImage3D()
     self.window_interactor.SetInteractorStyle(self.interactor_style)
     self.render_window.SetInteractor(self.window_interactor)
     point_picker = vtk.vtkPointPicker()
     self.window_interactor.SetPicker(point_picker)
     
     self.render_window.GlobalWarningDisplayOff()
     self.render_window.Render()
     self.camera = self.renderer.GetActiveCamera()
     self.camera.ParallelProjectionOn()
     w, h = self.window_interactor.GetSize()
     if h * x * self.space[0] < w * y * self.space[1]:
         scale = y / 2.0 * self.space[1]
     else:
         scale = h * x  * self.space[0] / 2.0 / w
     self.camera.SetParallelScale(scale)
     point = self.camera.GetFocalPoint()
     dis = self.camera.GetDistance()
     self.camera.SetViewUp(0, -1, 0)
     self.camera.SetPosition(point[0], point[1], point[2] - dis)
     self.renderer.ResetCameraClippingRange()
     
     # View of image
     self.view = 2
             
     self.interactor_style.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
     self.interactor_style.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)
     self.interactor_style.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
     self.interactor_style.AddObserver("MiddleButtonPressEvent", self.MiddleButtonPressCallback)
     self.interactor_style.AddObserver("RightButtonPressEvent", self.RightButtonPressCallback)
     self.interactor_style.AddObserver("RightButtonReleaseEvent", self.RightButtonReleaseCallback)
     self.interactor_style.AddObserver("KeyPressEvent", self.KeyPressCallback)
     self.interactor_style.AddObserver("CharEvent", self.CharCallback)
     
     self.updateAfter()
     self.render_window.Render()
Exemplo n.º 48
0
    def keypress_handler(self, obj, event):

        key = obj.GetKeyCode()
        pos2d = obj.GetEventPosition()

        # create new sphere
        if key == "k":

            self.scene.add_articulation_sphere(pos2d)

        # mark sphere for connection if no other marker set, connect otherwise
        elif key == "c":

            selected_sphere = None # there should be at most 1
            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    selected_sphere = sphere
                    break
            if not selected_sphere: return
            picker = vtk.vtkPropPicker()
            if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
                actor = picker.GetActor()
                if self.scene.get_active_polytube_model() and \
                  actor is self.scene.get_active_polytube_model().actor:
                    m = self.scene.get_active_polytube_model()
                    m.connect_articulation_sphere_to_closest_point(
                                                        selected_sphere, pos2d)

        # select sphere (only one at a time)
        elif key == "s":

            for sphere in self.scene.actor_to_sphere.values():
                sphere.set_selected(False)

            picker = vtk.vtkPropPicker()
            if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
                actor = picker.GetActor()
                if actor in self.scene.actor_to_sphere:
                    self.scene.actor_to_sphere[actor].toggle_selected()

        # delete selected sphere
        elif key == "d":

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    self.scene.delete_articulation_sphere(sphere)
                    sphere.run_callbacks('delete')

        elif key == 'D':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    n = sphere.delete_selected_points()
                    self.frame.SetStatusText('Deleted %d points' % n)
                    wiz = self.frame.mvl_wiz
                    if wiz.model is not None and wiz.curr_page == wiz.pages[0]:
                        wiz.model.P = self.scene.get_active_point_cloud().P
                        wiz.curr_page.on_run(None)

        # cut polytube model node
        elif key in 'xX':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    if key == 'x':
                        sphere.run_callbacks('cut_above')
                    else:
                        sphere.run_callbacks('cut_branch')

        # fly-to (set camera focal point)
        elif key == "f":

            if self.scene.get_active_point_cloud():
                self.scene.get_active_point_cloud().actor.SetPickable(True)
                picker = vtk.vtkPointPicker()
                if picker.Pick(pos2d[0], pos2d[1], 0, self.frame.ren):
                    self.frame.iren.FlyTo(self.frame.ren,
                                          *picker.GetPickPosition())
                self.scene.get_active_point_cloud().actor.SetPickable(False)

        elif key == 'N':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    wiz = self.frame.mvl_wiz
                    if wiz.model is not None and wiz.curr_page == wiz.pages[0]:
                        sphere.stitch_neighborhood_graph(wiz.model.N_full)
                        wiz.model.find_nn_connected_components()
                        n_comps, n_nodes_biggest, density = \
                                            wiz.model.get_connectivity_infos()
                        self.scene.set_point_cloud_graph(wiz.model.N_full)
                        wiz.pages[0].set_nn_connected_components_color_scheme(
                                                         wiz.model.N_components)
                        wiz.pages[1].is_dirty = True
                        st = 'Found %s connected component%s (biggest has ' \
                             '%s nodes; conn. factor = %f)' % \
                             (n_comps, 's' if n_comps>1 else '',
                              n_nodes_biggest, density)
                        self.frame.SetStatusText(st)