Exemplo n.º 1
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, sideBreast, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        #alignR = int(raw_input('\nAlign right? Yes:1 No:0 : '))
        #if alignR:
        if(sideBreast=="Right"):
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
        
        # Change info origin
        translated_T2image = vtk.vtkImageChangeInformation()
        translated_T2image.SetInput( transformed_T2image )
        translated_T2image.SetOutputOrigin(self.T2origin)
        translated_T2image.Update()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInput(translated_T2image.GetOutput())
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInput( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
Exemplo n.º 2
0
    def run(self):
        self.vtk_renderer = vtkRenderer()
        self.setup_gui()
        self.setup_grid()

        # Handle any deferred configuration
        # Overlaid polygons
        for args in self.conf_overlaidPolygons:
            self.overlay_polygon_internal(*args)
        # Draw (and maybe alter) the axes
        if self.vtk_drawAxes:
            self.vtk_axes = vtkCubeAxesActor2D()
            # Perform all of the alterations required, by applying func to the vtk_axes instance (with the given args).
            for func, args in self.conf_axesAlterations:
                func(*((self.vtk_axes,) + args))
        # Alter the Tk root as necessary.
        for func, args in self.conf_tkAlterations:
            func(*((self.tk_root,) + args))
        # Finished with deferred configuration.

        # Draw Height Quantities
        for q in self.height_quantities:
            self.update_height_quantity(q, self.height_dynamic[q])
            self.draw_height_quantity(q)
            
        self.tk_root.mainloop()
Exemplo n.º 3
0
    def addAxes(self, obj):
        """Add axes"""
        tprop = self.textProperty(fontsize = self.opt.axes_fontsize)

        axes = vtk.vtkCubeAxesActor2D()
        axes.SetInput(obj.GetOutput())
        axes.SetLabelFormat(self.opt.axes_format)
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(1.5)
        axes.SetCornerOffset(0.0)

        axes.GetProperty().SetColor(tprop.GetColor())
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)

        if self.opt.axes_levels:
            axes.SetNumberOfLabels()
        if self.opt.axes_xlabel:
            axes.SetXLabel(self.opt.axes_xlabel)
        if self.opt.axes_ylabel:
            axes.SetYLabel(self.opt.axes_ylabel)
        if self.opt.axes_zlabel:
            axes.SetZLabel(self.opt.axes_zlabel)

        return axes
Exemplo n.º 4
0
Arquivo: Axes.py Projeto: sldion/DNACC
    def __init__ (self, mod_m):
        debug ("In Axes::__init__ ()")
        Common.state.busy ()
        Base.Objects.Module.__init__ (self, mod_m)
        self.axes = vtk.vtkCubeAxesActor2D ()
        txt = ("X", "Y", "Z")
        for i in range (0, 3):
            eval ("self.axes.%sAxisVisibilityOn ()"%(txt[i]))

        self.axes.SetNumberOfLabels (2)
        self.axes.SetFontFactor (1.35)
        self.axes.SetFlyModeToOuterEdges ()
        self.axes.SetCornerOffset (0.0)
        self.axes.ScalingOff ()
        self.axes.GetProperty ().SetColor (*Common.config.fg_color)
        self.axes.SetCamera (self.renwin.get_active_camera ())
        if hasattr(self.axes, "GetAxisTitleTextProperty"):
            ttp = self.axes.GetAxisTitleTextProperty()
            ltp = self.axes.GetAxisLabelTextProperty()
            ttp.ShadowOff()
            fg_color = Common.config.fg_color
            ttp.SetColor(fg_color)
            ltp.SetColor(fg_color)
            ltp.ShadowOff()
        else:
            self.axes.ShadowOff ()
        self.renwin.add_actors (self.axes)
        self.axes.SetInput (self.mod_m.GetOutput ())
        self.actor = self.axes
        # used for the pipeline browser
        self.pipe_objs = self.axes
        self._gui_init ()
        Common.state.idle ()
Exemplo n.º 5
0
def cube_axes(size):
    render = vtk.vtkRenderer()

    cube = vtk.vtkCubeSource()
    cube.SetXLength(size)
    cube.SetYLength(size)
    cube.SetZLength(size)

    # Create a text property for both cube axes
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(layer_color, layer_color, layer_color)
    tprop.ShadowOn()

    # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
    # draw the axes.  Add the actor to the renderer.
    axes = vtk.vtkCubeAxesActor2D()
    axes.SetInputConnection(cube.GetOutputPort())
    axes.SetCamera(render.GetActiveCamera())
    axes.SetLabelFormat("%6.4g")
    axes.SetFlyModeToOuterEdges()
    axes.SetFontFactor(0.8)
    axes.GetAxisLabelTextProperty().SetColor(cube_color, cube_color,
                                             cube_color)
    axes.SetAxisTitleTextProperty(tprop)
    axes.SetAxisLabelTextProperty(tprop)
    axes.GetProperty().SetColor(cube_color, cube_color, cube_color)

    return axes
Exemplo n.º 6
0
    def run(self):
        self.vtk_renderer = vtkRenderer()
        self.setup_gui()
        self.setup_grid()

        # Handle any deferred configuration
        # Overlaid polygons
        for args in self.conf_overlaidPolygons:
            self.overlay_polygon_internal(*args)
        # Draw (and maybe alter) the axes
        if self.vtk_drawAxes:
            self.vtk_axes = vtkCubeAxesActor2D()
            # Perform all of the alterations required, by applying func to the vtk_axes instance (with the given args).
            for func, args in self.conf_axesAlterations:
                func(*((self.vtk_axes, ) + args))
        # Alter the Tk root as necessary.
        for func, args in self.conf_tkAlterations:
            func(*((self.tk_root, ) + args))
        # Finished with deferred configuration.

        # Draw Height Quantities
        for q in self.height_quantities:
            self.update_height_quantity(q, self.height_dynamic[q])
            self.draw_height_quantity(q)

        self.tk_root.mainloop()
Exemplo n.º 7
0
    def __init__(self, parent):
        QVTKRenderWindowInteractor.__init__(self, parent)

        self.renderer = vtk.vtkRenderer()
        self.GetRenderWindow().AddRenderer(self.renderer)
        
        interactor = vtk.vtkInteractorStyleSwitch()
        self._Iren.SetInteractorStyle(interactor)
                
        self.surface = None

        # Remainng calls set up axes.
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1,1,1)

        # Create a faint outline to go with the axes.
        self.outline = vtk.vtkOutlineFilter()

        # Initially set up with a box as input.  This will be changed
        # to a plot once the user clicks something.
        self.box = vtk.vtkBox()
        self.box.SetBounds(0,10,0,10,0,10)
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(self.box)
        sample.SetSampleDimensions(2,2,2)
        sample.SetModelBounds(0,10,0,10,0,5)
        sample.ComputeNormalsOff()

        self.outline.SetInputConnection(sample.GetOutputPort())
        mapOutline = vtk.vtkPolyDataMapper()
        mapOutline.SetInputConnection(self.outline.GetOutputPort())
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(mapOutline)
        self.outlineActor.GetProperty().SetColor(1,1,1)
        self.outlineActor.GetProperty().SetOpacity(.25)
        self.renderer.AddActor(self.outlineActor)

        self.axes = vtk.vtkCubeAxesActor2D()
        self.axes.SetCamera(self.renderer.GetActiveCamera())
        self.axes.SetFlyModeToOuterEdges()

        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("MPI Rank")
        self.axes.SetYLabel("Progress")
        self.axes.SetZLabel("Effort")
        self.axes.SetInput(sample.GetOutput())
        self.renderer.AddViewProp(self.axes)

        # Keep original camera around in case it gets changed
        self.originalCamera = self.renderer.GetActiveCamera()

        self.renderer.GetActiveCamera().Pitch(90)     # Want effort to be vertical
        self.renderer.GetActiveCamera().OrthogonalizeViewUp()
        self.renderer.ResetCamera()
        self.renderer.GetActiveCamera().Elevation(15)  # Be slightly above the data
Exemplo n.º 8
0
    def __init__(self,
                 plots=None,
                 las_header=None,
                 axes_on=False,
                 app=None,
                 background=(.2, .3, .4)):
        """
        :param plots: list of VTKPointClouds to plot
        :param las_header: a las_header that is optionally supplied if reading from a las file, helpful for saving
        :param axes_on: flag for turning axes on/off
        :param app: the main QApplication driving the GUI
        :param background: tuple of 0-1's for background color
        """
        super().__init__()
        self.plots = plots
        self.las_header = las_header
        self.background = background
        self.default_viewup = (0.0, 1.0, 0.0)
        self.axes_on = axes_on
        # self.app = Qt.QApplication(sys.argv)
        self.app = app
        self.main = Qt.QMainWindow()
        self.main.__init__()
        self.frame = Qt.QFrame()
        self.hl = Qt.QHBoxLayout()
        self.bl = Qt.QVBoxLayout()

        self.widgets = []
        self.widget_defaults = []
        self.widget_point_actors = []
        self.axes_actors = []
        if self.plots is not None:
            for i in range(len(plots)):
                vtk_widget = QVTKRenderWindowInteractor(self.frame)
                self.widgets.append(vtk_widget)
                self.hl.addWidget(vtk_widget)
                self.axes_actors.append(vtk.vtkCubeAxesActor2D())
                self.plot_point_cloud_qt(plots[i], vtk_widget)

            for w in self.widgets:
                position = w.GetRenderWindow().GetInteractor(
                ).GetInteractorStyle().camera.GetPosition()
                focus = w.GetRenderWindow().GetInteractor().GetInteractorStyle(
                ).camera.GetFocalPoint()
                viewup = w.GetRenderWindow().GetInteractor(
                ).GetInteractorStyle().camera.GetViewUp()
                self.widget_defaults.append((position, focus, viewup))

        self.hl.addLayout(self.bl)
        self.add_buttons()
        self.frame.setLayout(self.hl)
        self.main.setCentralWidget(self.frame)
        self.main.show()
        for w in self.widgets:
            w.GetRenderWindow().GetInteractor().Initialize()
            w.GetRenderWindow().GetInteractor().Start()
Exemplo n.º 9
0
def scale_bar_actor(center,
                    camera,
                    length=10000,
                    color=(0, 0, 0),
                    linewidth=5,
                    font_size=20):
    """Creates a xyz 3d scale bar actor located at a specific location with a given size

    Parameters
    ----------
    center : iterable
        a length 3 iterable of xyz position
    camera : vtk.vtkCamera
        the camera the scale bar should follow
    length : int, optional
        length of each of the xyz axis, by default 10000
    color : tuple, optional
        color of text and lines, by default (0,0,0)
    linewidth : int, optional
        width of line in pixels, by default 5
    font_size : int, optional
        font size of xyz labels, by default 20

    Returns
    -------
    vtk.vktActor
        scale bar actor to add to render_actors

    """
    axes_actor = vtk.vtkCubeAxesActor2D()
    axes_actor.SetBounds(center[0], center[0] + length, center[1],
                         center[1] + length, center[2], center[2] + length)
    # this means no real labels
    axes_actor.SetLabelFormat("")
    axes_actor.SetCamera(camera)
    # this turns off the tick marks and labelled numbers
    axes_actor.SetNumberOfLabels(0)
    # this affects whether the corner of the 3 axis
    # changes as you rotate the view
    # this option makes it stay constant
    axes_actor.SetFlyModeToNone()
    axes_actor.SetFontFactor(1.0)
    axes_actor.GetProperty().SetColor(*color)
    axes_actor.GetProperty().SetLineWidth(linewidth)
    # this controls the color of text
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(*color)
    # no shadows on text
    tprop.ShadowOff()
    tprop.SetFontSize(font_size)
    # makes the xyz and labels the same
    axes_actor.SetAxisTitleTextProperty(tprop)
    axes_actor.SetAxisLabelTextProperty(tprop)

    return axes_actor
Exemplo n.º 10
0
    def visualize_map(self, VOIclip):
        # get info from image before visualization
        VOIclip.UpdateInformation()
        self.dims = VOIclip.GetDimensions()
        (xMin, xMax, yMin, yMax, zMin, zMax) = VOIclip.GetWholeExtent()
        self.spacing = VOIclip.GetSpacing()

        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( VOIclip )
        self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( VOIclip )
        self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( VOIclip )
        self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
        self.zImagePlaneWidget.SetSliceIndex(0)
                
        self.xImagePlaneWidget.On()
        self.yImagePlaneWidget.On()
        self.zImagePlaneWidget.On()
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1, 1, 1)
        tprop.ShadowOff()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetInput(VOIclip)
        axes.SetCamera(self.renderer1.GetActiveCamera())
        axes.SetLabelFormat("%6.4g")
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(1.2)
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axes)
        
        ############
        # bounds and initialize camera
        bounds = VOIclip.GetBounds()
        self.renderer1.ResetCamera(bounds)    
        self.renderer1.ResetCameraClippingRange()
        self.camera.SetViewUp(0.0,-1.0,0.0)
        self.camera.Azimuth(360)
        
        # Initizalize
        #self.renWin1.Render()
        self.renderer1.Render()
        self.iren1.Start()  
                            
        return
Exemplo n.º 11
0
def new_axes_actor(ren: vtk.vtkRenderer, data_source):
    axes = vtk.vtkCubeAxesActor2D()
    axes.SetInputConnection(data_source.GetOutputPort())
    axes.SetCamera(ren.GetActiveCamera())
    axes.SetLabelFormat("%6.4g")
    axes.SetFlyModeToOuterEdges()
    axes.SetFontFactor(0.8)
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(1, 1, 1)
    tprop.ShadowOn()
    axes.SetAxisTitleTextProperty(tprop)
    axes.SetAxisLabelTextProperty(tprop)
    return axes
Exemplo n.º 12
0
def displayPolyAnd3Planes(poly, image, title = 'Polydata and 3 Planes'):
    """
    display a poly and 3 planes
    """
    
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(poly)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetRepresentationToWireframe()
    actor.GetProperty().SetColor(0,0,0) #RED
    
    ren= vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1,1,1)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(ren)
    renwin.SetSize( 700, 700 )
    renwin.SetWindowName(title)
    
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)
    wX,wY,wZ = create3Planes(image)

    wX.SetInteractor(iren); wX.On()
    wY.SetInteractor(iren); wY.On()
    wZ.SetInteractor(iren); wZ.On()

    outline = createOutlineActor(image)
    ren.AddActor(outline)
    
    axes = vtk.vtkCubeAxesActor2D()
    axes.SetCamera(ren.GetActiveCamera())
    axes.SetViewProp(outline)
    ren.AddActor(axes)

    ren.ResetCamera()
    cam1 = ren.GetActiveCamera()
    cam1.Elevation(-90)
    cam1.SetViewUp(0, 0, 1)
    cam1.Azimuth(45)
    ren.ResetCameraClippingRange()
        
    iren.Initialize()
    renwin.Render()
    iren.Start()
Exemplo n.º 13
0
    def visualizemha(self, img_path, image_pos_pat, image_ori_pat, interact):
        '''Display and render volumes, reference frames, actors and widgets'''  
             
        # Proceed to build reference frame for display objects based on DICOM coords   
        mhareader = vtk.vtkMetaImageReader()
        mhareader.SetFileName(img_path)
        mhareader.Update()
        
        self.warpT2_mha = self.mhaTransform(mhareader.GetOutput(), image_pos_pat, image_ori_pat)
        
        self.T2origin = list(self.warpT2_mha.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(self.warpT2_mha.GetExtent())
        print self.T2extent        

        # Initizalize
        self.xImagePlaneWidget.Modified()
        self.yImagePlaneWidget.Modified()
        self.zImagePlaneWidget.Modified()
                
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInputData(self.warpT2_mha )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInputData(self.warpT2_mha )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInputData( self.warpT2_mha )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
    
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInputData(self.warpT2_mha)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)     
        
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()     
                            
        return
Exemplo n.º 14
0
Arquivo: epdp.py Projeto: ecell/newio
    def __create_axes(self):
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetBounds(numpy.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0]) * self.settings.scaling)
        axes.SetRanges(0.0, self.__world_size, 0.0, self.__world_size, 0.0, self.__world_size)
        axes.SetLabelFormat("%g")
        axes.SetFontFactor(1.5)
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(self.settings.axis_annotation_color)
        tprop.ShadowOn()
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        axes.UseRangesOn()
        axes.SetCornerOffset(0.0)

        return axes
Exemplo n.º 15
0
    def makeAxes(self, outline, outlinefilter):
        """ create axes """
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(self.fgColor)
        tprop.ShadowOff()

        prop = vtk.vtkProperty2D()
        prop.SetColor(self.fgColor)

        zax = vtk.vtkCubeAxesActor()
        zax.SetBounds(outline.GetBounds()[0], outline.GetBounds()[1], outline.GetBounds()[2], outline.GetBounds()[3],
                      outline.GetBounds()[4], outline.GetBounds()[4])
        zax.SetDragable(False)
        zax.SetCamera(self.renderer.GetActiveCamera())
        zax.SetFlyModeToOuterEdges()
        zax.DrawXGridlinesOn()
        zax.DrawYGridlinesOn()
        zax.DrawZGridlinesOn()
        zax.SetXTitle('')
        zax.SetYTitle('')
        zax.SetZTitle('')
        zax.SetXAxisMinorTickVisibility(0)
        zax.SetYAxisMinorTickVisibility(0)
        zax.SetZAxisMinorTickVisibility(0)
        zax.SetXAxisLabelVisibility(0)
        zax.SetYAxisLabelVisibility(0)
        zax.SetZAxisLabelVisibility(0)

        axes = vtk.vtkCubeAxesActor2D()
        axes.SetDragable(False)
        axes.SetInputConnection(outlinefilter.GetOutputPort())

        axes.SetCamera(self.renderer.GetActiveCamera())
        axes.SetLabelFormat(self.config.LabelFormat())
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(self.fontFactor)
        axes.SetNumberOfLabels(self.config.NLabels())
        axes.SetXLabel(self.config.XLabel())
        axes.SetYLabel(self.config.YLabel())
        axes.SetZLabel(self.config.ZLabel())
        axes.SetRanges(self.out.GetBounds())
        axes.SetUseRanges(True)
        axes.SetProperty(prop)
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)

        return zax, axes
Exemplo n.º 16
0
    def initArea(self):
        '''
        Sets up the VTK simulation area
        :return:None
        '''
        # Zoom items
        self.zitems = []

        self.actors_dict = {}
        
        self.cellTypeActors={}
        self.outlineActor = vtk.vtkActor()
        self.outlineDim=[0,0,0]
        
        self.invisibleCellTypes={}
        self.typesInvisibleStr=""
        self.set3DInvisibleTypes()
        
        self.axesActor = vtk.vtkCubeAxesActor2D()

        self.clut = vtk.vtkLookupTable()
        self.clut.SetHueRange(0.67, 0.0)
        self.clut.SetSaturationRange(1.0,1.0)
        self.clut.SetValueRange(1.0,1.0)
        self.clut.SetAlphaRange(1.0,1.0)
        self.clut.SetNumberOfColors(1024)
        self.clut.Build()

        ## Set up the mapper and actor (3D) for concentration field.
        # self.conMapper = vtk.vtkPolyDataMapper()
        self.conActor = vtk.vtkActor()

        self.glyphsActor=vtk.vtkActor()
        # self.glyphsMapper=vtk.vtkPolyDataMapper()
        
        self.cellGlyphsActor  = vtk.vtkActor()
        self.FPPLinksActor  = vtk.vtkActor()

        # Weird attributes
        self.typeActors             = {} # vtkActor
        # self.smootherFilters        = {} # vtkSmoothPolyDataFilter
        # self.polyDataNormals        = {} # vtkPolyDataNormals
        # self.typeExtractors         = {} # vtkDiscreteMarchingCubes
        # self.typeExtractorMappers   = {} # vtkPolyDataMapper

        self.actors_dict['cellsActor'] = {}
    def initArea(self):
        '''
        Sets up the VTK simulation area
        :return:None
        '''
        # Zoom items
        self.zitems = []

        self.actors_dict = {}

        self.cellTypeActors = {}
        self.outlineActor = vtk.vtkActor()
        self.outlineDim = [0, 0, 0]

        self.invisibleCellTypes = {}
        self.typesInvisibleStr = ""
        self.set3DInvisibleTypes()

        self.axesActor = vtk.vtkCubeAxesActor2D()

        self.clut = vtk.vtkLookupTable()
        self.clut.SetHueRange(0.67, 0.0)
        self.clut.SetSaturationRange(1.0, 1.0)
        self.clut.SetValueRange(1.0, 1.0)
        self.clut.SetAlphaRange(1.0, 1.0)
        self.clut.SetNumberOfColors(1024)
        self.clut.Build()

        ## Set up the mapper and actor (3D) for concentration field.
        # self.conMapper = vtk.vtkPolyDataMapper()
        self.conActor = vtk.vtkActor()

        self.glyphsActor = vtk.vtkActor()
        # self.glyphsMapper=vtk.vtkPolyDataMapper()

        self.cellGlyphsActor = vtk.vtkActor()
        self.FPPLinksActor = vtk.vtkActor()

        # Weird attributes
        self.typeActors = {}  # vtkActor
        # self.smootherFilters        = {} # vtkSmoothPolyDataFilter
        # self.polyDataNormals        = {} # vtkPolyDataNormals
        # self.typeExtractors         = {} # vtkDiscreteMarchingCubes
        # self.typeExtractorMappers   = {} # vtkPolyDataMapper

        self.actors_dict['cellsActor'] = {}
Exemplo n.º 18
0
    def addT2visualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [self.transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        self.T2origin = list(self.transformed_T2image.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(self.transformed_T2image.GetExtent())
        print self.T2extent        
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0, 1, 1)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInputData(self.transformed_T2image)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return
Exemplo n.º 19
0
    def addT2visualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        self.T2origin = list(transformed_T2image.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(transformed_T2image.GetExtent())
        print self.T2extent        
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( transformed_T2image )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( transformed_T2image )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( transformed_T2image )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0, 1, 1)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInput(transformed_T2image)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return
    def __init__(self, data_reader, renderer):
        # Create a text property for cube axes
        self.tprop = vtk.vtkTextProperty()
        self.tprop.SetColor(1, 1, 1)
        self.tprop.ShadowOn()

        # Create a vtkCubeAxesActor2D.  Use the closest vertex to the camera to
        # determine where to draw the axes.  Add the actor to the renderer.
        self.actor = vtk.vtkCubeAxesActor2D()
        self.actor.SetInput(data_reader.get_data_set())
        self.actor.SetCamera(renderer.GetActiveCamera())
        self.actor.SetLabelFormat("%6.4g")
        self.actor.SetFlyModeToClosestTriad()
        self.actor.SetFontFactor(0.8)
        self.actor.GetProperty().SetColor(0, 0, 0)
        self.actor.ScalingOff()
        self.actor.SetAxisTitleTextProperty(self.tprop)
        self.actor.SetAxisLabelTextProperty(self.tprop)
Exemplo n.º 21
0
    def _create_axes(self):
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetBounds(
            numpy.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0]) *
            self.settings.scaling)
        axes.SetRanges(0.0, self._world_size, 0.0, self._world_size, 0.0,
                       self._world_size)
        axes.SetLabelFormat('%g')
        axes.SetFontFactor(1.5)
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(self.settings.axis_annotation_color)
        tprop.ShadowOn()
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        axes.UseRangesOn()
        axes.SetCornerOffset(0.0)

        return axes
    def __init__(self,data_reader,renderer):
		# Create a text property for cube axes
		self.tprop=vtk.vtkTextProperty()
		self.tprop.SetColor(1,1,1)
		self.tprop.ShadowOn()
		
		# Create a vtkCubeAxesActor2D.  Use the closest vertex to the camera to
        # determine where to draw the axes.  Add the actor to the renderer.
		self.actor=vtk.vtkCubeAxesActor2D()
		self.actor.SetInput(data_reader.get_data_set())
		self.actor.SetCamera(renderer.GetActiveCamera())
		self.actor.SetLabelFormat("%6.4g")
		self.actor.SetFlyModeToClosestTriad()
		self.actor.SetFontFactor(0.8)
		self.actor.GetProperty().SetColor(0,0,0)
		self.actor.ScalingOff()
		self.actor.SetAxisTitleTextProperty(self.tprop)
		self.actor.SetAxisLabelTextProperty(self.tprop)
Exemplo n.º 23
0
def view3Planes(image, title = 'Image and 3 Planes'):
    """
    display and image and 3 planes
    """
    
    xMin, xMax, yMin, yMax, zMin, zMax = image.GetWholeExtent()
    
    ren= vtk.vtkRenderer()
    ren.SetBackground(0.2,0.3,0.6)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(ren)
    renwin.SetSize( 700, 700 )
    renwin.SetWindowName(title)
    
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)
    wX,wY,wZ = create3Planes(image)

    wX.SetInteractor(iren); wX.On()
    wY.SetInteractor(iren); wY.On()
    wZ.SetInteractor(iren); wZ.On()

    outline = createOutlineActor(image)
    ren.AddActor(outline)
    
    axes = vtk.vtkCubeAxesActor2D()
    axes.SetCamera(ren.GetActiveCamera())
    axes.SetViewProp(outline)
    ren.AddActor(axes)

    ren.ResetCamera()
    cam1 = ren.GetActiveCamera()
    cam1.Elevation(-70)
    cam1.SetViewUp(0, 0, 1)
    cam1.Azimuth(30)
    ren.ResetCameraClippingRange()
        
    iren.Initialize()
    renwin.Render()
    iren.Start() 
Exemplo n.º 24
0
 def simple_axis(self, ren):
     """Show axes."""
     if self.mesh is not None:
         tprop = vtk.vtkTextProperty()
         tprop.SetColor(0, 0, 0)
         tprop.ShadowOff()
         outline = vtk.vtkOutlineFilter()
         outline.SetInput(self.vtkgrid[self.dim])
         normals = vtk.vtkPolyDataNormals()
         normals.SetInputConnection(outline.GetOutputPort())
         self.axes = vtk.vtkCubeAxesActor2D()
         self.axes.SetInput(normals.GetOutput())
         self.axes.SetCamera(ren.GetActiveCamera())
         self.axes.GetProperty().SetColor(0, 0, 0)
         self.axes.SetAxisTitleTextProperty(tprop)
         self.axes.SetAxisLabelTextProperty(tprop)
         self.axes.SetCornerOffset(0)
         if self.dim == 2:
             self.axes.ZAxisVisibilityOff()
         ren.AddViewProp(self.axes)
Exemplo n.º 25
0
def create_axes(bounds, **params):
    # bounds = (minpos[0], maxpos[0], minpos[1],
    #           maxpos[1], minpos[2], maxpos[2])
    ranges = bounds

    axes = vtk.vtkCubeAxesActor2D()
    axes.SetBounds(bounds)
    axes.SetRanges(ranges)
    axes.SetLabelFormat('%g')
    # axes.SetFontFactor(1.5)
    axes.UseRangesOn()
    # axes.SetCornerOffset(0.0)

    tprop = vtk.vtkTextProperty()
    if 'color' in params.keys():
        tprop.SetColor(params['color'])
    # tprop.ShadowOn()
    axes.SetAxisTitleTextProperty(tprop)
    axes.SetAxisLabelTextProperty(tprop)

    return axes
Exemplo n.º 26
0
    def _create_axes(self):
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetBounds(
                [0.0, self._scalings[0],
                 0.0, self._scalings[1], 
                 0.0, self._scalings[2]])
        axes.SetRanges(
                 0.0, self._world_sizes[0],
                 0.0, self._world_sizes[1],
                 0.0, self._world_sizes[2])
        axes.SetLabelFormat('%g')
        axes.SetFontFactor(1.5)
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(self.settings.axis_annotation_color)
        tprop.ShadowOn()
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        axes.UseRangesOn()
        axes.SetCornerOffset(0.0)

        return axes
Exemplo n.º 27
0
def main ():
    # example code...
    import vtk
    from vtk.wx.wxVTKRenderWindow import wxVTKRenderWindow
    
    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    transform = vtk.vtkTransformFilter ()
    transform.SetInput ( cone.GetOutput() )
    transform.SetTransform ( vtk.vtkTransform() )
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(transform.GetOutput())
    l = vtk.vtkLookupTable ()
    coneMapper.SetLookupTable (l)
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)    
    axes = vtk.vtkCubeAxesActor2D ()

    app = wx.PySimpleApp()
    frame = wx.Frame(None, -1, "wx.RenderWindow", size=wx.Size(400,400))
    wid = wxVTKRenderWindow(frame, -1)

    ren = vtk.vtkRenderer()
    renWin = wid.GetRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(300,300)
    ren.AddActor (coneActor)
    ren.AddActor (axes)
    axes.SetCamera (ren.GetActiveCamera ())
    renWin.Render ()

    debug ("Starting VTK Pipeline Browser...")
    pipe = vtkPipelineBrowser (frame, renWin)
    pipe.show()

    pipe_segment = vtkPipelineBrowser(frame, renWin, (coneActor, axes))
    pipe_segment.show()

    app.MainLoop()
Exemplo n.º 28
0
def main():
    # example code...
    import vtk
    from vtk.wx.wxVTKRenderWindow import wxVTKRenderWindow

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    transform = vtk.vtkTransformFilter()
    transform.SetInput(cone.GetOutput())
    transform.SetTransform(vtk.vtkTransform())
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(transform.GetOutput())
    l = vtk.vtkLookupTable()
    coneMapper.SetLookupTable(l)
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    axes = vtk.vtkCubeAxesActor2D()

    app = wx.PySimpleApp()
    frame = wx.Frame(None, -1, "wx.RenderWindow", size=wx.Size(400, 400))
    wid = wxVTKRenderWindow(frame, -1)

    ren = vtk.vtkRenderer()
    renWin = wid.GetRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(300, 300)
    ren.AddActor(coneActor)
    ren.AddActor(axes)
    axes.SetCamera(ren.GetActiveCamera())
    renWin.Render()

    debug("Starting VTK Pipeline Browser...")
    pipe = vtkPipelineBrowser(frame, renWin)
    pipe.show()

    pipe_segment = vtkPipelineBrowser(frame, renWin, (coneActor, axes))
    pipe_segment.show()

    app.MainLoop()
Exemplo n.º 29
0
    def show_axes(self):
        """Shows the axes around the main object"""

        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0., 0., 0.)
        tprop.ShadowOn()

        axes = vtk.vtkCubeAxesActor2D()
        if vtk.VTK_MAJOR_VERSION <= 5:
            axes.SetInput(self.polydatas[0])
        else:
            axes.SetInputData(self.polydatas[0])

        axes.SetCamera(self.renderer.GetActiveCamera())
        axes.SetLabelFormat("%6.4g")
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(0.8)
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        # axes.DrawGridLinesOn()

        self.renderer.AddViewProp(axes)
        self.axes.append(axes)
Exemplo n.º 30
0
    def _createIPW(self):
        # we have to do this to get the correct log range
        self._histogram.GetOutput().Update()

        # this means we have newly valid input and should setup an ipw
        self._ipw = vtk.vtkImagePlaneWidget()
        self._histogram.GetOutput().Update()
        self._ipw.SetInput(self._histogram.GetOutput())
        self._ipw.SetInteractor(self._viewFrame.rwi)
        # normal to the Z-axis
        self._ipw.SetPlaneOrientation(2)
        self._ipw.SetSliceIndex(0)

        # setup specific lut
        srange = self._histogram.GetOutput().GetScalarRange()
        lut = vtk.vtkLookupTable()
        lut.SetScaleToLog10()
        lut.SetTableRange(srange)
        lut.SetSaturationRange(1.0, 1.0)
        lut.SetValueRange(1.0, 1.0)
        lut.SetHueRange(0.1, 1.0)
        lut.Build()
        self._ipw.SetUserControlledLookupTable(1)
        self._ipw.SetLookupTable(lut)

        self._ipw.SetDisplayText(1)
        # if we use ContinousCursor, we get OffImage when zoomed
        # on Linux (really irritating) but not on Windows.  A VTK
        # recompile might help, we'll see.
        self._ipw.SetUseContinuousCursor(1)
        # make sure the user can't twist the plane out of sight
        self._ipw.SetMiddleButtonAction(0)
        self._ipw.SetRightButtonAction(0)

        # add an observer
        self._ipw.AddObserver("StartInteractionEvent", self._observerIPWInteraction)
        self._ipw.AddObserver("InteractionEvent", self._observerIPWInteraction)
        self._ipw.AddObserver("EndInteractionEvent", self._observerIPWInteraction)

        self._ipw.On()

        self._axes = vtk.vtkCubeAxesActor2D()
        self._axes.SetFlyModeToOuterEdges()
        # NOBODY will ever know why we have to switch off the Y axis when
        # we actually want the Z-axis to go away.
        self._axes.YAxisVisibilityOff()
        self._axes.SetBounds(self._ipw.GetResliceOutput().GetBounds())

        self._renderer.AddActor(self._axes)
        self._axes.SetCamera(self._renderer.GetActiveCamera())
        self._axes.PickableOff()

        if 0:
            # now add a scalarbar
            self._scalarBarWidget = vtk.vtkScalarBarWidget()
            self._scalarBarWidget.SetInteractor(self._viewFrame.rwi)
            self._scalarBarWidget.GetScalarBarActor().SetTitle("Frequency")
            self._scalarBarWidget.GetScalarBarActor().SetLookupTable(lut)
            # and activate
            self._scalarBarWidget.On()

        self._resetCamera()
        self._render()
Exemplo n.º 31
0
    def simpleVisualize(self, volume, interact):
        """ simpleVisualize will load a 3D ortoghonal planes visualization of a volume"""

        # get info from image before visualization
        volume.UpdateInformation()
        self.dims = volume.GetDimensions()
        print "Image Dimensions"
        print self.dims
        (xMin, xMax, yMin, yMax, zMin, zMax) = volume.GetWholeExtent()
        print "Image Extension"
        print xMin, xMax, yMin, yMax, zMin, zMax
        self.spacing = volume.GetSpacing()
        print "Image Spacing"
        print self.spacing
        self.origin = volume.GetOrigin()
        print "Image Origin"
        print self.origin

        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput(volume)
        self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput(volume)
        self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput(volume)
        self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
        self.zImagePlaneWidget.SetSliceIndex(0)

        self.xImagePlaneWidget.On()
        self.yImagePlaneWidget.On()
        self.zImagePlaneWidget.On()

        # Set UP the axes
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1, 1, 1)
        tprop.ShadowOff()
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetInput(volume)
        axes.SetCamera(self.renderer1.GetActiveCamera())
        axes.SetLabelFormat("%6.4g")
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(1.2)
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        self.renderer1.AddViewProp(axes)

        ############
        # bounds and initialize camera
        bounds = volume.GetBounds()
        self.renderer1.ResetCamera(bounds)
        self.renderer1.ResetCameraClippingRange()
        self.camera.SetViewUp(0.0, -1.0, 0.0)
        self.camera.Azimuth(315)

        # Initizalize
        self.renWin1.Render()
        self.renderer1.Render()

        if (interact == True):
            self.iren1.Initialize()
            self.iren1.Start()

        return
Exemplo n.º 32
0
def display(image, image_pos_pat, image_ori_pat):
	global xMin, xMax, yMin, yMax, zMin, zMax, xSpacing, ySpacing, zSpacing, interactor, actions, reslice, interactorStyle
	# The box widget observes the events invoked by the render window
	# interactor.  These events come from user interaction in the render
	# window.
	# boxWidget = vtk.vtkBoxWidget()
	# boxWidget.SetInteractor(iren1)
	# boxWidget.SetPlaceFactor(1)
	
	# Initialize Image orienation
	IO = matrix(	[[0, 0,-1, 0],
			[1, 0, 0, 0],
			[0,-1, 0, 0],
			[0, 0, 0, 1]])
	# Assign the 6-Image orientation patient coordinates (from Dicomtags)
	IO[0,0] = image_ori_pat[0]; IO[1,0] = image_ori_pat[1]; IO[2,0] = image_ori_pat[2]; 
	IO[0,1] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[2,1] = image_ori_pat[5]; 
	
	# obtain thrid column as the cross product of column 1 y 2
	IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]]
	IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]]
	IO_col3 = cross(IO_col1, IO_col2)
	
	# assign column 3	
	IO[0,2] = IO_col3[0]; IO[1,2] = IO_col3[1]; IO[2,2] = IO_col3[2]; 
	
	IP =  array([0, 0, 0, 1]) # Initialization Image Position
	IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2];  
	IO[0,3] = image_pos_pat[0]; IO[1,3] = image_pos_pat[1]; IO[2,3] = image_pos_pat[2]
	
	print "image_pos_pat :"
	print image_pos_pat
	print "image_ori_pat:"
	print image_ori_pat
	
	origin = IP*IO.I
	print "Volume Origin:"
	print origin[0,0], origin[0,1], origin[0,2]
	
	# Create matrix 4x4
	DICOM_mat = vtk.vtkMatrix4x4();
	DICOM_mat.SetElement(0, 0, IO[0,0])
	DICOM_mat.SetElement(0, 1, IO[0,1])
	DICOM_mat.SetElement(0, 2, IO[0,2])
	DICOM_mat.SetElement(0, 3, IO[0,3])
	
	DICOM_mat.SetElement(1, 0, IO[1,0])
	DICOM_mat.SetElement(1, 1, IO[1,1])
	DICOM_mat.SetElement(1, 2, IO[1,2])
	DICOM_mat.SetElement(1, 3, IO[1,3])
	
	DICOM_mat.SetElement(2, 0, IO[2,0])
	DICOM_mat.SetElement(2, 1, IO[2,1])
	DICOM_mat.SetElement(2, 2, IO[2,2])
	DICOM_mat.SetElement(2, 3, IO[2,3])
	
	DICOM_mat.SetElement(3, 0, IO[3,0])
	DICOM_mat.SetElement(3, 1, IO[3,1])
	DICOM_mat.SetElement(3, 2, IO[3,2])
	DICOM_mat.SetElement(3, 3, IO[3,3])
	#DICOM_mat.Invert()
	
	# Set up the axes	
	transform = vtk.vtkTransform()
	transform.Concatenate(DICOM_mat)
	transform.Update()
	
	# Set up the cube (set up the translation back to zero	
	DICOM_mat_cube = vtk.vtkMatrix4x4();
	DICOM_mat_cube.DeepCopy(DICOM_mat)
	DICOM_mat_cube.SetElement(0, 3, 0)
	DICOM_mat_cube.SetElement(1, 3, 0)
	DICOM_mat_cube.SetElement(2, 3, 0)
		
	transform_cube = vtk.vtkTransform()
	transform_cube.Concatenate(DICOM_mat_cube)
	transform_cube.Update()
	
	##########################
	# Calculate the center of the volume
	(xMin, xMax, yMin, yMax, zMin, zMax) = image.GetWholeExtent()
	(xSpacing, ySpacing, zSpacing) = image.GetSpacing()
	(x0, y0, z0) = image.GetOrigin()
	
	center = [x0 + xSpacing * 0.5 * (xMin + xMax),
		  y0 + ySpacing * 0.5 * (yMin + yMax),
		  z0 + zSpacing * 0.5 * (zMin + zMax)]
	
	# Matrices for axial, coronal, sagittal, oblique view orientations
	axial = vtk.vtkMatrix4x4()
	axial.DeepCopy((1, 0, 0, center[0],
			0, 1, 0, center[1],
			0, 0, 1, center[2],
			0, 0, 0, 1))
	
	coronal = vtk.vtkMatrix4x4()
	coronal.DeepCopy((1, 0, 0, center[0],
			  0, 0, 1, center[1],
			  0,-1, 0, center[2],
			  0, 0, 0, 1))
	
	sagittal = vtk.vtkMatrix4x4()
	sagittal.DeepCopy((0, 0,-1, center[0],
			   1, 0, 0, center[1],
			   0,-1, 0, center[2],
			   0, 0, 0, 1))
	
	oblique = vtk.vtkMatrix4x4()
	oblique.DeepCopy((1, 0, 0, center[0],
			  0, 0.866025, -0.5, center[1],
			  0, 0.5, 0.866025, center[2],
			  0, 0, 0, 1))
	
	# Extract a slice in the desired orientation
	reslice = vtk.vtkImageReslice()
	reslice.SetInput(image)
	reslice.SetOutputDimensionality(2)
	reslice.SetResliceAxes(sagittal)
	reslice.SetInterpolationModeToLinear()
	
	# Create a greyscale lookup table
	table = vtk.vtkLookupTable()
	table.SetRange(0, 2000) # image intensity range
	table.SetValueRange(0.0, 1.0) # from black to white
	table.SetSaturationRange(0.0, 0.0) # no color saturation
	table.SetRampToLinear()
	table.Build()
	
	# Map the image through the lookup table
	color = vtk.vtkImageMapToColors()
	color.SetLookupTable(table)
	color.SetInputConnection(reslice.GetOutputPort())

	# Display the image
	actor = vtk.vtkImageActor()
	actor.GetMapper().SetInputConnection(color.GetOutputPort())

	renderer1 = vtk.vtkRenderer()
	renderer1.AddActor(actor)
	################
	    
	
	# set up cube actor with Orientation(R-L, A-P, S-O) using transform_cube
	# Set up to ALS (+X=A, +Y=S, +Z=L) source:
	cube = vtk.vtkAnnotatedCubeActor()
	cube.SetXPlusFaceText( "S" );
	cube.SetXMinusFaceText( "I" );
	cube.SetYPlusFaceText( "L" );
	cube.SetYMinusFaceText( "R" );
	cube.SetZPlusFaceText( "A" );
	cube.SetZMinusFaceText( "P" );
	cube.SetFaceTextScale( 0.5 );
	cube.GetAssembly().SetUserTransform( transform_cube );
		
	# Set UP the axes
	axes2 = vtk.vtkAxesActor()
	axes2.SetShaftTypeToCylinder();
	#axes2.SetUserTransform( transform_cube );		 
	axes2.SetTotalLength( 1.5, 1.5, 1.5 );
	axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() );
	axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() );
	axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() );

	tprop2 = axes2.GetXAxisCaptionActor2D()
	tprop2.GetCaptionTextProperty();

	assembly = vtk.vtkPropAssembly();
	assembly.AddPart( axes2 );
	assembly.AddPart( cube );
	
	widget = vtk.vtkOrientationMarkerWidget();
	widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 );
	widget.SetOrientationMarker( assembly );
	widget.SetInteractor( iren1 );
	widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
	widget.SetEnabled( 1 );
	widget.InteractiveOff();
			
	# Set Up Camera view
	renderer1.SetBackground(0.0, 0.0, 0.0)
	camera = renderer1.GetActiveCamera()

	# bounds and initialize camera
	b = image.GetBounds()
	renderer1.ResetCamera(b)	
	renderer1.ResetCameraClippingRange()
	camera.SetViewUp(0.0,-1.0,0.0)
	camera.Azimuth(315)
	
	# Create a text property for both cube axes
	tprop = vtk.vtkTextProperty()
	tprop.SetColor(1, 1, 1)
	tprop.ShadowOff()
	
	# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
	# draw the axes.  Add the actor to the renderer.
	axes = vtk.vtkCubeAxesActor2D()
	axes.SetInput(image)
	axes.SetCamera(renderer1.GetActiveCamera())
	axes.SetLabelFormat("%6.4g")
	axes.SetFlyModeToOuterEdges()
	axes.SetFontFactor(1.2)
	axes.SetAxisTitleTextProperty(tprop)
	axes.SetAxisLabelTextProperty(tprop)      
	renderer1.AddViewProp(axes)
	
	############
	# Place the interactor initially. The input to a 3D widget is used to
	# initially position and scale the widget. The "EndInteractionEvent" is
  	# observed which invokes the SelectPolygons callback.
    	# boxWidget.SetInput(image)
	# boxWidget.PlaceWidget()
	# boxWidget.AddObserver("InteractionEvent", SelectPolygons)
	# boxWidget.On()
	# Initizalize
	# Set up the interaction
	interactorStyle = vtk.vtkInteractorStyleImage()
	interactor = vtk.vtkRenderWindowInteractor()
	interactor.SetInteractorStyle(interactorStyle)
	renWin1.SetInteractor(interactor)
	renWin1.Render()
	
	renderer1.Render()
	interactor.Start()
	renderer1.RemoveViewProp(axes)
						
	return transform_cube, zImagePlaneWidget.GetSliceIndex()
Exemplo n.º 33
0
 def visualize(self, images, image_pos_pat, image_ori_pat, sub, postS, interact):
     '''Display and render volumes, reference frames, actors and widgets'''
     if(sub):
         #subtract volumes based on indicated postS            
         # define image based on subtraction of postS -preS
         image = self.subImage(images, postS)
     else:
         image = images[postS]            
          
     # Proceed to build reference frame for display objects based on DICOM coords   
     [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat)
     
     # get info from image before visualization
     self.transformed_image.UpdateInformation()
     self.dims = self.transformed_image.GetDimensions()
     print "Image Dimensions"
     print self.dims
     self.T1spacing = self.transformed_image.GetSpacing()
     print "Image Spacing"
     print self.T1spacing
     self.T1origin = self.transformed_image.GetOrigin()
     print "Image Origin"
     print self.T1origin
     self.T1extent = list(self.transformed_image.GetWholeExtent())
     print "Image Extent"
     print self.T1extent
         
     # Set up ortogonal planes
     self.xImagePlaneWidget.SetInput( self.transformed_image )
     self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
     self.xImagePlaneWidget.SetSliceIndex(0)
     self.yImagePlaneWidget.SetInput( self.transformed_image )
     self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
     self.yImagePlaneWidget.SetSliceIndex(0)
     self.zImagePlaneWidget.SetInput( self.transformed_image )
     self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
     self.zImagePlaneWidget.SetSliceIndex(0)
         
     self.xImagePlaneWidget.On()
     self.yImagePlaneWidget.On()
     self.zImagePlaneWidget.On()
     
     # set up cube actor with Orientation(A-P, S-I, L-R) using transform_cube
     # Set up to ALS (+X=A, +Y=S, +Z=L) source:
     cube = vtk.vtkAnnotatedCubeActor()
     cube.SetXPlusFaceText( "L" );
     cube.SetXMinusFaceText( "R" );
     cube.SetYPlusFaceText( "A" );
     cube.SetYMinusFaceText( "P" );
     cube.SetZPlusFaceText( "S" );
     cube.SetZMinusFaceText( "I" );
     cube.SetFaceTextScale( 0.5 );
     cube.GetAssembly().SetUserTransform( transform_cube );
         
     # Set UP the axes
     axes2 = vtk.vtkAxesActor()
     axes2.SetShaftTypeToCylinder();
     #axes2.SetUserTransform( transform_cube );         
     axes2.SetTotalLength( 1.5, 1.5, 1.5 );
     axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() );
     axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() );
     axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() );
 
     tprop2 = axes2.GetXAxisCaptionActor2D()
     tprop2.GetCaptionTextProperty();
 
     assembly = vtk.vtkPropAssembly();
     assembly.AddPart( axes2 );
     assembly.AddPart( cube );
     
     widget = vtk.vtkOrientationMarkerWidget();
     widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 );
     widget.SetOrientationMarker( assembly );
     widget.SetInteractor( self.iren1 );
     widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
     widget.SetEnabled( 1 );
     widget.InteractiveOff();
                 
     # Create a text property for both cube axes
     tprop = vtk.vtkTextProperty()
     tprop.SetColor(1, 1, 1)
     tprop.ShadowOff()
     
     # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
     # draw the axes.  Add the actor to the renderer.
     axes = vtk.vtkCubeAxesActor2D()
     axes.SetInput(self.transformed_image)
     axes.SetCamera(self.renderer1.GetActiveCamera())
     axes.SetLabelFormat("%6.4g")
     axes.SetFlyModeToOuterEdges()
     axes.SetFontFactor(1.2)
     axes.SetAxisTitleTextProperty(tprop)
     axes.SetAxisLabelTextProperty(tprop)      
     self.renderer1.AddViewProp(axes)
     
     ############
     # bounds and initialize camera
     bounds = self.transformed_image.GetBounds()
     self.renderer1.ResetCamera(bounds)    
     self.renderer1.ResetCameraClippingRange()
     self.camera.SetViewUp(0.0,-1.0,0.0)
     self.camera.Azimuth(315)
     
     # Initizalize
     self.renWin1.Modified()
     self.renWin1.Render()
     self.renderer1.Render()
     
     if(interact==True):
         interactor = self.renWin1.GetInteractor()
         interactor.Start()
                         
     return
Exemplo n.º 34
0
    def __init__(self, module_manager):
        # call base constructor
        ModuleBase.__init__(self, module_manager)
        ColourDialogMixin.__init__(
            self, module_manager.get_module_view_parent_window())
        self._numDataInputs = self.NUM_INPUTS
        # use list comprehension to create list keeping track of inputs
        self._inputs = [{'Connected' : None, 'inputData' : None,
                         'vtkActor' : None, 'ipw' : None}
                       for i in range(self._numDataInputs)]
        # then the window containing the renderwindows
        self.threedFrame = None

        # the renderers corresponding to the render windows
        self._threedRenderer = None

        self._outline_source = vtk.vtkOutlineSource()
        om = vtk.vtkPolyDataMapper()
        om.SetInputConnection(self._outline_source.GetOutputPort())
        self._outline_actor = vtk.vtkActor()
        self._outline_actor.SetMapper(om)
        self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D()
        self._cube_axes_actor2d.SetFlyModeToOuterEdges()
        #self._cube_axes_actor2d.SetFlyModeToClosestTriad()


        # use box widget for VOI selection
        self._voi_widget = vtk.vtkBoxWidget()
        # we want to keep it aligned with the cubic volume, thanks
        self._voi_widget.SetRotationEnabled(0)
        self._voi_widget.AddObserver('InteractionEvent',
                                     self.voiWidgetInteractionCallback)
        self._voi_widget.AddObserver('EndInteractionEvent',
                                     self.voiWidgetEndInteractionCallback)
        self._voi_widget.NeedsPlacement = True

        # also create the VTK construct for actually extracting VOI from data
        #self._extractVOI = vtk.vtkExtractVOI()
        self._currentVOI = 6 * [0]

        # set the whole UI up!
        self._create_window()

        # our interactor styles (we could add joystick or something too)
        self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera()


        # set the default
        self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle)
        
        rwi = self.threedFrame.threedRWI
        rwi.Unbind(wx.EVT_MOUSEWHEEL)
        rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)        

        # initialise our sliceDirections, this will also setup the grid and
        # bind all slice UI events
        self.sliceDirections = sliceDirections(
            self, self.controlFrame.sliceGrid)

        self.selectedPoints = selectedPoints(
            self, self.controlFrame.pointsGrid)

        # we now have a wx.ListCtrl, let's abuse it
        self._tdObjects = tdObjects(self,
                                    self.controlFrame.objectsListGrid)

        self._implicits = implicits(self,
                                    self.controlFrame.implicitsGrid)


        # setup orientation widget stuff
        # NB NB NB: we switch interaction with this off later
        # (InteractiveOff()), thus disabling direct translation and
        # scaling.  If we DON'T do this, interaction with software 
        # raycasters are greatly slowed down.
        self._orientation_widget = vtk.vtkOrientationMarkerWidget()
        
        self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
        #aca.TextEdgesOff()

        aca.GetXMinusFaceProperty().SetColor(1,0,0)
        aca.GetXPlusFaceProperty().SetColor(1,0,0)
        aca.GetYMinusFaceProperty().SetColor(0,1,0)
        aca.GetYPlusFaceProperty().SetColor(0,1,0)
        aca.GetZMinusFaceProperty().SetColor(0,0,1)
        aca.GetZPlusFaceProperty().SetColor(0,0,1)
        
        self._axes_actor = vtk.vtkAxesActor()

        self._orientation_widget.SetInteractor(
            self.threedFrame.threedRWI)
        self._orientation_widget.SetOrientationMarker(
            self._axes_actor)
        self._orientation_widget.On()
       
        # make sure interaction is off; when on, interaction with
        # software raycasters is greatly slowed down!
        self._orientation_widget.InteractiveOff()
Exemplo n.º 35
0
    def __init__(self, module_manager):
        # call base constructor
        ModuleBase.__init__(self, module_manager)
        ColourDialogMixin.__init__(
            self, module_manager.get_module_view_parent_window())
        self._numDataInputs = self.NUM_INPUTS
        # use list comprehension to create list keeping track of inputs
        self._inputs = [{
            'Connected': None,
            'inputData': None,
            'vtkActor': None,
            'ipw': None
        } for i in range(self._numDataInputs)]
        # then the window containing the renderwindows
        self.threedFrame = None

        # the renderers corresponding to the render windows
        self._threedRenderer = None

        self._outline_source = vtk.vtkOutlineSource()
        om = vtk.vtkPolyDataMapper()
        om.SetInputConnection(self._outline_source.GetOutputPort())
        self._outline_actor = vtk.vtkActor()
        self._outline_actor.SetMapper(om)
        self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D()
        self._cube_axes_actor2d.SetFlyModeToOuterEdges()
        #self._cube_axes_actor2d.SetFlyModeToClosestTriad()

        # use box widget for VOI selection
        self._voi_widget = vtk.vtkBoxWidget()
        # we want to keep it aligned with the cubic volume, thanks
        self._voi_widget.SetRotationEnabled(0)
        self._voi_widget.AddObserver('InteractionEvent',
                                     self.voiWidgetInteractionCallback)
        self._voi_widget.AddObserver('EndInteractionEvent',
                                     self.voiWidgetEndInteractionCallback)
        self._voi_widget.NeedsPlacement = True

        # also create the VTK construct for actually extracting VOI from data
        #self._extractVOI = vtk.vtkExtractVOI()
        self._currentVOI = 6 * [0]

        # set the whole UI up!
        self._create_window()

        # our interactor styles (we could add joystick or something too)
        self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera()

        # set the default
        self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle)

        rwi = self.threedFrame.threedRWI
        rwi.Unbind(wx.EVT_MOUSEWHEEL)
        rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)

        # initialise our sliceDirections, this will also setup the grid and
        # bind all slice UI events
        self.sliceDirections = sliceDirections(self,
                                               self.controlFrame.sliceGrid)

        self.selectedPoints = selectedPoints(self,
                                             self.controlFrame.pointsGrid)

        # we now have a wx.ListCtrl, let's abuse it
        self._tdObjects = tdObjects(self, self.controlFrame.objectsListGrid)

        self._implicits = implicits(self, self.controlFrame.implicitsGrid)

        # setup orientation widget stuff
        # NB NB NB: we switch interaction with this off later
        # (InteractiveOff()), thus disabling direct translation and
        # scaling.  If we DON'T do this, interaction with software
        # raycasters are greatly slowed down.
        self._orientation_widget = vtk.vtkOrientationMarkerWidget()

        self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
        #aca.TextEdgesOff()

        aca.GetXMinusFaceProperty().SetColor(1, 0, 0)
        aca.GetXPlusFaceProperty().SetColor(1, 0, 0)
        aca.GetYMinusFaceProperty().SetColor(0, 1, 0)
        aca.GetYPlusFaceProperty().SetColor(0, 1, 0)
        aca.GetZMinusFaceProperty().SetColor(0, 0, 1)
        aca.GetZPlusFaceProperty().SetColor(0, 0, 1)

        self._axes_actor = vtk.vtkAxesActor()

        self._orientation_widget.SetInteractor(self.threedFrame.threedRWI)
        self._orientation_widget.SetOrientationMarker(self._axes_actor)
        self._orientation_widget.On()

        # make sure interaction is off; when on, interaction with
        # software raycasters is greatly slowed down!
        self._orientation_widget.InteractiveOff()
Exemplo n.º 36
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        self.T2origin = list(transformed_T2image.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(transformed_T2image.GetExtent())
        print self.T2extent        
        
        alignR = int(raw_input('\nAlign right? Yes:1 or align with T1w: !=1 : '))
        if alignR:
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
                
        # Change info origin
        transformedInfo_T2image = vtk.vtkImageChangeInformation()
        transformedInfo_T2image.SetInputData( transformed_T2image )
        transformedInfo_T2image.SetOutputOrigin(self.T2origin)
        transformedInfo_T2image.Update()
        
        self.transformed_T2image = transformedInfo_T2image.GetOutput()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInputData(self.transformed_T2image)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInputData( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
Exemplo n.º 37
0
class TestGL2PSExporter(Testing.vtkTest):
    # Create these as class attributes so that they are only created
    # once and not for every test.
    cs = vtk.vtkConeSource()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(cs.GetOutputPort())

    act = vtk.vtkActor()
    act.SetMapper(mapper)
    act.GetProperty().SetColor(0.5, 0.5, 1.0)

    axes = vtk.vtkCubeAxesActor2D()
    axes.SetInput(cs.GetOutput())
    axes.SetFontFactor(2.0)
    axes.SetCornerOffset(0.0)
    axes.GetProperty().SetColor(0,0,0)

    txt = vtk.vtkTextActor()
    txt.SetDisplayPosition(45, 150)
    txt.SetInput("This is test\nmultiline\ninput\ndata.")
    tprop = txt.GetTextProperty()
    tprop.SetFontSize(18)
    tprop.SetFontFamilyToArial()
    tprop.SetJustificationToCentered()
    tprop.BoldOn()
    tprop.ItalicOn()
    tprop.ShadowOn()
    tprop.SetColor(0, 0, 1)

    ren = vtk.vtkRenderer()
    ren.AddActor(act)
    ren.AddActor(txt)
    axes.SetCamera(ren.GetActiveCamera())
    ren.AddActor(axes)
    ren.SetBackground(0.8, 0.8, 0.8)

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    cam = ren.GetActiveCamera()
    ren.ResetCamera()
    cam.Azimuth(30)

    iren.Initialize()
    iren.Render()

    def _cleanup(self, files):
        """Remove the list of given files."""
        for f in files:
            if os.path.isfile(f):
                os.remove(f)
        
    def testVectorEPS(self):
        """Test vector EPS output."""
        # Get a temporary file name.  Set the extension to empty since
        # the exporter appends a suitable extension.
        tmp_eps = tempfile.mktemp('')
        # Write an EPS file.
        exp = vtk.vtkGL2PSExporter()
        exp.SetRenderWindow(self.renWin)
        exp.SetFilePrefix(tmp_eps)
        # Turn off compression so PIL can read file.
        exp.CompressOff() 
        exp.SetSortToBSP()
        exp.DrawBackgroundOn()
        exp.Write()
        # Now read the EPS file using PIL.
        tmp_eps += '.eps'
        im = Image.open(tmp_eps)
        # Get a temporary name for the PNG file.
        tmp_png = tempfile.mktemp('.png')
        im.save(tmp_png)

        # Now read the saved image and compare it for the test.
        png_r = vtk.vtkPNGReader()
        png_r.SetFileName(tmp_png)
        png_r.Update()
        img = png_r.GetOutput()

        # Cleanup.  Do this first because if the test fails, an
        # exception is raised and the temporary files won't be
        # removed.
        self._cleanup([tmp_eps, tmp_png])
        
        img_file = "TestGL2PSExporter.png"
        Testing.compareImageWithSavedImage(img,
                                           Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        Testing.interact()

    def testRasterEPS(self):
        """Test EPS output when Write3DPropsAsRasterImage is on."""
        # Get a temporary file name.  Set the extension to empty since
        # the exporter appends a suitable extension.
        tmp_eps = tempfile.mktemp('')
        # Write an EPS file.
        exp = vtk.vtkGL2PSExporter()
        exp.SetRenderWindow(self.renWin)
        exp.SetFilePrefix(tmp_eps)
        # Turn off compression so PIL can read file.
        exp.CompressOff() 
        exp.SetSortToOff()
        exp.DrawBackgroundOn()
        exp.Write3DPropsAsRasterImageOn()
        exp.Write()
        # Now read the EPS file using PIL.
        tmp_eps += '.eps'
        im = Image.open(tmp_eps)
        # Get a temporary name for the PNG file.
        tmp_png = tempfile.mktemp('.png')
        im.save(tmp_png)

        # Now read the saved image and compare it for the test.
        png_r = vtk.vtkPNGReader()
        png_r.SetFileName(tmp_png)
        png_r.Update()
        img = png_r.GetOutput()

        # Cleanup.  Do this first because if the test fails, an
        # exception is raised and the temporary files won't be
        # removed.
        self._cleanup([tmp_eps, tmp_png])
        
        img_file = "TestGL2PSExporter.png"
        Testing.compareImageWithSavedImage(img,
                                           Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        Testing.interact()
Exemplo n.º 38
0
 def visualize(self, images, image_pos_pat, image_ori_pat, sub, postS, interact=True):
     '''Display and render volumes, reference frames, actors and widgets'''
     if(sub):
         #subtract volumes based on indicated postS            
         # define image based on subtraction of postS -preS
         image = self.subImage(images, postS)
     else:
         image = images[postS]            
          
     # Proceed to build reference frame for display objects based on DICOM coords   
     [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat)
     
     # get info from image before visualization
     self.dims = self.transformed_image.GetDimensions()
     print "Image Dimensions"
     print self.dims
     self.T1spacing = self.transformed_image.GetSpacing()
     print "Image Spacing"
     print self.T1spacing
     self.T1origin = self.transformed_image.GetOrigin()
     print "Image Origin"
     print self.T1origin
     self.T1extent = list(self.transformed_image.GetExtent())
     print "Image Extent"
     print self.T1extent
         
     # Set up ortogonal planes
     self.xImagePlaneWidget.SetInputData( self.transformed_image )
     self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
     self.xImagePlaneWidget.SetSliceIndex(0)
     self.yImagePlaneWidget.SetInputData( self.transformed_image )
     self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
     self.yImagePlaneWidget.SetSliceIndex(0)
     self.zImagePlaneWidget.SetInputData( self.transformed_image )
     self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
     self.zImagePlaneWidget.SetSliceIndex(0)
         
     self.xImagePlaneWidget.On()
     self.yImagePlaneWidget.On()
     self.zImagePlaneWidget.On()
     
     # set up cube actor with Orientation(A-P, S-I, L-R) using transform_cube
     # Set up to ALS (+X=A, +Y=S, +Z=L) source:
     cube = vtk.vtkAnnotatedCubeActor()
     cube.SetXPlusFaceText( "L" );
     cube.SetXMinusFaceText( "R" );
     cube.SetYPlusFaceText( "A" );
     cube.SetYMinusFaceText( "P" );
     cube.SetZPlusFaceText( "S" );
     cube.SetZMinusFaceText( "I" );
     cube.SetFaceTextScale( 0.5 );
     cube.GetAssembly().SetUserTransform( transform_cube );
         
     # Set UP the axes
     axes2 = vtk.vtkAxesActor()
     axes2.SetShaftTypeToCylinder();
     #axes2.SetUserTransform( transform_cube );         
     axes2.SetTotalLength( 1.5, 1.5, 1.5 );
     axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() );
     axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() );
     axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() );
 
     tprop2 = axes2.GetXAxisCaptionActor2D()
     tprop2.GetCaptionTextProperty();
 
     assembly = vtk.vtkPropAssembly();
     assembly.AddPart( axes2 );
     assembly.AddPart( cube );
     
     widget = vtk.vtkOrientationMarkerWidget();
     widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 );
     widget.SetOrientationMarker( assembly );
     widget.SetInteractor( self.iren1 );
     widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
     widget.SetEnabled( 1 );
     widget.InteractiveOff();
                 
     # Create a text property for both cube axes
     tprop = vtk.vtkTextProperty()
     tprop.SetColor(1, 1, 1)
     tprop.ShadowOff()
     
     # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
     # draw the axes.  Add the actor to the renderer.
     axes = vtk.vtkCubeAxesActor2D()
     axes.SetInputData(self.transformed_image)
     axes.SetCamera(self.renderer1.GetActiveCamera())
     axes.SetLabelFormat("%6.4g")
     axes.SetFlyModeToOuterEdges()
     axes.SetFontFactor(1.2)
     axes.SetAxisTitleTextProperty(tprop)
     axes.SetAxisLabelTextProperty(tprop)      
     self.renderer1.AddViewProp(axes)
     
     ############
     # bounds and initialize camera
     bounds = self.transformed_image.GetBounds()
     self.renderer1.ResetCamera(bounds)    
     self.renderer1.ResetCameraClippingRange()
     self.camera.SetViewUp(0.0,-1.0,0.0)
     self.camera.Azimuth(315)
     
     # Initizalize
     self.renWin1.Modified()
     self.renWin1.Render()
     self.renderer1.Render()
     
     if(interact==True):
         interactor = self.renWin1.GetInteractor()
         interactor.Start()
                         
     return
Exemplo n.º 39
0
    def run(self):
        doImports()

        self.renWin = vtk.vtkRenderWindow()
        self.ren = vtk.vtkRenderer()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(600, 600)
        self.ren.SetBackground(0.7, 0.7, 0.7)
        self.ren.ResetCamera()
        self.cam = self.ren.GetActiveCamera()

        self.axes = vtk.vtkCubeAxesActor2D()
        self.axes.SetCamera(self.ren.GetActiveCamera())

        self.undefinedActor=vtk.vtkTextActor()
        self.undefinedActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        self.undefinedActor.GetPositionCoordinate().SetValue(0.05,0.2)
        self.undefinedActor.GetTextProperty().SetColor(1.,0.,0.)
        self.undefinedActor.SetInput("")

        try:
            self.readFile()
        except Exception:
            e = sys.exc_info()[1] # Needed because python 2.5 does not support 'as e'
            warning("While reading",self.parser.getArgs()[0],"this happened:",e)
            raise e

        self.ren.ResetCamera()

        self.root = tkinter.Tk()
        self.root.withdraw()

        # Create the toplevel window
        self.top = tkinter.Toplevel(self.root)
        self.top.title("blockMesh-Viewer")
        self.top.protocol("WM_DELETE_WINDOW", self.quit)

        # Create some frames
        self.f1 = tkinter.Frame(self.top)
        self.f2 = tkinter.Frame(self.top)

        self.f1.pack(side="top", anchor="n", expand=1, fill="both")
        self.f2.pack(side="bottom", anchor="s", expand="f", fill="x")

        # Create the Tk render widget, and bind the events
        self.rw = vtkTkRenderWindowInteractor(self.f1, width=400, height=400, rw=self.renWin)
        self.rw.pack(expand="t", fill="both")

        self.blockHigh=tkinter.IntVar()
        self.blockHigh.set(-1)

        self.oldBlock=-1
        self.blockActor=None
        self.blockTextActor=None

        self.patchHigh=tkinter.IntVar()
        self.patchHigh.set(-1)

        self.oldPatch=-1
        self.patchActor=None
        self.patchTextActor=vtk.vtkTextActor()
        self.patchTextActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        self.patchTextActor.GetPositionCoordinate().SetValue(0.05,0.1)
        self.patchTextActor.GetTextProperty().SetColor(0.,0.,0.)
        self.patchTextActor.SetInput("Patch: <none>")

        self.scroll=tkinter.Scale(self.f2,orient='horizontal',
                                  from_=-1,to=len(self.blocks)-1,resolution=1,tickinterval=1,
                                  label="Block (-1 is none)",
                                  variable=self.blockHigh,command=self.colorBlock)

        self.scroll.pack(side="top", expand="t", fill="x")

        self.scroll2=tkinter.Scale(self.f2,orient='horizontal',
                                   from_=-1,to=len(list(self.patches.keys()))-1,resolution=1,tickinterval=1,
                                   label="Patch (-1 is none)",
                                   variable=self.patchHigh,command=self.colorPatch)

        self.scroll2.pack(side="top", expand="t", fill="x")

        self.f3 = tkinter.Frame(self.f2)
        self.f3.pack(side="bottom", anchor="s", expand="f", fill="x")

        self.b1 = tkinter.Button(self.f3, text="Quit", command=self.quit)
        self.b1.pack(side="left", expand="t", fill="x")
        self.b2 = tkinter.Button(self.f3, text="Reread blockMeshDict", command=self.reread)
        self.b2.pack(side="left", expand="t", fill="x")

        self.root.update()

        self.iren = self.renWin.GetInteractor()
        self.istyle = vtk.vtkInteractorStyleSwitch()

        self.iren.SetInteractorStyle(self.istyle)
        self.istyle.SetCurrentStyleToTrackballCamera()

        self.addProps()

        self.iren.Initialize()
        self.renWin.Render()
        self.iren.Start()

        self.root.mainloop()
Exemplo n.º 40
0
  def set_initial_display(self):
    if self.renwininter is None:
      self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter)
      self.renwininter.setWhatsThis(rendering_control_instructions)
      self.renwin = self.renwininter.GetRenderWindow()
      self.inter = self.renwin.GetInteractor()
      self.winsplitter.insertWidget(0,self.renwininter)
      self.winsplitter.addWidget(self.v_box_controls)
      self.winsplitter.setSizes([500,100])
      self.renwininter.show()

# Paul Kemper suggested the following:
      camstyle = vtk.vtkInteractorStyleTrackballCamera()
      self.renwininter.SetInteractorStyle(camstyle)


    self.extents =  self.image_array.GetDataExtent()
    self.spacing = self.image_array.GetDataSpacing()
    self.origin = self.image_array.GetDataOrigin()

# An outline is shown for context.
    if self.warped_surface:
      self.index_selector.initWarpContextmenu()
      sx, sy, sz = self.image_array.GetDataSpacing()
      xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent()
      xMin = sx * xMin
      xMax = sx * xMax
      yMin = sy * yMin
      yMax = sy * yMax
      self.scale_factor = 0.5 * ((xMax-xMin) + (yMax-yMin)) / (self.data_max - self.data_min)
      zMin = self.data_min * self.scale_factor
      zMax = self.data_max * self.scale_factor
      self.outline = vtk.vtkOutlineSource();
      self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax)
    else:
      self.index_selector.init3DContextmenu()
      self.outline = vtk.vtkOutlineFilter()
      self.outline.SetInput(self.image_array.GetOutput())
    outlineMapper = vtk.vtkPolyDataMapper();
    outlineMapper.SetInput(self.outline.GetOutput() );
    outlineActor = vtk.vtkActor();
    outlineActor.SetMapper(outlineMapper);

# create blue to red color table
    self.lut = vtk.vtkLookupTable()
    self.lut.SetHueRange(0.6667, 0.0)
    self.lut.SetNumberOfColors(256)
    self.lut.Build()

# here is where the 2-D image gets warped
    if self.warped_surface:
      geometry = vtk.vtkImageDataGeometryFilter()
      geometry.SetInput(self.image_array.GetOutput())
      self.warp = vtk.vtkWarpScalar()
      self.warp.SetInput(geometry.GetOutput())
      self.warp.SetScaleFactor(self.scale_factor)
      self.mapper = vtk.vtkPolyDataMapper();
      self.mapper.SetInput(self.warp.GetPolyDataOutput())
      self.mapper.SetScalarRange(self.data_min,self.data_max)
      self.mapper.SetLookupTable(self.lut)
      self.mapper.ImmediateModeRenderingOff()
      warp_actor = vtk.vtkActor()
#     warp_actor.SetScale(2,1,1)
      warp_actor.SetMapper(self.mapper)

      min_range = 0.5 * self.scale_factor
      max_range = 2.0 * self.scale_factor
      self.index_selector.set_emit(False)
      self.index_selector.setMaxValue(max_range,False)
      self.index_selector.setMinValue(min_range)
      self.index_selector.setTickInterval( (max_range - min_range) / 10 )
      self.index_selector.setRange(max_range, False)
      self.index_selector.setValue(self.scale_factor)
      self.index_selector.setLabel('display gain')
      self.index_selector.hideNDControllerOption()
      self.index_selector.reset_scale_toggle()
      self.index_selector.set_emit(True)
    else:
# set up ImagePlaneWidgets ...

# The shared picker enables us to use 3 planes at one time
# and gets the picking order right
      picker = vtk.vtkCellPicker()
      picker.SetTolerance(0.005)

# get locations for initial slices
      xMin, xMax, yMin, yMax, zMin, zMax =  self.extents
      x_index = (xMax-xMin) / 2
      y_index = (yMax-yMin) / 2
      z_index = (zMax-zMin) / 2

# The 3 image plane widgets are used to probe the dataset.
      self.planeWidgetX = vtk.vtkImagePlaneWidget()
      self.planeWidgetX.DisplayTextOn()
      self.planeWidgetX.SetInput(self.image_array.GetOutput())
      self.planeWidgetX.SetPlaneOrientationToXAxes()
      self.planeWidgetX.SetSliceIndex(x_index)
      self.planeWidgetX.SetPicker(picker)
      self.planeWidgetX.SetKeyPressActivationValue("x")
      self.planeWidgetX.SetLookupTable(self.lut)
      self.planeWidgetX.TextureInterpolateOff()
      self.planeWidgetX.SetResliceInterpolate(0)

      self.planeWidgetY = vtk.vtkImagePlaneWidget()
      self.planeWidgetY.DisplayTextOn()
      self.planeWidgetY.SetInput(self.image_array.GetOutput())
      self.planeWidgetY.SetPlaneOrientationToYAxes()
      self.planeWidgetY.SetSliceIndex(y_index)
      self.planeWidgetY.SetPicker(picker)
      self.planeWidgetY.SetKeyPressActivationValue("y")
      self.planeWidgetY.SetLookupTable(self.planeWidgetX.GetLookupTable())
      self.planeWidgetY.TextureInterpolateOff()
      self.planeWidgetY.SetResliceInterpolate(0)

      self.planeWidgetZ = vtk.vtkImagePlaneWidget()
      self.planeWidgetZ.DisplayTextOn()
      self.planeWidgetZ.SetInput(self.image_array.GetOutput())
      self.planeWidgetZ.SetPlaneOrientationToZAxes()
      self.planeWidgetZ.SetSliceIndex(z_index)
      self.planeWidgetZ.SetPicker(picker)
      self.planeWidgetZ.SetKeyPressActivationValue("z")
      self.planeWidgetZ.SetLookupTable(self.planeWidgetX.GetLookupTable())
      self.planeWidgetZ.TextureInterpolateOff()
      self.planeWidgetZ.SetResliceInterpolate(0)
    
      self.current_widget = self.planeWidgetZ
      self.mode_widget = self.planeWidgetZ
      self.index_selector.set_emit(False)
      self.index_selector.setMinValue(zMin)
      self.index_selector.setMaxValue(zMax,False)
      self.index_selector.setTickInterval( (zMax-zMin) / 10 )
      self.index_selector.setRange(zMax, False)
      self.index_selector.setValue(z_index)
      self.index_selector.setLabel('Z axis')
      self.index_selector.reset_scale_toggle()
      self.index_selector.set_emit(True)

# create scalar bar for display of intensity range
    self.scalar_bar = vtk.vtkScalarBarActor()
    self.scalar_bar.SetLookupTable(self.lut)
    self.scalar_bar.SetOrientationToVertical()
    self.scalar_bar.SetWidth(0.1)
    self.scalar_bar.SetHeight(0.8)
    self.scalar_bar.SetTitle("Intensity")
    self.scalar_bar.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
    self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1)


# Create the RenderWindow and Renderer
    self.ren = vtk.vtkRenderer()
    self.renwin.AddRenderer(self.ren)
    
# Add the outline actor to the renderer, set the background color and size
    if self.warped_surface:
      self.ren.AddActor(warp_actor)
    self.ren.AddActor(outlineActor)
    self.ren.SetBackground(0.1, 0.1, 0.2)
    self.ren.AddActor2D(self.scalar_bar)

# Create a text property for cube axes
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(1, 1, 1)
    tprop.ShadowOn()

# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
# draw the axes.  Add the actor to the renderer.
    self.axes = vtk.vtkCubeAxesActor2D()
    if self.warped_surface:
      if zMin < 0.0 and zMax > 0.0:
        zLoc = 0.0
      else:
        zLoc = zMin 
      self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc)
      self.axes.SetZLabel(" ")
    else:
      self.axes.SetInput(self.image_array.GetOutput())
      self.axes.SetZLabel("Z")
    self.axes.SetCamera(self.ren.GetActiveCamera())
    self.axes.SetLabelFormat("%6.4g")
    self.axes.SetFlyModeToOuterEdges()
    self.axes.SetFontFactor(0.8)
    self.axes.SetAxisTitleTextProperty(tprop)
    self.axes.SetAxisLabelTextProperty(tprop)
    self.axes.SetXLabel("X")
    self.axes.SetYLabel("Y")
    self.ren.AddProp(self.axes)

# Set the interactor for the widgets
    if not self.warped_surface:
      self.planeWidgetX.SetInteractor(self.inter)
      self.planeWidgetX.On()
      self.planeWidgetY.SetInteractor(self.inter)
      self.planeWidgetY.On()
      self.planeWidgetZ.SetInteractor(self.inter)
      self.planeWidgetZ.On()

    self.initialize_camera()
Exemplo n.º 41
0
def show_neurons(tree_dict,
                 label_nodes_dict={},
                 labels_dict={},
                 priorities_dict={},
                 pos_dict={},
                 rot_dict={},
                 nodecolor=ng.nodecolor_4cp,
                 background=(0, 0, 0),
                 lines=False,
                 relative=True,
                 stereo=False,
                 axes=True,
                 fullscreen=True):
    """
    tree_dict: dict containing {cell_name: morphology tree}
    label_nodes_dict: {cell_name: list of label nodes}
    labels_dict: {cell_name: list of labels corresponding to label nodes}
    priorities_dict: {cell_name: list of priorities of the labels}
    axes: If true, show axis with scale bar info
    """
    label_actors = {}
    neuron_actors = {}
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(*background)

    for cell, neurotree in tree_dict.items():
        label_nodes = label_nodes_dict.get(cell, [])
        labels = labels_dict.get(cell, [])
        priorities = priorities_dict.get(cell, [])
        pos = pos_dict.get(cell, [0, 0, 0])
        rot = rot_dict.get(cell, [])
        neuron_actor, label_actor = neuron3d(neurotree,
                                             label_nodes=label_nodes,
                                             labels=labels,
                                             priorities=priorities,
                                             pos=pos,
                                             rot=rot,
                                             nodecolor=nodecolor,
                                             lines=lines,
                                             relative=relative)
        neuron_actors[cell] = neuron_actor
        label_actors[cell] = label_actor
        renderer.AddActor(neuron_actor)
        if label_actor is not None:
            renderer.AddActor2D(label_actor)
    if axes:  # show axis with scale bar info
        _ax = vtk.vtkCubeAxesActor2D()
        _ax.SetLabelFormat('%3.0f')
        _ax.SetNumberOfLabels(0)
        # _ax.SetYAxisVisibility(False)
        # _ax.SetZAxisVisibility(False)
        _ax.SetBounds(0, 200, 0, 200, 0, 200)
        _ax.SetXLabel('X')
        _ax.SetYLabel('Y')
        _ax.SetZLabel('Z')
        _ax.SetXOrigin(0)
        _ax.SetYOrigin(0)
        _ax.SetZOrigin(0)
        color = (1.0 - background[0], 1.0 - background[1], 1.0 - background[2])
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(color)
        _ax.SetAxisLabelTextProperty(tprop)
        _ax.GetProperty().SetColor(*color)
        # _ax.SetFlyModeToClosestTriad()
        _ax.SetCamera(renderer.GetActiveCamera())
        renderer.AddActor(_ax)
    renderer.ResetCamera()
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    if fullscreen:
        win.FullScreenOn()
    if stereo:
        win.GetStereoCapableWindow()
        win.StereoCapableWindowOn()
        win.SetStereoRender(1)
        win.SetStereoTypeToCrystalEyes()
        win.SetFullScreen(1)
        #win.SetStereoTypeToRedBlue()

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(win)

    win.Render()
    interactor.Initialize()
    interactor.Start()
Exemplo n.º 42
0
    def set_initial_display(self):
        if self.renwininter is None:
            self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter)
            self.renwininter.setWhatsThis(rendering_control_instructions)
            self.renwin = self.renwininter.GetRenderWindow()
            self.inter = self.renwin.GetInteractor()
            self.winsplitter.insertWidget(0, self.renwininter)
            self.winsplitter.addWidget(self.v_box_controls)
            self.winsplitter.setSizes([500, 100])
            self.renwininter.show()

            # Paul Kemper suggested the following:
            camstyle = vtk.vtkInteractorStyleTrackballCamera()
            self.renwininter.SetInteractorStyle(camstyle)

        self.extents = self.image_array.GetDataExtent()
        self.spacing = self.image_array.GetDataSpacing()
        self.origin = self.image_array.GetDataOrigin()

        # An outline is shown for context.
        if self.warped_surface:
            self.index_selector.initWarpContextmenu()
            sx, sy, sz = self.image_array.GetDataSpacing()
            xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent(
            )
            xMin = sx * xMin
            xMax = sx * xMax
            yMin = sy * yMin
            yMax = sy * yMax
            self.scale_factor = 0.5 * (
                (xMax - xMin) +
                (yMax - yMin)) / (self.data_max - self.data_min)
            zMin = self.data_min * self.scale_factor
            zMax = self.data_max * self.scale_factor
            self.outline = vtk.vtkOutlineSource()
            self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax)
        else:
            self.index_selector.init3DContextmenu()
            self.outline = vtk.vtkOutlineFilter()
            self.outline.SetInput(self.image_array.GetOutput())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInput(self.outline.GetOutput())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # create blue to red color table
        self.lut = vtk.vtkLookupTable()
        self.lut.SetHueRange(0.6667, 0.0)
        self.lut.SetNumberOfColors(256)
        self.lut.Build()

        # here is where the 2-D image gets warped
        if self.warped_surface:
            geometry = vtk.vtkImageDataGeometryFilter()
            geometry.SetInput(self.image_array.GetOutput())
            self.warp = vtk.vtkWarpScalar()
            self.warp.SetInput(geometry.GetOutput())
            self.warp.SetScaleFactor(self.scale_factor)
            self.mapper = vtk.vtkPolyDataMapper()
            self.mapper.SetInput(self.warp.GetPolyDataOutput())
            self.mapper.SetScalarRange(self.data_min, self.data_max)
            self.mapper.SetLookupTable(self.lut)
            self.mapper.ImmediateModeRenderingOff()
            warp_actor = vtk.vtkActor()
            #     warp_actor.SetScale(2,1,1)
            warp_actor.SetMapper(self.mapper)

            min_range = 0.5 * self.scale_factor
            max_range = 2.0 * self.scale_factor
            self.index_selector.set_emit(False)
            self.index_selector.setMaxValue(max_range, False)
            self.index_selector.setMinValue(min_range)
            self.index_selector.setTickInterval((max_range - min_range) / 10)
            self.index_selector.setRange(max_range, False)
            self.index_selector.setValue(self.scale_factor)
            self.index_selector.setLabel('display gain')
            self.index_selector.hideNDControllerOption()
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)
        else:
            # set up ImagePlaneWidgets ...

            # The shared picker enables us to use 3 planes at one time
            # and gets the picking order right
            picker = vtk.vtkCellPicker()
            picker.SetTolerance(0.005)

            # get locations for initial slices
            xMin, xMax, yMin, yMax, zMin, zMax = self.extents
            x_index = (xMax - xMin) / 2
            y_index = (yMax - yMin) / 2
            z_index = (zMax - zMin) / 2

            # The 3 image plane widgets are used to probe the dataset.
            self.planeWidgetX = vtk.vtkImagePlaneWidget()
            self.planeWidgetX.DisplayTextOn()
            self.planeWidgetX.SetInput(self.image_array.GetOutput())
            self.planeWidgetX.SetPlaneOrientationToXAxes()
            self.planeWidgetX.SetSliceIndex(x_index)
            self.planeWidgetX.SetPicker(picker)
            self.planeWidgetX.SetKeyPressActivationValue("x")
            self.planeWidgetX.SetLookupTable(self.lut)
            self.planeWidgetX.TextureInterpolateOff()
            self.planeWidgetX.SetResliceInterpolate(0)

            self.planeWidgetY = vtk.vtkImagePlaneWidget()
            self.planeWidgetY.DisplayTextOn()
            self.planeWidgetY.SetInput(self.image_array.GetOutput())
            self.planeWidgetY.SetPlaneOrientationToYAxes()
            self.planeWidgetY.SetSliceIndex(y_index)
            self.planeWidgetY.SetPicker(picker)
            self.planeWidgetY.SetKeyPressActivationValue("y")
            self.planeWidgetY.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetY.TextureInterpolateOff()
            self.planeWidgetY.SetResliceInterpolate(0)

            self.planeWidgetZ = vtk.vtkImagePlaneWidget()
            self.planeWidgetZ.DisplayTextOn()
            self.planeWidgetZ.SetInput(self.image_array.GetOutput())
            self.planeWidgetZ.SetPlaneOrientationToZAxes()
            self.planeWidgetZ.SetSliceIndex(z_index)
            self.planeWidgetZ.SetPicker(picker)
            self.planeWidgetZ.SetKeyPressActivationValue("z")
            self.planeWidgetZ.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetZ.TextureInterpolateOff()
            self.planeWidgetZ.SetResliceInterpolate(0)

            self.current_widget = self.planeWidgetZ
            self.mode_widget = self.planeWidgetZ
            self.index_selector.set_emit(False)
            self.index_selector.setMinValue(zMin)
            self.index_selector.setMaxValue(zMax, False)
            self.index_selector.setTickInterval((zMax - zMin) / 10)
            self.index_selector.setRange(zMax, False)
            self.index_selector.setValue(z_index)
            self.index_selector.setLabel('Z axis')
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)

# create scalar bar for display of intensity range
        self.scalar_bar = vtk.vtkScalarBarActor()
        self.scalar_bar.SetLookupTable(self.lut)
        self.scalar_bar.SetOrientationToVertical()
        self.scalar_bar.SetWidth(0.1)
        self.scalar_bar.SetHeight(0.8)
        self.scalar_bar.SetTitle("Intensity")
        self.scalar_bar.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedViewport()
        self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1)

        # Create the RenderWindow and Renderer
        self.ren = vtk.vtkRenderer()
        self.renwin.AddRenderer(self.ren)

        # Add the outline actor to the renderer, set the background color and size
        if self.warped_surface:
            self.ren.AddActor(warp_actor)
        self.ren.AddActor(outlineActor)
        self.ren.SetBackground(0.1, 0.1, 0.2)
        self.ren.AddActor2D(self.scalar_bar)

        # Create a text property for cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1, 1, 1)
        tprop.ShadowOn()

        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        self.axes = vtk.vtkCubeAxesActor2D()
        if self.warped_surface:
            if zMin < 0.0 and zMax > 0.0:
                zLoc = 0.0
            else:
                zLoc = zMin
            self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc)
            self.axes.SetZLabel(" ")
        else:
            self.axes.SetInput(self.image_array.GetOutput())
            self.axes.SetZLabel("Z")
        self.axes.SetCamera(self.ren.GetActiveCamera())
        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFlyModeToOuterEdges()
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("X")
        self.axes.SetYLabel("Y")
        self.ren.AddProp(self.axes)

        # Set the interactor for the widgets
        if not self.warped_surface:
            self.planeWidgetX.SetInteractor(self.inter)
            self.planeWidgetX.On()
            self.planeWidgetY.SetInteractor(self.inter)
            self.planeWidgetY.On()
            self.planeWidgetZ.SetInteractor(self.inter)
            self.planeWidgetZ.On()

        self.initialize_camera()
	def initializeVTK(self):
		"""
		Code to initialize VTK portions of this widget
		"""           
		
		self.renWin = self.wxrenwin.GetRenderWindow()
		
		ren = self.renderer = self.wxrenwin.getRenderer()
		
		ren.SetBackground(0, 0, 0)
		self.wxrenwin.Render()

		self.iren = iren = self.renWin.GetInteractor()
		self.iren.SetSize(self.renWin.GetSize())

		self.dataExtensionX = 50
		self.dataExtensionY = 50
		self.dataExtensionZ = 50

		self.data = None
		self.interactionCallback = None
		
		self.spline = spline = vtk.vtkSplineWidget()
		self.spline.GetLineProperty().SetColor(1, 0, 0)
		self.spline.GetHandleProperty().SetColor(0, 1, 0)
		self.spline.SetResolution(10000)
		
		self.spline.SetInteractor(self.iren)
		self.style = self.iren.GetInteractorStyle()
		
		self.spline.AddObserver("EndInteractionEvent", self.endInteraction)
		self.spline.AddObserver("InteractionEvent", self.endInteraction)
		self.style.AddObserver("EndInteractionEvent", self.endInteraction)
		self.style.AddObserver("InteractionEvent", self.endInteraction)        
		self.iren.AddObserver("EndInteractionEvent", self.endInteraction)
		self.iren.AddObserver("InteractionEvent", self.endInteraction)                

		self.spline.On()
		
		self.spline.SetEnabled(1)        
		self.style.SetEnabled(1)
		
		self.outline = vtk.vtkOutlineFilter ()
		self.outlinemapper = vtk.vtkPolyDataMapper ()
		self.outlineactor = vtk.vtkActor ()
		self.axes = vtk.vtkCubeAxesActor2D ()
		self.initCamera()
				
		self.arrow = vtk.vtkArrowSource()

		self.arrowTransform = vtk.vtkTransform()
		self.arrowTransform.RotateX(90.0)
		self.arrowTransform.Scale(80.0, 200.0, 200.0)

		self.transformFilter = vtk.vtkTransformFilter()
			
		self.transformFilter.SetTransform(self.arrowTransform)
		self.transformFilter.SetInput(self.arrow.GetOutput())
		self.arrowMapper = vtk.vtkPolyDataMapper()
		self.arrowMapper.SetInput(self.transformFilter.GetOutput())
		self.arrowActor = vtk.vtkActor()
		self.arrowActor.GetProperty().SetColor((0, 0, 1))
		self.arrowActor.SetMapper(self.arrowMapper)

		self.renderer.AddActor(self.arrowActor)    
		
		self.arrowActor.SetVisibility(0)
		
		self.wxrenwin.Render()
vprop.ShadeOn()
vprop.SetAmbient(0.1)
vprop.SetDiffuse(0.7)
vprop.SetSpecular(0.4)
vprop.SetSpecularPower(60)  # 10

volume = vtkVolume()
volume.SetProperty(vprop)
volume.SetMapper(splatmapper)

ren = vtkRenderer()
ren.SetBackground(0.5, 0.5, 0.5)
ren.AddVolume(volume)
#ren.GetActiveCamera().ParallelProjectionOn()

cubeAxesActor2d = vtk.vtkCubeAxesActor2D()
cubeAxesActor2d.SetFlyModeToOuterEdges()
ren.AddActor(cubeAxesActor2d)
cubeAxesActor2d.VisibilityOff()  # turn on here!
v16.Update()
cubeAxesActor2d.SetBounds(v16.GetOutput().GetBounds())
cubeAxesActor2d.SetCamera(ren.GetActiveCamera())

renwin = vtkRenderWindow()
renwin.SetSize(512, 512)
renwin.AddRenderer(ren)

rwi = vtkRenderWindowInteractor()
rwi.SetRenderWindow(renwin)

rwi.AddObserver('CharEvent', ce_cb)
Exemplo n.º 45
0
ren.AddViewProp(foheActor)
ren.AddViewProp(outlineActor)
ren2.AddViewProp(foheActor)
ren2.AddViewProp(outlineActor)

ren.SetBackground(0.1, 0.2, 0.4)
ren2.SetBackground(0.1, 0.2, 0.4)

# Create a text property for both cube axes
tprop = vtk.vtkTextProperty()
tprop.SetColor(1, 1, 1)
tprop.ShadowOn()

# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
# draw the axes.  Add the actor to the renderer.
axes = vtk.vtkCubeAxesActor2D()
axes.SetInputConnection(normals.GetOutputPort())
axes.SetCamera(ren.GetActiveCamera())
axes.SetLabelFormat("%6.4g")
axes.SetFlyModeToOuterEdges()
axes.SetFontFactor(0.8)
axes.SetAxisTitleTextProperty(tprop)
axes.SetAxisLabelTextProperty(tprop)
ren.AddViewProp(axes)

# Create a vtkCubeAxesActor2D.  Use the closest vertex to the camera to
# determine where to draw the axes.  Add the actor to the renderer.
axes2 = vtk.vtkCubeAxesActor2D()
axes2.SetViewProp(foheActor)
axes2.SetCamera(ren2.GetActiveCamera())
axes2.SetLabelFormat("%6.4g")
Exemplo n.º 46
0
def neuron3d(neuron_graph,
             label_nodes=[],
             labels=[],
             priorities=[],
             nodecolor=nodecolor_4cp,
             background=(0, 0, 0),
             lines=False,
             stereo=False,
             axes=True,
             fullscreen=True):
    """axes: If true, show axis with scale bar info
    """
    renderer, actor = nrngraph2vtk(neuron_graph,
                                   label_nodes=label_nodes,
                                   labels=labels,
                                   priorities=priorities,
                                   nodecolor=nodecolor,
                                   background=background,
                                   lines=lines)
    if axes:  # show axis with scale bar info
        _ax = vtk.vtkCubeAxesActor2D()
        _ax.SetLabelFormat('%3.0f')
        _ax.SetNumberOfLabels(0)
        _ax.SetYAxisVisibility(False)
        _ax.SetZAxisVisibility(False)
        _ax.SetBounds(0, 200, -600, -400, 0, 200)
        _ax.SetXLabel('')
        _ax.SetXOrigin(0)
        _ax.SetYOrigin(-600)
        _ax.SetZOrigin(0)
        color = (1.0 - background[0], 1.0 - background[1], 1.0 - background[2])
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(color)
        _ax.SetAxisLabelTextProperty(tprop)
        _ax.GetProperty().SetColor(*color)
        _ax.SetFlyModeToClosestTriad()
        _ax.SetCamera(renderer.GetActiveCamera())
        renderer.AddActor(_ax)
    renderer.ResetCamera()
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    if fullscreen:
        win.FullScreenOn()
    if stereo:
        win.GetStereoCapableWindow()
        win.StereoCapableWindowOn()
        win.SetStereoRender(1)
        win.SetStereoTypeToCrystalEyes()
        win.SetFullScreen(1)
        #win.SetStereoTypeToRedBlue()

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(win)

    win.Render()

    # exporter = vtk.vtkX3DExporter()
    # exporter.SetFileName('ggn.x3d')
    # exporter.SetRenderWindow(win)
    # exporter.Write()

    interactor.Initialize()
    interactor.Start()
Exemplo n.º 47
0
ren.AddViewProp(foheActor)
ren.AddViewProp(outlineActor)
ren2.AddViewProp(foheActor)
ren2.AddViewProp(outlineActor)

ren.SetBackground(0.1, 0.2, 0.4)
ren2.SetBackground(0.1, 0.2, 0.4)

# Create a text property for both cube axes
tprop = vtk.vtkTextProperty()
tprop.SetColor(1, 1, 1)
tprop.ShadowOn()

# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
# draw the axes.  Add the actor to the renderer.
axes = vtk.vtkCubeAxesActor2D()
axes.SetInputConnection(normals.GetOutputPort())
axes.SetCamera(ren.GetActiveCamera())
axes.SetLabelFormat("%6.4g")
axes.SetFlyModeToOuterEdges()
axes.SetFontFactor(0.8)
axes.SetAxisTitleTextProperty(tprop)
axes.SetAxisLabelTextProperty(tprop)
ren.AddViewProp(axes)

# Create a vtkCubeAxesActor2D.  Use the closest vertex to the camera to
# determine where to draw the axes.  Add the actor to the renderer.
axes2 = vtk.vtkCubeAxesActor2D()
axes2.SetViewProp(foheActor)
axes2.SetCamera(ren2.GetActiveCamera())
axes2.SetLabelFormat("%6.4g")
Exemplo n.º 48
0
    def initializeVTK(self):
        """
		Code to initialize VTK portions of this widget
		"""

        self.renWin = self.wxrenwin.GetRenderWindow()

        ren = self.renderer = self.wxrenwin.getRenderer()

        ren.SetBackground(0, 0, 0)
        self.wxrenwin.Render()

        self.iren = iren = self.renWin.GetInteractor()
        self.iren.SetSize(self.renWin.GetSize())

        self.dataExtensionX = 50
        self.dataExtensionY = 50
        self.dataExtensionZ = 50

        self.data = None
        self.interactionCallback = None

        self.spline = spline = vtk.vtkSplineWidget()
        self.spline.GetLineProperty().SetColor(1, 0, 0)
        self.spline.GetHandleProperty().SetColor(0, 1, 0)
        self.spline.SetResolution(10000)

        self.spline.SetInteractor(self.iren)
        self.style = self.iren.GetInteractorStyle()

        self.spline.AddObserver("EndInteractionEvent", self.endInteraction)
        self.spline.AddObserver("InteractionEvent", self.endInteraction)
        self.style.AddObserver("EndInteractionEvent", self.endInteraction)
        self.style.AddObserver("InteractionEvent", self.endInteraction)
        self.iren.AddObserver("EndInteractionEvent", self.endInteraction)
        self.iren.AddObserver("InteractionEvent", self.endInteraction)

        self.spline.On()

        self.spline.SetEnabled(1)
        self.style.SetEnabled(1)

        self.outline = vtk.vtkOutlineFilter()
        self.outlinemapper = vtk.vtkPolyDataMapper()
        self.outlineactor = vtk.vtkActor()
        self.axes = vtk.vtkCubeAxesActor2D()
        self.initCamera()

        self.arrow = vtk.vtkArrowSource()

        self.arrowTransform = vtk.vtkTransform()
        self.arrowTransform.RotateX(90.0)
        self.arrowTransform.Scale(80.0, 200.0, 200.0)

        self.transformFilter = vtk.vtkTransformFilter()

        self.transformFilter.SetTransform(self.arrowTransform)
        self.transformFilter.SetInput(self.arrow.GetOutput())
        self.arrowMapper = vtk.vtkPolyDataMapper()
        self.arrowMapper.SetInput(self.transformFilter.GetOutput())
        self.arrowActor = vtk.vtkActor()
        self.arrowActor.GetProperty().SetColor((0, 0, 1))
        self.arrowActor.SetMapper(self.arrowMapper)

        self.renderer.AddActor(self.arrowActor)

        self.arrowActor.SetVisibility(0)

        self.wxrenwin.Render()
vprop.ShadeOn()
vprop.SetAmbient(0.1)
vprop.SetDiffuse(0.7)
vprop.SetSpecular(0.4)
vprop.SetSpecularPower(60) # 10

volume = vtkVolume()
volume.SetProperty(vprop)
volume.SetMapper(splatmapper)

ren = vtkRenderer()
ren.SetBackground(0.5, 0.5, 0.5)
ren.AddVolume(volume)
#ren.GetActiveCamera().ParallelProjectionOn()

cubeAxesActor2d = vtk.vtkCubeAxesActor2D()
cubeAxesActor2d.SetFlyModeToOuterEdges()
ren.AddActor(cubeAxesActor2d)
cubeAxesActor2d.VisibilityOff() # turn on here!
v16.Update()
cubeAxesActor2d.SetBounds(v16.GetOutput().GetBounds())
cubeAxesActor2d.SetCamera(ren.GetActiveCamera())

renwin = vtkRenderWindow()
renwin.SetSize(512, 512)
renwin.AddRenderer(ren)

rwi = vtkRenderWindowInteractor()
rwi.SetRenderWindow(renwin)

rwi.AddObserver('CharEvent', ce_cb)
Exemplo n.º 50
0
    def _createIPW(self):
        # we have to do this to get the correct log range
        self._histogram.GetOutput().Update()
        
        # this means we have newly valid input and should setup an ipw
        self._ipw = vtk.vtkImagePlaneWidget()
        self._histogram.GetOutput().Update()
        self._ipw.SetInput(self._histogram.GetOutput())
        self._ipw.SetInteractor(self._viewFrame.rwi)
        # normal to the Z-axis
        self._ipw.SetPlaneOrientation(2)
        self._ipw.SetSliceIndex(0)

        # setup specific lut
        srange = self._histogram.GetOutput().GetScalarRange()
        lut = vtk.vtkLookupTable()
        lut.SetScaleToLog10()                
        lut.SetTableRange(srange)
        lut.SetSaturationRange(1.0,1.0)
        lut.SetValueRange(1.0, 1.0)
        lut.SetHueRange(0.1, 1.0)
        lut.Build()
        self._ipw.SetUserControlledLookupTable(1)
        self._ipw.SetLookupTable(lut)
        
        self._ipw.SetDisplayText(1)
        # if we use ContinousCursor, we get OffImage when zoomed
        # on Linux (really irritating) but not on Windows.  A VTK
        # recompile might help, we'll see.
        self._ipw.SetUseContinuousCursor(1)
        # make sure the user can't twist the plane out of sight
        self._ipw.SetMiddleButtonAction(0)
        self._ipw.SetRightButtonAction(0)

        # add an observer
        self._ipw.AddObserver('StartInteractionEvent',
                              self._observerIPWInteraction)
        self._ipw.AddObserver('InteractionEvent',
                              self._observerIPWInteraction)
        self._ipw.AddObserver('EndInteractionEvent',
                              self._observerIPWInteraction)
        
        self._ipw.On()

        self._axes = vtk.vtkCubeAxesActor2D()
        self._axes.SetFlyModeToOuterEdges()
        # NOBODY will ever know why we have to switch off the Y axis when
        # we actually want the Z-axis to go away.
        self._axes.YAxisVisibilityOff()
        self._axes.SetBounds(self._ipw.GetResliceOutput().GetBounds())
        
        self._renderer.AddActor(self._axes)
        self._axes.SetCamera(self._renderer.GetActiveCamera())
        self._axes.PickableOff()

        if 0:
            # now add a scalarbar
            self._scalarBarWidget = vtk.vtkScalarBarWidget()
            self._scalarBarWidget.SetInteractor(self._viewFrame.rwi)
            self._scalarBarWidget.GetScalarBarActor().SetTitle('Frequency')
            self._scalarBarWidget.GetScalarBarActor().SetLookupTable(
                lut)
            # and activate
            self._scalarBarWidget.On()
        
        self._resetCamera()
        self._render()