def WriteImage(self, m_outFileName="./Dump/tmp.png", m_dimension=[400, 400]):
        """
        Write current renderer to a png file. For Debug

        :param m_outFileName:   [str] Output name of the file, can be directory name. Default="./Dump/tmp.png"
        :param m_dimension:     [x, y]. Dimension, i.e. width and height of the image file.
        :return:
        """
        if self._renderer.GetRenderWindow() == None:
            self._renderWindow.AddRenderer(self._renderer)

        elif self._renderer.GetRenderWindow() != self._renderWindow:
            self._renderer.GetRenderWindow().Finalize()
            self._renderWindow = vtk.vtkRenderWindow()
            self._renderWindow.AddRenderer(self._renderer)
        else:
            self._renderWindow = vtk.vtkRenderWindow()
            self._renderWindow.AddRenderer(self._renderer)

        self._renderWindow.SetOffScreenRendering(1)
        self._renderWindow.SetSize(m_dimension)
        self._renderWindow.Render()
        self._renderWindow.SetAAFrames(10)

        m_writer = vtk.vtkPNGWriter()
        m_wintoim = vtk.vtkWindowToImageFilter()
        m_wintoim.SetInput(self._renderWindow)
        m_wintoim.Update()

        m_writer.SetInputConnection(m_wintoim.GetOutputPort())
        m_writer.SetFileName(m_outFileName)
        m_writer.Write()

        pass
Ejemplo n.º 2
0
    def build_vtk_renderer(self):

        # offscreen rendering
        if (vtk.vtkVersion().GetVTKMajorVersion() == 5.0):
            graphics_factory = vtk.vtkGraphicsFactory()
            graphics_factory.SetOffScreenOnlyMode( 1);
            graphics_factory.SetUseMesaClasses( 1 );
            imaging_factory = vtk.vtkImagingFactory()
            imaging_factory.SetUseMesaClasses( 1 );
  
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1, 1, 1)
        self.render_window = vtk.vtkRenderWindow()
        # offscreen rendering
        self.render_window.SetOffScreenRendering(1)

        self.render_window.AddRenderer(self.renderer)
        # create a renderwindowinteractor
        #if self.interact:
        #self.iren = vtk.vtkRenderWindowInteractor()
        #self.iren.SetRenderWindow(self.render_window)

        # scalar bar        
        self.scalarbar = vtk.vtkScalarBarActor()
        # To avoid uninitialized warning in VTK 6
        self.scalarbar.SetTitle("") 
        # black text since background is white for printing
        self.scalarbar.GetLabelTextProperty().SetColor(0, 0, 0)
        self.scalarbar.GetTitleTextProperty().SetColor(0, 0, 0)
    def testFixedPointRayCasterLinearCropped(self):

        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        iRen = vtk.vtkRenderWindowInteractor()

        tFPRCN = TestFixedPointRayCasterNearest.FixedPointRayCasterNearest(ren, renWin, iRen)
        volumeProperty = tFPRCN.GetVolumeProperty()
        volumeMapper = tFPRCN.GetVolumeMapper()

        for j in range(0, 5):
            for i in range(0, 5):
                volumeMapper[i][j].SetCroppingRegionPlanes(10, 20, 10, 20, 10, 20)
                volumeMapper[i][j].SetCroppingRegionFlags(253440)
                volumeMapper[i][j].CroppingOn()

                volumeProperty[i][j].SetInterpolationTypeToLinear()

        # render and interact with data

        renWin.Render()

        img_file = "TestFixedPointRayCasterLinearCropped.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=10)
        vtk.test.Testing.interact()
Ejemplo n.º 4
0
def main():
   #Create a sphere
   sphereSource = vtk.vtkSphereSource()
   sphereSource.SetCenter(0.0, 0.0, 0.0)
   sphereSource.SetRadius(5)
 
   #Create a mapper and actor
   mapper = vtk.vtkPolyDataMapper()
   mapper.SetInputConnection(sphereSource.GetOutputPort())
   actor = vtk.vtkActor()
   actor.SetMapper(mapper)
 
   # Setup a renderer, render window, and interactor
   renderer = vtk.vtkRenderer()
   renderWindow = vtk.vtkRenderWindow()
   #renderWindow.SetWindowName("Test")
 
   renderWindow.AddRenderer(renderer);
   renderWindowInteractor = vtk.vtkRenderWindowInteractor()
   renderWindowInteractor.SetRenderWindow(renderWindow)
 
   #Add the actor to the scene
   renderer.AddActor(actor)
   renderer.SetBackground(1,1,1) # Background color white
 
   #Render and interact
   renderWindow.Render()
 
   #*** SetWindowName after renderWindow.Render() is called***
   renderWindow.SetWindowName("Test")
 
   renderWindowInteractor.Start()
Ejemplo n.º 5
0
    def testStyleJoystickActor(self):

        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        testStyleBaseSpike = TestStyleBaseSpike.StyleBaseSpike(ren, renWin, iRen)

        # Set interactor style
        inStyle = vtk.vtkInteractorStyleSwitch()
        iRen.SetInteractorStyle(inStyle)

        # Switch to Joystick+Actor mode

        iRen.SetKeyEventInformation(0, 0, "j", 0)
        iRen.InvokeEvent("CharEvent")

        iRen.SetKeyEventInformation(0, 0, "a", 0)
        iRen.InvokeEvent("CharEvent")
        # Test style
        testStyleBase = TestStyleBase.TestStyleBase(ren)
        testStyleBase.test_style(inStyle.GetCurrentStyle())

        # render and interact with data

        img_file = "TestStyleJoystickActor.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Ejemplo n.º 6
0
def main():
    '''One render window, multiple viewports'''
    iren_list = []
    rw = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(rw)
    # Define viewport ranges
    xmins=[0,.5,0,.5]
    xmaxs=[0.5,1,0.5,1]
    ymins=[0,0,.5,.5]
    ymaxs=[0.5,0.5,1,1]
    for i in range(4):
        ren = vtk.vtkRenderer()
        rw.AddRenderer(ren)
        ren.SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i])
        
        #Create a sphere
        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetCenter(0.0, 0.0, 0.0)
        sphereSource.SetRadius(5)
        
        #Create a mapper and actor
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphereSource.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        ren.AddActor(actor)
        ren.ResetCamera()
    
    rw.Render()
    rw.SetWindowName('RW: Multiple ViewPorts')
    iren.Start()
Ejemplo n.º 7
0
def plotvtk(mesh,boundary):
    meshMapper = vtk.vtkPolyDataMapper()
    meshMapper.SetInputConnection(mesh.GetOutputPort())

    meshActor = vtk.vtkActor()
    meshActor.SetMapper(meshMapper)
    meshActor.GetProperty().SetEdgeColor(0, 0, 1)
    meshActor.GetProperty().SetInterpolationToFlat()
    meshActor.GetProperty().SetRepresentationToWireframe()

    boundaryMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        boundaryMapper.SetInputConnection(boundary.GetProducerPort())
    else:
        boundaryMapper.SetInputData(boundary)

    boundaryActor = vtk.vtkActor()
    boundaryActor.SetMapper(boundaryMapper)
    boundaryActor.GetProperty().SetColor(1, 0, 0)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(meshActor)
    renderer.AddActor(boundaryActor)
    renderer.SetBackground(.3, .6, .3)

    renderWindowInteractor.Initialize()
    renderWindow.Render()
    renderWindowInteractor.Start()
Ejemplo n.º 8
0
def initialize(self, VTKWebApp, args):
    if not VTKWebApp.view:
        # VTK specific code
        renderer = vtk.vtkRenderer()
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer)

        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        renderWindowInteractor.SetRenderWindow(renderWindow)
        renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        cone = vtk.vtkConeSource()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()

        mapper.SetInputConnection(cone.GetOutputPort())
        actor.SetMapper(mapper)

        renderer.AddActor(actor)
        renderer.ResetCamera()
        renderWindow.Render()

        # VTK Web application specific
        VTKWebApp.view = renderWindow
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
Ejemplo n.º 9
0
    def compute(self):
        r = self.get_input("renderer").vtkInstance
        window = vtk.vtkRenderWindow()
        w = self.force_get_input("width", 512)
        h = self.force_get_input("height", 512)
        window.OffScreenRenderingOn()
        window.SetSize(w, h)
        # r.ResetCamera()

        widget = None
        if system.systemType=='Darwin':
            from PyQt4 import QtCore, QtGui
            widget = QtGui.QWidget(None, QtCore.Qt.FramelessWindowHint)
            widget.resize(w, h)
            widget.show()
            window.SetWindowInfo(str(int(widget.winId())))    
       
        window.AddRenderer(r)
#        window.Start()
        window.Render()
        win2image = vtk.vtkWindowToImageFilter()
        win2image.SetInput(window)
        win2image.Update()
        writer = vtk.vtkPNGWriter()
        writer.SetInput(win2image.GetOutput())
        output = self.interpreter.filePool.create_file(suffix='.png')
        writer.SetFileName(output.name)
        writer.Write()
        window.Finalize()
        if widget!=None:
            widget.close()
        self.set_output("image", output)
def view(stlfilename):
    reader = vtk.vtkSTLReader()
    reader.SetFileName(stlfilename)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

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

    # Create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # Create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Assign actor to the renderer
    ren.AddActor(actor)

    # Enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
    def __init__(self, file_list,spacing_list,feature_type,irad = 1.2, h_th=-200,
                 glyph_type='sphere', glyph_scale_factor=1,use_field_data=True, opacity_list=[],
                 color_list=[], lung=[]):
      
        assert feature_type == "ridge_line" or feature_type == "valley_line" \
        or feature_type == "ridge_surface" or feature_type == "valley_surface" \
        or feature_type == "vessel" or feature_type == "airway" \
        or feature_type == "fissure", "Invalid feature type"
      
        if feature_type == "airway":
          feature_type = "valley_line"
        elif feature_type == "vessel":
          feature_type = "ridge_line"
        elif feature_type == "fissure":
          feature_type = "ridge_surface"
      
        self.mapper_list = list()
        self.actor_list = list()
        self.glyph_list = list()
        self.glyph_type = glyph_type
        self.file_list = file_list
        self.spacing_list = spacing_list
        self.opacity_list = opacity_list
        self.irad = irad
        self.h_th = h_th
        self.color_list = color_list
        self.lung = lung
        self.use_field_data = use_field_data
        self.feature_type = feature_type
        self.normal_map=dict()
        self.normal_map['ridge_line'] = "hevec0"
        self.normal_map['valley_line'] = "hevec2"
        self.normal_map['ridge_surface'] = "hevec2"
        self.normal_map['valley_surface'] = "hevec0"
        self.strength_map=dict()
        self.strength_map['ridge_line'] = "h1"
        self.strength_map['valley_line'] = "h1"
        self.strength_map['ridge_surface'] = "h2"
        self.strength_map['valley_surface'] = "h0"
  
        if feature_type == 'ridge_line' or feature_type == 'valley_line':
            self.height = irad
            self.radius = 0.5
        elif feature_type == 'ridge_surface' or feature_type == 'valley_surface':
            self.height = 0.5
            self.radius = irad
  
        self.min_rad = 0.5
        self.max_rad = 6
        self.glyph_scale_factor = glyph_scale_factor

        self.capture_prefix = ""
        self.capture_count = 1

        # VTK Objects
        self.ren = vtk.vtkRenderer()
        self.renWin = vtk.vtkRenderWindow()
        self.iren = vtk.vtkRenderWindowInteractor()
  
        self.image_count = 1
Ejemplo n.º 12
0
    def draw(self):

        # Update location and movement
        self.update()

        # create a rendering window and renderer
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(1200, 900)
        renWin.AddRenderer(ren)

        # Create camera
        camera = vtk.vtkCamera()
        #camera.SetPosition(0.5,10.0,0.0);
        #camera.Roll(-90)
        #ren.SetActiveCamera(camera)

        # create a renderwindowinteractor
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Add actors
        ren.AddActor(self.modelActor)
        ren.AddActor(self.axesActor)

        # enable user interface interactor
        iren.Initialize()
        renWin.Render()
        style = vtk.vtkInteractorStyleMultiTouchCamera()
        iren.SetInteractorStyle(style)
        iren.Start()
Ejemplo n.º 13
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            cone = vtk.vtkConeSource()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()

            mapper.SetInputConnection(cone.GetOutputPort())
            actor.SetMapper(mapper)

            renderer.AddActor(actor)
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
Ejemplo n.º 14
0
 def _init_render(self):
     window = vtk.vtkRenderWindow()
     window.SetSize(int(self.settings.image_width),
                    int(self.settings.image_height))
     window.SetOffScreenRendering(self.settings.offscreen_rendering)
     window.AddRenderer(self._renderer.renderer)
     self.window = window
Ejemplo n.º 15
0
def __test_adjust_sphere():
    import vtk

    n_points = 4
    points = []
    for i in xrange(n_points):
        p = np.random.random(3) * 100
        points.append(p)
    r, ctr = adjust_sphere(points)
    r2 = r / 10
    ren_win = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    iren.SetRenderWindow(ren_win)
    ren = vtk.vtkRenderer()
    ren_win.AddRenderer(ren)
    # draw points
    for p in points:
        __add_sphere_to_ren(p, r2, ren)
    #draw big sphere
    ac = __add_sphere_to_ren(ctr, r, ren)
    ac.GetProperty().SetColor((1, 0, 0))

    iren.Initialize()
    iren.Start()
Ejemplo n.º 16
0
def vtk_basic( actors ):
    """
    Create a window, renderer, interactor, add the actors and start the thing
    
    Parameters
    ----------
    actors :  list of vtkActors
    
    Returns
    -------
    nothing
    """     
    
    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(600,600)
    # ren.SetBackground( 1, 1, 1)
 
    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    for a in actors:
        # assign actor to the renderer
        ren.AddActor(a )

    #enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 17
0
def notebookviz(output):
        width,height = 400, 300
        demMapper = vtkPolyDataMapper()
        demMapper.SetInputConnection(output.GetOutputPort())

        surfaceActor = vtkActor()
        surfaceActor.SetMapper(demMapper)
        surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
        surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
        surfaceActor.GetProperty().SetSpecular(.4)
        surfaceActor.GetProperty().SetSpecularPower(50)

        VtkRenderer = vtkRenderer()
        VtkRenderer.SetBackground(1.0, 1.0, 1.0)
        VtkRenderer.AddActor(surfaceActor)

        renderWindow = vtkRenderWindow()
        renderWindow.SetOffScreenRendering(1)
        renderWindow.AddRenderer(VtkRenderer)
        renderWindow.SetSize(width, height)
        renderWindow.Render()

        windowToImageFilter = vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renderWindow)
        windowToImageFilter.Update()

        writer = vtkPNGWriter()
        writer.SetWriteToMemory(1)
        writer.SetInputConnection(windowToImageFilter.GetOutputPort())
        writer.Write()
        data = str(buffer(writer.GetResult()))

        return Image(data)
Ejemplo n.º 18
0
  def testThreshold(self):
    global args
    writefiles = "SaveData" in args

    renderer = vtk.vtkRenderer()
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    renwin.Render()

    if "GPURender" in args:
        vtk.vtkPistonMapper.InitCUDAGL(renwin)

    src = vtk.vtkImageMandelbrotSource()
    src.SetWholeExtent(0,10,0,10,0,10)

    #scale and bias until piston's threshold understands origin and spacing
    src.Update()
    inputdata = src.GetOutput()
    if "Normalize" in args:
         testdata1 = inputdata.NewInstance()
         testdata1.ShallowCopy(inputdata)
         testdata1.SetSpacing(1,1,1)
         testdata1.SetOrigin(0,0,0)
         inputdata = testdata1

    d2p = vtk.vtkDataSetToPiston()
    d2p.SetInputData(inputdata)
    #d2p.SetInputConnection(src.GetOutputPort())

    threshF = vtk.vtkPistonThreshold()
    threshF.SetInputConnection(d2p.GetOutputPort())
    threshF.SetMinValue(0)
    threshF.SetMaxValue(80)

    p2d = vtk.vtkPistonToDataSet()
    p2d.SetInputConnection(threshF.GetOutputPort())
    p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)

    if writefiles:
        writeFile(p2d, "piston_threshold.vtk")

    mapper = vtk.vtkPistonMapper()
    mapper.SetInputConnection(threshF.GetOutputPort())
    mapper.Update()

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

    renderer.AddActor(actor)

    renderer.ResetCamera()
    renwin.Render()

    img_file = "TestThreshold.png"
    Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

    if Testing.isInteractive():
        iren.Start()
Ejemplo n.º 19
0
def vtk_Nviews( actors ):
    """
    Create a window, an interactor and one renderer per actor
    
    Parameters
    ----------
    actors :  list of vtkActors
    
    Returns
    -------
    nothing
    """    
    N = len(actors)
    
    # create a rendering window and renderers
    renderers = [vtk.vtkRenderer() for i in range(N)]
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize( 600, 600 )
    for i in range(N):
        # split the viewport
        renderers[i].SetViewport(0,float(N-i-1)/N,1,float(N-i)/N)
        renderers[i].SetBackground( 1, 1, 1)
        renderers[i].AddActor( actors[i] )
        renWin.AddRenderer(renderers[i])
 
    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    #enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 20
0
    def __init__(self):

        # Create the Renderer, RenderWindow, etc. and set the Picker.
        self.ren = vtk.vtkRenderer()
        self.renwin = vtk.vtkRenderWindow()
        self.renwin.AddRenderer(self.ren)
        self.ren.SetViewport(0,0,1,1)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renwin)
        
        # Create text mappers and 2d actors to display finger position.
        self.fingerMarker1 = Marker("(1)")
        self.fingerMarker2 = Marker("(2)")
        self.fingerMarker3 = Marker("(3)")
        self.fingerMarker4 = Marker("(4)")
        self.fingerMarker5 = Marker("(5)")

        # Add the actors to the renderer, set the background and size
        self.ren.AddActor2D(self.fingerMarker1.textActor)
        self.ren.AddActor2D(self.fingerMarker2.textActor)
        self.ren.AddActor2D(self.fingerMarker3.textActor)
        self.ren.AddActor2D(self.fingerMarker4.textActor)
        self.ren.AddActor2D(self.fingerMarker5.textActor)
        self.ren.SetBackground(0, 0, 0)
        self.renwin.SetSize(680, 460)
        #self.renwin.FullScreenOn()
        
        '''
        TUIO STUFF
        '''
        self.tracking = tuio.Tracking('')
        self.tracker = CursorTracker(8)
        self.terminate = False
Ejemplo n.º 21
0
	def __init__(self):
		self.outputs=[]
		self.paint=rgbPainter()
		self.scalingFactor=1.0
		self.showAxes=True
		self.showScalarBar=True
		self.showCaption=True
		self.showXYPlane=True
		self.showYZPlane=True
		self.showZXPlane=True
		self.nbSize=80
		self.sampleSpacing=8.0
	
		self.camera = vtk.vtkCamera()

		self.ren = vtk.vtkRenderer();
		self.renWin = vtk.vtkRenderWindow();
		self.renWin.AddRenderer(self.ren);
		self.renWin.SetWindowName("DESICOS-viewer v0.1 ")
		self.iren = vtk.vtkRenderWindowInteractor();
		self.iren.SetRenderWindow(self.renWin);
		style1 = vtk.vtkInteractorStyleTrackballCamera()
		self.iren.SetInteractorStyle(style1)
		self.ren.SetBackground(1, 1, 1);
		self.renWin.SetSize(800, 600);
Ejemplo n.º 22
0
def main():
    setup_vn()
    aPolyVertexGrid1 = Tns.vn.represent_map("pop")[0]
    Tns.vn.update_scalars([a/20. for a in Tns.p1_l_x],
                          [aPolyVertexGrid1], 
                          [len(Tns.p1_l_id)])
    aPolyVertexGrid2 = Tns.vn.represent_map("pop2")[0]
    # aPolyVertexActor = Tns.vn.make_actor_for_grid(aPolyVertexGrid)
    # aPolyVertexActor2 = Tns.vn.make_actor_for_grid(aPolyVertexGrid2)
    lvl_to_g = {0:[aPolyVertexGrid1, aPolyVertexGrid2]}
    #lvl_to_g = Tns.vn.levels_to_grids()
    all_actors = Tns.vn.make_all_actors(lvl_to_g)
    # Create the usual rendering stuff.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(1024, 768)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren.SetBackground(.0, .0, .0)
    for a in all_actors:
        ren.AddActor(a)
    ren.ResetCamera()
    ren.GetActiveCamera().Azimuth(00)
    ren.GetActiveCamera().Elevation(-40)
    ren.GetActiveCamera().Dolly(0)
    ren.ResetCameraClippingRange()
    # Render the scene and start interaction.
    iren.Initialize()
    renWin.Render()
    import time
    time.sleep(0.1)
    iren.Start()
Ejemplo n.º 23
0
def render_to_image(output_filename, vtk_format, renderer, w, h):
    window = vtk.vtkRenderWindow()
    window.OffScreenRenderingOn()
    window.SetSize(w, h)

    # FIXME think this may be fixed in VTK6 so we don't have this
    # dependency...
    widget = None
    if systemType=='Darwin':
        from PyQt4 import QtCore, QtGui
        widget = QtGui.QWidget(None, QtCore.Qt.FramelessWindowHint)
        widget.resize(w, h)
        widget.show()
        window.SetWindowInfo(str(int(widget.winId())))

    window.AddRenderer(renderer)
    window.Render()
    win2image = vtk.vtkWindowToImageFilter()
    win2image.SetInput(window)
    win2image.Update()
    writer = vtk_format()
    if LooseVersion(vtk.vtkVersion().GetVTKVersion()) >= \
       LooseVersion('6.0.0'):
        writer.SetInputData(win2image.GetOutput())
    else:
        writer.SetInput(win2image.GetOutput())
    writer.SetFileName(output_filename)
    writer.Write()
    window.Finalize()
    if widget!=None:
        widget.close()
Ejemplo n.º 24
0
	def show(self):

		# Add to the cloud
		self.vtkPolyData.SetPoints(self.vtkPoints)
		self.vtkPolyData.SetVerts(self.vtkCells)

		self.vtkPolyData.GetPointData().SetVectors(self.vtkColor)

		self.vtkPolyData.Modified()
		self.vtkPolyData.Update()

		# Renderer
		mapper = vtk.vtkPolyDataMapper()
		mapper.SetInput(self.vtkPolyData)
		renderer = vtk.vtkRenderer()
		self.vtkActor.SetMapper(mapper)
		renderer.AddActor(self.vtkActor)
		renderer.SetBackground(.2, .3, .4)
		renderer.ResetCamera()
		#renderer.SetPosition([-3, 0, 11])

		# Render Window
		renderWindow = vtk.vtkRenderWindow()
		renderWindow.AddRenderer(renderer)

		# Interactor
		renderWindowInteractor = vtk.vtkRenderWindowInteractor()
		renderWindowInteractor.SetRenderWindow(renderWindow)

		# Begin Interaction
		renderWindow.Render()
		renderWindowInteractor.Start()
Ejemplo n.º 25
0
    def testUnstructured(self):
        rt = vtk.vtkRTAnalyticSource()
        rt.SetWholeExtent(-5, 5, -5, 5, -5, 5)

        t = vtk.vtkThreshold()
        t.SetInputConnection(rt.GetOutputPort())
        t.ThresholdByUpper(-10)

        s = vtk.vtkSphere()
        s.SetRadius(2)
        s.SetCenter(0,0,0)

        c = vtk.vtkTableBasedClipDataSet()
        c.SetInputConnection(t.GetOutputPort())
        c.SetClipFunction(s)
        c.SetInsideOut(1)

        c.Update()

        self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)

        eg = vtk.vtkEnSightGoldReader()
        eg.SetCaseFileName(VTK_DATA_ROOT + "/Data/EnSight/elements.case")
        eg.Update()

        pl = vtk.vtkPlane()
        pl.SetOrigin(3.5, 3.5, 0.5)
        pl.SetNormal(0, 0, 1)

        c.SetInputConnection(eg.GetOutputPort())
        c.SetClipFunction(pl)
        c.SetInsideOut(1)

        c.Update()
        data = c.GetOutputDataObject(0).GetBlock(0)
        self.assertEqual(data.GetNumberOfCells(), 75)

        rw = vtk.vtkRenderWindow()
        ren = vtk.vtkRenderer()
        rw.AddRenderer(ren)
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(data)
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        ren.AddActor(actor)
        ac = ren.GetActiveCamera()
        ac.SetPosition(-7.9, 9.7, 14.6)
        ac.SetFocalPoint(3.5, 3.5, 0.5)
        ac.SetViewUp(0.08, 0.93, -0.34)
        rw.Render()
        ren.ResetCameraClippingRange()

        rtTester = vtk.vtkTesting()
        for arg in sys.argv[1:]:
            rtTester.AddArgument(arg)
        rtTester.AddArgument("-V")
        rtTester.AddArgument("tableBasedClip.png")
        rtTester.SetRenderWindow(rw)
        rw.Render()
        rtResult = rtTester.RegressionTest(10)
Ejemplo n.º 26
0
    def createRenderWindow( self, **args ):
        blocking = args.get( 'blocking', False )
        renWin = args.get( 'renwin', None ) 
        if renWin == None:
            renWin = vtk.vtkRenderWindow()
            
        rendWinInteractor = renWin.GetInteractor()
        if rendWinInteractor == None:                
            rendWinInteractor = vtk.vtkRenderWindowInteractor() if blocking else vtk.vtkGenericRenderWindowInteractor()
            renWin.SetInteractor( rendWinInteractor )
            rendWinInteractor.SetRenderWindow(renWin)  
        
        self.renderWindowInteractor =  rendWinInteractor              
        self.renderer = vtk.vtkRenderer()
        renWin.AddRenderer( self.renderer )

        self.interactorStyle = vtk.vtkInteractorStyleTrackballCamera( )
        self.renderWindowInteractor.SetInteractorStyle( self.interactorStyle )
        self.interactorStyle.KeyPressActivationOff( )
        self.interactorStyle.SetEnabled(1)
                     
        if self.useDepthPeeling:
            self.renderer.UseDepthPeelingOn( )
            self.renderer.SetOcclusionRatio( 0.2 )       
            renWin.SetAlphaBitPlanes( 1 )
            renWin.SetMultiSamples( 0 )
            
        self.renderer.SetBackground(1.0, 1.0, 1.0)
        self.renderer.SetNearClippingPlaneTolerance( 0.0001 )    
        self.renderWindow = renWin
def Visualize_Orientation(model, out_file):
    # create coordinate actor
    axes_actor = vtk.vtkAxesActor()
    axes_actor.SetTotalLength(500.0, 500.0, 500.0)

    # create model actor
    model_mapper = vtk.vtkPolyDataMapper()
    model_mapper.SetInputData(model)
    model_actor = vtk.vtkActor()
    model_actor.SetMapper(model_mapper)

    global renderer
    global interactor

    renderer = vtk.vtkRenderer()
    renderer.AddActor(model_actor)
    renderer.AddActor(axes_actor)
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()

    interactor_style = QIN_Style()
    interactor_style.SetRenderer(renderer)
    interactor_style.SetActor(model_actor)
    interactor_style.SetPolyData(model)
    interactor_style.SetOutName(out_file)
    interactor.SetInteractorStyle(interactor_style)

    win.SetInteractor(interactor)
    win.Render()
    interactor.Start()
    pass
Ejemplo n.º 28
0
def initialize():

    # Create a rendering window and renderer
    transform = vtk.vtkTransform()
    transform.Scale(10.0, 10.0, 10.0)
     
    axes = vtk.vtkAxesActor()
    axes.SetUserTransform(transform)

    transform.Translate(3.0, -2.0, 0.0)
    axes.SetUserTransform(transform)

    ren = vtk.vtkRenderer()
    ren.AddActor(axes)
    ren.ResetCamera()

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

    # Create a RenderWindowInteractor to permit manipulating the camera
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()

    return ren, iren, renWin
Ejemplo n.º 29
0
def show_vtk_file(path):
	# open vtk file from arglist
	reader = vtk.vtkDataSetReader()
	reader.SetFileName(path)
	reader.Update()
	# read out data and scalarrange
	output = reader.GetOutput()
	scalarrange = output.GetScalarRange()
	# generate Mapper and set DataSource
	mapper = vtk.vtkDataSetMapper()
	mapper.SetInput(output)
	mapper.SetScalarRange(scalarrange)
	# create actor
	actor = vtk.vtkActor()
	actor.SetMapper(mapper)
	# build renderer
	renderer = vtk.vtkRenderer()
	window = vtk.vtkRenderWindow()
	window.AddRenderer(renderer)
	# create interaction
	interaction = vtk.vtkRenderWindowInteractor()
	interaction.SetRenderWindow(window)
	# add actor
	renderer.AddActor(actor)
	# show window and start inteaction and renderer
	interaction.Initialize()
	window.Render()
	interaction.Start()
Ejemplo n.º 30
0
def RenderVTKVolume(image, volprops):
    volmap = vtk.vtkVolumeRayCastMapper()
    volmap.SetVolumeRayCastFunction(vtk.vtkVolumeRayCastCompositeFunction())
    volmap.SetInputConnection(image.GetOutputPort())

    vol = vtk.vtkVolume()
    vol.SetMapper(volmap)
    vol.SetProperty(volprops)

    #Standard VTK stuff
    ren = vtk.vtkRenderer()
    ren.AddVolume(vol)
    ren.SetBackground((1, 1, 1))

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

    istyle = vtk.vtkInteractorStyleSwitch()
    istyle.SetCurrentStyleToTrackballCamera()

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    iren.SetInteractorStyle(istyle)

    renwin.Render()
    iren.Start()
Ejemplo n.º 31
0
def vis(dyns, save, cross):
    datdir = os.path.abspath(os.path.join(dyns[0], '../..'))
    stat = np.load('%s/static.npz' % datdir)
    l = stat['l']
    lu, ld = l / 2.0, l / 2.0
    R = stat['R']
    R_drop = stat['R_d']

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.AddRenderer(ren)
    if save:
        renWin.OffScreenRenderingOn()
        winImFilt = vtk.vtkWindowToImageFilter()
        winImFilt.SetInput(renWin)
        writer = vtk.vtkPNGWriter()
        writer.SetInputConnection(winImFilt.GetOutputPort())
    else:
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)
        iren.Initialize()

    timeActor = vtk.vtkTextActor()
    timeActor.SetInput('init')
    ren.AddActor(timeActor)

    env = vtk.vtkSphereSource()
    env.SetThetaResolution(30)
    env.SetPhiResolution(30)
    env.SetRadius(R_drop)

    # env = vtk.vtkRegularPolygonSource()
    # env.GeneratePolygonOff()
    # env.SetNumberOfSides(200)
    # x = 4.0
    # th = np.arcsin(x / R_drop)
    # env.SetRadius(R_drop * np.cos(th))
    # env_tube = vtk.vtkTubeFilter()
    # env_tube.SetInputConnection(env.GetOutputPort())
    # env_tube.SetRadius(0.5)
    # env.Update()

    envMapper = vtk.vtkPolyDataMapper()
    envMapper.SetInputConnection(env.GetOutputPort())
    envActor = vtk.vtkActor()
    envActor.SetMapper(envMapper)
    envActor.GetProperty().SetColor(1, 0, 0)
    envActor.GetProperty().SetRepresentationToWireframe()
    envActor.GetProperty().SetOpacity(0.5)
    ren.AddActor(envActor)

    particleCPoints = vtk.vtkPoints()
    particleCPolys = vtk.vtkPolyData()
    particleCPolys.SetPoints(particleCPoints)
    particlesC = vtk.vtkGlyph3D()
    lineSource = vtk.vtkLineSource()
    lineSource.SetPoint1(-ld, 0.0, 0.0)
    lineSource.SetPoint2(lu, 0.0, 0.0)
    particleCSource = vtk.vtkTubeFilter()
    particleCSource.SetInputConnection(lineSource.GetOutputPort())
    particleCSource.SetRadius(R)
    particleCSource.SetNumberOfSides(10)
    particlesC.SetSourceConnection(particleCSource.GetOutputPort())
    particlesC.SetInputData(particleCPolys)
    particlesCMapper = vtk.vtkPolyDataMapper()
    particlesCMapper.SetInputConnection(particlesC.GetOutputPort())
    particlesCActor = vtk.vtkActor()
    particlesCActor.SetMapper(particlesCMapper)
    particlesCActor.GetProperty().SetColor(0, 1, 0)
    ren.AddActor(particlesCActor)
    particleESource = vtk.vtkSphereSource()
    particleESource.SetRadius(0.95 * R)
    particleESource.SetThetaResolution(20)
    particleESource.SetPhiResolution(20)
    particleE1Points = vtk.vtkPoints()
    particleE1Polys = vtk.vtkPolyData()
    particleE1Polys.SetPoints(particleE1Points)
    particlesE1 = vtk.vtkGlyph3D()
    particlesE1.SetSourceConnection(particleESource.GetOutputPort())
    particlesE1.SetInputData(particleE1Polys)
    particlesE1Mapper = vtk.vtkPolyDataMapper()
    particlesE1Mapper.SetInputConnection(particlesE1.GetOutputPort())
    particlesE1Actor = vtk.vtkActor()
    particlesE1Actor.SetMapper(particlesE1Mapper)
    particlesE1Actor.GetProperty().SetColor(0, 1, 0)
    ren.AddActor(particlesE1Actor)
    particleE2Points = vtk.vtkPoints()
    particleE2Polys = vtk.vtkPolyData()
    particleE2Polys.SetPoints(particleE2Points)
    particlesE2 = vtk.vtkGlyph3D()
    particlesE2.SetSourceConnection(particleESource.GetOutputPort())
    particlesE2.SetInputData(particleE2Polys)
    particlesE2Mapper = vtk.vtkPolyDataMapper()
    particlesE2Mapper.SetInputConnection(particlesE2.GetOutputPort())
    particlesE2Actor = vtk.vtkActor()
    particlesE2Actor.SetMapper(particlesE2Mapper)
    particlesE2Actor.GetProperty().SetColor(0, 1, 0)
    ren.AddActor(particlesE2Actor)

    renWin.fnames = dyns
    renWin.index = 0
    renWin.l = l
    renWin.cross = cross
    renWin.timeActor = timeActor
    renWin.particleCPoints = particleCPoints
    renWin.particleCPolys = particleCPolys
    renWin.particleE1Points = particleE1Points
    renWin.particleE2Points = particleE2Points

    if not save:
        ren.GetActiveCamera().SetPosition(0.0, 0.0, -73.0)
        ren.GetActiveCamera().Zoom(1.0)

        iren.RemoveObservers('KeyPressEvent')
        iren.AddObserver('KeyPressEvent', progress_iren, 1.0)
        iren.Start()
    else:
        while True:
            fname = progress_renwin(renWin)
            print(fname)
            outname = os.path.splitext(os.path.basename(fname))[0]
            winImFilt.Modified()
            writer.SetFileName('{}.jpg'.format(outname))
            writer.Write()
import vtk

# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

style = vtk.vtkInteractorStyleTrackballActor()
iren.SetInteractorStyle(style)

# create source
sphereSource = vtk.vtkSphereSource()
sphereSource.Update()

# mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(sphereSource.GetOutput())

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

# assign actor to the renderer
ren.AddActor(actor)

# enable user interface interactor
iren.Initialize()
Ejemplo n.º 33
0
    def testCells(self):

        # Demonstrates all cell types
        #
        # NOTE: the use of NewInstance/DeepCopy is included to increase
        # regression coverage.  It is not required in most applications.

        ren = vtk.vtkRenderer()
        # turn off all cullers
        ren.GetCullers().RemoveAllItems()

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(300, 150)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        # create a scene with one of each cell type

        # Voxel

        voxelPoints = vtk.vtkPoints()
        voxelPoints.SetNumberOfPoints(8)
        voxelPoints.InsertPoint(0, 0, 0, 0)
        voxelPoints.InsertPoint(1, 1, 0, 0)
        voxelPoints.InsertPoint(2, 0, 1, 0)
        voxelPoints.InsertPoint(3, 1, 1, 0)
        voxelPoints.InsertPoint(4, 0, 0, 1)
        voxelPoints.InsertPoint(5, 1, 0, 1)
        voxelPoints.InsertPoint(6, 0, 1, 1)
        voxelPoints.InsertPoint(7, 1, 1, 1)

        aVoxel = vtk.vtkVoxel()
        aVoxel.GetPointIds().SetId(0, 0)
        aVoxel.GetPointIds().SetId(1, 1)
        aVoxel.GetPointIds().SetId(2, 2)
        aVoxel.GetPointIds().SetId(3, 3)
        aVoxel.GetPointIds().SetId(4, 4)
        aVoxel.GetPointIds().SetId(5, 5)
        aVoxel.GetPointIds().SetId(6, 6)
        aVoxel.GetPointIds().SetId(7, 7)

        bVoxel = aVoxel.NewInstance()
        bVoxel.DeepCopy(aVoxel)

        aVoxelGrid = vtk.vtkUnstructuredGrid()
        aVoxelGrid.Allocate(1, 1)
        aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds())
        aVoxelGrid.SetPoints(voxelPoints)

        aVoxelMapper = vtk.vtkDataSetMapper()
        aVoxelMapper.SetInputData(aVoxelGrid)

        aVoxelActor = vtk.vtkActor()
        aVoxelActor.SetMapper(aVoxelMapper)
        aVoxelActor.GetProperty().BackfaceCullingOn()

        # Hexahedron

        hexahedronPoints = vtk.vtkPoints()
        hexahedronPoints.SetNumberOfPoints(8)
        hexahedronPoints.InsertPoint(0, 0, 0, 0)
        hexahedronPoints.InsertPoint(1, 1, 0, 0)
        hexahedronPoints.InsertPoint(2, 1, 1, 0)
        hexahedronPoints.InsertPoint(3, 0, 1, 0)
        hexahedronPoints.InsertPoint(4, 0, 0, 1)
        hexahedronPoints.InsertPoint(5, 1, 0, 1)
        hexahedronPoints.InsertPoint(6, 1, 1, 1)
        hexahedronPoints.InsertPoint(7, 0, 1, 1)

        aHexahedron = vtk.vtkHexahedron()
        aHexahedron.GetPointIds().SetId(0, 0)
        aHexahedron.GetPointIds().SetId(1, 1)
        aHexahedron.GetPointIds().SetId(2, 2)
        aHexahedron.GetPointIds().SetId(3, 3)
        aHexahedron.GetPointIds().SetId(4, 4)
        aHexahedron.GetPointIds().SetId(5, 5)
        aHexahedron.GetPointIds().SetId(6, 6)
        aHexahedron.GetPointIds().SetId(7, 7)

        bHexahedron = aHexahedron.NewInstance()
        bHexahedron.DeepCopy(aHexahedron)

        aHexahedronGrid = vtk.vtkUnstructuredGrid()
        aHexahedronGrid.Allocate(1, 1)
        aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(),
                                       aHexahedron.GetPointIds())
        aHexahedronGrid.SetPoints(hexahedronPoints)

        aHexahedronMapper = vtk.vtkDataSetMapper()
        aHexahedronMapper.SetInputData(aHexahedronGrid)

        aHexahedronActor = vtk.vtkActor()
        aHexahedronActor.SetMapper(aHexahedronMapper)
        aHexahedronActor.AddPosition(2, 0, 0)
        aHexahedronActor.GetProperty().BackfaceCullingOn()

        # Tetra

        tetraPoints = vtk.vtkPoints()
        tetraPoints.SetNumberOfPoints(4)
        tetraPoints.InsertPoint(0, 0, 0, 0)
        tetraPoints.InsertPoint(1, 1, 0, 0)
        tetraPoints.InsertPoint(2, .5, 1, 0)
        tetraPoints.InsertPoint(3, .5, .5, 1)

        aTetra = vtk.vtkTetra()
        aTetra.GetPointIds().SetId(0, 0)
        aTetra.GetPointIds().SetId(1, 1)
        aTetra.GetPointIds().SetId(2, 2)
        aTetra.GetPointIds().SetId(3, 3)

        bTetra = aTetra.NewInstance()
        bTetra.DeepCopy(aTetra)

        aTetraGrid = vtk.vtkUnstructuredGrid()
        aTetraGrid.Allocate(1, 1)
        aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds())
        aTetraGrid.SetPoints(tetraPoints)

        aTetraCopy = vtk.vtkUnstructuredGrid()
        aTetraCopy.ShallowCopy(aTetraGrid)

        aTetraMapper = vtk.vtkDataSetMapper()
        aTetraMapper.SetInputData(aTetraCopy)

        aTetraActor = vtk.vtkActor()
        aTetraActor.SetMapper(aTetraMapper)
        aTetraActor.AddPosition(4, 0, 0)
        aTetraActor.GetProperty().BackfaceCullingOn()

        # Wedge

        wedgePoints = vtk.vtkPoints()
        wedgePoints.SetNumberOfPoints(6)
        wedgePoints.InsertPoint(0, 0, 1, 0)
        wedgePoints.InsertPoint(1, 0, 0, 0)
        wedgePoints.InsertPoint(2, 0, .5, .5)
        wedgePoints.InsertPoint(3, 1, 1, 0)
        wedgePoints.InsertPoint(4, 1, 0, 0)
        wedgePoints.InsertPoint(5, 1, .5, .5)

        aWedge = vtk.vtkWedge()
        aWedge.GetPointIds().SetId(0, 0)
        aWedge.GetPointIds().SetId(1, 1)
        aWedge.GetPointIds().SetId(2, 2)
        aWedge.GetPointIds().SetId(3, 3)
        aWedge.GetPointIds().SetId(4, 4)
        aWedge.GetPointIds().SetId(5, 5)

        bWedge = aWedge.NewInstance()
        bWedge.DeepCopy(aWedge)

        aWedgeGrid = vtk.vtkUnstructuredGrid()
        aWedgeGrid.Allocate(1, 1)
        aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds())
        aWedgeGrid.SetPoints(wedgePoints)

        aWedgeCopy = vtk.vtkUnstructuredGrid()
        aWedgeCopy.DeepCopy(aWedgeGrid)

        aWedgeMapper = vtk.vtkDataSetMapper()
        aWedgeMapper.SetInputData(aWedgeCopy)

        aWedgeActor = vtk.vtkActor()
        aWedgeActor.SetMapper(aWedgeMapper)
        aWedgeActor.AddPosition(6, 0, 0)
        aWedgeActor.GetProperty().BackfaceCullingOn()

        # Pyramid

        pyramidPoints = vtk.vtkPoints()
        pyramidPoints.SetNumberOfPoints(5)
        pyramidPoints.InsertPoint(0, 0, 0, 0)
        pyramidPoints.InsertPoint(1, 1, 0, 0)
        pyramidPoints.InsertPoint(2, 1, 1, 0)
        pyramidPoints.InsertPoint(3, 0, 1, 0)
        pyramidPoints.InsertPoint(4, .5, .5, 1)

        aPyramid = vtk.vtkPyramid()
        aPyramid.GetPointIds().SetId(0, 0)
        aPyramid.GetPointIds().SetId(1, 1)
        aPyramid.GetPointIds().SetId(2, 2)
        aPyramid.GetPointIds().SetId(3, 3)
        aPyramid.GetPointIds().SetId(4, 4)

        bPyramid = aPyramid.NewInstance()
        bPyramid.DeepCopy(aPyramid)

        aPyramidGrid = vtk.vtkUnstructuredGrid()
        aPyramidGrid.Allocate(1, 1)
        aPyramidGrid.InsertNextCell(aPyramid.GetCellType(),
                                    aPyramid.GetPointIds())
        aPyramidGrid.SetPoints(pyramidPoints)

        aPyramidMapper = vtk.vtkDataSetMapper()
        aPyramidMapper.SetInputData(aPyramidGrid)

        aPyramidActor = vtk.vtkActor()
        aPyramidActor.SetMapper(aPyramidMapper)
        aPyramidActor.AddPosition(8, 0, 0)
        aPyramidActor.GetProperty().BackfaceCullingOn()

        # Pixel

        pixelPoints = vtk.vtkPoints()
        pixelPoints.SetNumberOfPoints(4)
        pixelPoints.InsertPoint(0, 0, 0, 0)
        pixelPoints.InsertPoint(1, 1, 0, 0)
        pixelPoints.InsertPoint(2, 0, 1, 0)
        pixelPoints.InsertPoint(3, 1, 1, 0)

        aPixel = vtk.vtkPixel()
        aPixel.GetPointIds().SetId(0, 0)
        aPixel.GetPointIds().SetId(1, 1)
        aPixel.GetPointIds().SetId(2, 2)
        aPixel.GetPointIds().SetId(3, 3)

        bPixel = aPixel.NewInstance()
        bPixel.DeepCopy(aPixel)

        aPixelGrid = vtk.vtkUnstructuredGrid()
        aPixelGrid.Allocate(1, 1)
        aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds())
        aPixelGrid.SetPoints(pixelPoints)

        aPixelMapper = vtk.vtkDataSetMapper()
        aPixelMapper.SetInputData(aPixelGrid)

        aPixelActor = vtk.vtkActor()
        aPixelActor.SetMapper(aPixelMapper)
        aPixelActor.AddPosition(0, 0, 2)
        aPixelActor.GetProperty().BackfaceCullingOn()

        # Quad

        quadPoints = vtk.vtkPoints()
        quadPoints.SetNumberOfPoints(4)
        quadPoints.InsertPoint(0, 0, 0, 0)
        quadPoints.InsertPoint(1, 1, 0, 0)
        quadPoints.InsertPoint(2, 1, 1, 0)
        quadPoints.InsertPoint(3, 0, 1, 0)

        aQuad = vtk.vtkQuad()
        aQuad.GetPointIds().SetId(0, 0)
        aQuad.GetPointIds().SetId(1, 1)
        aQuad.GetPointIds().SetId(2, 2)
        aQuad.GetPointIds().SetId(3, 3)

        bQuad = aQuad.NewInstance()
        bQuad.DeepCopy(aQuad)

        aQuadGrid = vtk.vtkUnstructuredGrid()
        aQuadGrid.Allocate(1, 1)
        aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds())
        aQuadGrid.SetPoints(quadPoints)

        aQuadMapper = vtk.vtkDataSetMapper()
        aQuadMapper.SetInputData(aQuadGrid)

        aQuadActor = vtk.vtkActor()
        aQuadActor.SetMapper(aQuadMapper)
        aQuadActor.AddPosition(2, 0, 2)
        aQuadActor.GetProperty().BackfaceCullingOn()

        # Triangle

        trianglePoints = vtk.vtkPoints()
        trianglePoints.SetNumberOfPoints(3)
        trianglePoints.InsertPoint(0, 0, 0, 0)
        trianglePoints.InsertPoint(1, 1, 0, 0)
        trianglePoints.InsertPoint(2, .5, .5, 0)

        triangleTCoords = vtk.vtkFloatArray()
        triangleTCoords.SetNumberOfComponents(2)
        triangleTCoords.SetNumberOfTuples(3)
        triangleTCoords.InsertTuple2(0, 1, 1)
        triangleTCoords.InsertTuple2(1, 2, 2)
        triangleTCoords.InsertTuple2(2, 3, 3)

        aTriangle = vtk.vtkTriangle()
        aTriangle.GetPointIds().SetId(0, 0)
        aTriangle.GetPointIds().SetId(1, 1)
        aTriangle.GetPointIds().SetId(2, 2)

        bTriangle = aTriangle.NewInstance()
        bTriangle.DeepCopy(aTriangle)

        aTriangleGrid = vtk.vtkUnstructuredGrid()
        aTriangleGrid.Allocate(1, 1)
        aTriangleGrid.InsertNextCell(aTriangle.GetCellType(),
                                     aTriangle.GetPointIds())
        aTriangleGrid.SetPoints(trianglePoints)
        aTriangleGrid.GetPointData().SetTCoords(triangleTCoords)

        aTriangleMapper = vtk.vtkDataSetMapper()
        aTriangleMapper.SetInputData(aTriangleGrid)

        aTriangleActor = vtk.vtkActor()
        aTriangleActor.SetMapper(aTriangleMapper)
        aTriangleActor.AddPosition(4, 0, 2)
        aTriangleActor.GetProperty().BackfaceCullingOn()

        # Polygon

        polygonPoints = vtk.vtkPoints()
        polygonPoints.SetNumberOfPoints(4)
        polygonPoints.InsertPoint(0, 0, 0, 0)
        polygonPoints.InsertPoint(1, 1, 0, 0)
        polygonPoints.InsertPoint(2, 1, 1, 0)
        polygonPoints.InsertPoint(3, 0, 1, 0)

        aPolygon = vtk.vtkPolygon()
        aPolygon.GetPointIds().SetNumberOfIds(4)
        aPolygon.GetPointIds().SetId(0, 0)
        aPolygon.GetPointIds().SetId(1, 1)
        aPolygon.GetPointIds().SetId(2, 2)
        aPolygon.GetPointIds().SetId(3, 3)

        bPolygon = aPolygon.NewInstance()
        bPolygon.DeepCopy(aPolygon)

        aPolygonGrid = vtk.vtkUnstructuredGrid()
        aPolygonGrid.Allocate(1, 1)
        aPolygonGrid.InsertNextCell(aPolygon.GetCellType(),
                                    aPolygon.GetPointIds())
        aPolygonGrid.SetPoints(polygonPoints)

        aPolygonMapper = vtk.vtkDataSetMapper()
        aPolygonMapper.SetInputData(aPolygonGrid)

        aPolygonActor = vtk.vtkActor()
        aPolygonActor.SetMapper(aPolygonMapper)
        aPolygonActor.AddPosition(6, 0, 2)
        aPolygonActor.GetProperty().BackfaceCullingOn()

        # Triangle Strip

        triangleStripPoints = vtk.vtkPoints()
        triangleStripPoints.SetNumberOfPoints(5)
        triangleStripPoints.InsertPoint(0, 0, 1, 0)
        triangleStripPoints.InsertPoint(1, 0, 0, 0)
        triangleStripPoints.InsertPoint(2, 1, 1, 0)
        triangleStripPoints.InsertPoint(3, 1, 0, 0)
        triangleStripPoints.InsertPoint(4, 2, 1, 0)

        triangleStripTCoords = vtk.vtkFloatArray()
        triangleStripTCoords.SetNumberOfComponents(2)
        triangleStripTCoords.SetNumberOfTuples(3)
        triangleStripTCoords.InsertTuple2(0, 1, 1)
        triangleStripTCoords.InsertTuple2(1, 2, 2)
        triangleStripTCoords.InsertTuple2(2, 3, 3)
        triangleStripTCoords.InsertTuple2(3, 4, 4)
        triangleStripTCoords.InsertTuple2(4, 5, 5)

        aTriangleStrip = vtk.vtkTriangleStrip()
        aTriangleStrip.GetPointIds().SetNumberOfIds(5)
        aTriangleStrip.GetPointIds().SetId(0, 0)
        aTriangleStrip.GetPointIds().SetId(1, 1)
        aTriangleStrip.GetPointIds().SetId(2, 2)
        aTriangleStrip.GetPointIds().SetId(3, 3)
        aTriangleStrip.GetPointIds().SetId(4, 4)

        bTriangleStrip = aTriangleStrip.NewInstance()
        bTriangleStrip.DeepCopy(aTriangleStrip)

        aTriangleStripGrid = vtk.vtkUnstructuredGrid()
        aTriangleStripGrid.Allocate(1, 1)
        aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(),
                                          aTriangleStrip.GetPointIds())
        aTriangleStripGrid.SetPoints(triangleStripPoints)
        aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords)

        aTriangleStripMapper = vtk.vtkDataSetMapper()
        aTriangleStripMapper.SetInputData(aTriangleStripGrid)

        aTriangleStripActor = vtk.vtkActor()
        aTriangleStripActor.SetMapper(aTriangleStripMapper)
        aTriangleStripActor.AddPosition(8, 0, 2)
        aTriangleStripActor.GetProperty().BackfaceCullingOn()

        # Line

        linePoints = vtk.vtkPoints()
        linePoints.SetNumberOfPoints(2)
        linePoints.InsertPoint(0, 0, 0, 0)
        linePoints.InsertPoint(1, 1, 1, 0)

        aLine = vtk.vtkLine()
        aLine.GetPointIds().SetId(0, 0)
        aLine.GetPointIds().SetId(1, 1)

        bLine = aLine.NewInstance()
        bLine.DeepCopy(aLine)

        aLineGrid = vtk.vtkUnstructuredGrid()
        aLineGrid.Allocate(1, 1)
        aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
        aLineGrid.SetPoints(linePoints)

        aLineMapper = vtk.vtkDataSetMapper()
        aLineMapper.SetInputData(aLineGrid)

        aLineActor = vtk.vtkActor()
        aLineActor.SetMapper(aLineMapper)
        aLineActor.AddPosition(0, 0, 4)
        aLineActor.GetProperty().BackfaceCullingOn()

        # Poly line

        polyLinePoints = vtk.vtkPoints()
        polyLinePoints.SetNumberOfPoints(3)
        polyLinePoints.InsertPoint(0, 0, 0, 0)
        polyLinePoints.InsertPoint(1, 1, 1, 0)
        polyLinePoints.InsertPoint(2, 1, 0, 0)

        aPolyLine = vtk.vtkPolyLine()
        aPolyLine.GetPointIds().SetNumberOfIds(3)
        aPolyLine.GetPointIds().SetId(0, 0)
        aPolyLine.GetPointIds().SetId(1, 1)
        aPolyLine.GetPointIds().SetId(2, 2)

        bPolyLine = aPolyLine.NewInstance()
        bPolyLine.DeepCopy(aPolyLine)

        aPolyLineGrid = vtk.vtkUnstructuredGrid()
        aPolyLineGrid.Allocate(1, 1)
        aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(),
                                     aPolyLine.GetPointIds())
        aPolyLineGrid.SetPoints(polyLinePoints)

        aPolyLineMapper = vtk.vtkDataSetMapper()
        aPolyLineMapper.SetInputData(aPolyLineGrid)

        aPolyLineActor = vtk.vtkActor()
        aPolyLineActor.SetMapper(aPolyLineMapper)
        aPolyLineActor.AddPosition(2, 0, 4)
        aPolyLineActor.GetProperty().BackfaceCullingOn()

        # Vertex

        vertexPoints = vtk.vtkPoints()
        vertexPoints.SetNumberOfPoints(1)
        vertexPoints.InsertPoint(0, 0, 0, 0)

        aVertex = vtk.vtkVertex()
        aVertex.GetPointIds().SetId(0, 0)

        bVertex = aVertex.NewInstance()
        bVertex.DeepCopy(aVertex)

        aVertexGrid = vtk.vtkUnstructuredGrid()
        aVertexGrid.Allocate(1, 1)
        aVertexGrid.InsertNextCell(aVertex.GetCellType(),
                                   aVertex.GetPointIds())
        aVertexGrid.SetPoints(vertexPoints)

        aVertexMapper = vtk.vtkDataSetMapper()
        aVertexMapper.SetInputData(aVertexGrid)

        aVertexActor = vtk.vtkActor()
        aVertexActor.SetMapper(aVertexMapper)
        aVertexActor.AddPosition(0, 0, 6)
        aVertexActor.GetProperty().BackfaceCullingOn()

        # Poly Vertex

        polyVertexPoints = vtk.vtkPoints()
        polyVertexPoints.SetNumberOfPoints(3)
        polyVertexPoints.InsertPoint(0, 0, 0, 0)
        polyVertexPoints.InsertPoint(1, 1, 0, 0)
        polyVertexPoints.InsertPoint(2, 1, 1, 0)

        aPolyVertex = vtk.vtkPolyVertex()
        aPolyVertex.GetPointIds().SetNumberOfIds(3)
        aPolyVertex.GetPointIds().SetId(0, 0)
        aPolyVertex.GetPointIds().SetId(1, 1)
        aPolyVertex.GetPointIds().SetId(2, 2)

        bPolyVertex = aPolyVertex.NewInstance()
        bPolyVertex.DeepCopy(aPolyVertex)

        aPolyVertexGrid = vtk.vtkUnstructuredGrid()
        aPolyVertexGrid.Allocate(1, 1)
        aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(),
                                       aPolyVertex.GetPointIds())
        aPolyVertexGrid.SetPoints(polyVertexPoints)

        aPolyVertexMapper = vtk.vtkDataSetMapper()
        aPolyVertexMapper.SetInputData(aPolyVertexGrid)

        aPolyVertexActor = vtk.vtkActor()
        aPolyVertexActor.SetMapper(aPolyVertexMapper)
        aPolyVertexActor.AddPosition(2, 0, 6)
        aPolyVertexActor.GetProperty().BackfaceCullingOn()

        # Pentagonal prism

        pentaPoints = vtk.vtkPoints()
        pentaPoints.SetNumberOfPoints(10)
        pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0)
        pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0)
        pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0)
        pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0)
        pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0)
        pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0)
        pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0)
        pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0)
        pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0)

        aPenta = vtk.vtkPentagonalPrism()
        aPenta.GetPointIds().SetId(0, 0)
        aPenta.GetPointIds().SetId(1, 1)
        aPenta.GetPointIds().SetId(2, 2)
        aPenta.GetPointIds().SetId(3, 3)
        aPenta.GetPointIds().SetId(4, 4)
        aPenta.GetPointIds().SetId(5, 5)
        aPenta.GetPointIds().SetId(6, 6)
        aPenta.GetPointIds().SetId(7, 7)
        aPenta.GetPointIds().SetId(8, 8)
        aPenta.GetPointIds().SetId(9, 9)

        bPenta = aPenta.NewInstance()
        bPenta.DeepCopy(aPenta)

        aPentaGrid = vtk.vtkUnstructuredGrid()
        aPentaGrid.Allocate(1, 1)
        aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds())
        aPentaGrid.SetPoints(pentaPoints)

        aPentaCopy = vtk.vtkUnstructuredGrid()
        aPentaCopy.DeepCopy(aPentaGrid)

        aPentaMapper = vtk.vtkDataSetMapper()
        aPentaMapper.SetInputData(aPentaCopy)

        aPentaActor = vtk.vtkActor()
        aPentaActor.SetMapper(aPentaMapper)
        aPentaActor.AddPosition(10, 0, 0)
        aPentaActor.GetProperty().BackfaceCullingOn()

        # Hexagonal prism

        hexaPoints = vtk.vtkPoints()
        hexaPoints.SetNumberOfPoints(12)
        hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0)
        hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0)
        hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0)
        hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0)
        hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0)
        hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0)
        hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0)
        hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0)
        hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0)
        hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0)
        hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0)

        aHexa = vtk.vtkHexagonalPrism()
        aHexa.GetPointIds().SetId(0, 0)
        aHexa.GetPointIds().SetId(1, 1)
        aHexa.GetPointIds().SetId(2, 2)
        aHexa.GetPointIds().SetId(3, 3)
        aHexa.GetPointIds().SetId(4, 4)
        aHexa.GetPointIds().SetId(5, 5)
        aHexa.GetPointIds().SetId(6, 6)
        aHexa.GetPointIds().SetId(7, 7)
        aHexa.GetPointIds().SetId(8, 8)
        aHexa.GetPointIds().SetId(9, 9)
        aHexa.GetPointIds().SetId(10, 10)
        aHexa.GetPointIds().SetId(11, 11)

        bHexa = aHexa.NewInstance()
        bHexa.DeepCopy(aHexa)

        aHexaGrid = vtk.vtkUnstructuredGrid()
        aHexaGrid.Allocate(1, 1)
        aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds())
        aHexaGrid.SetPoints(hexaPoints)

        aHexaCopy = vtk.vtkUnstructuredGrid()
        aHexaCopy.DeepCopy(aHexaGrid)

        aHexaMapper = vtk.vtkDataSetMapper()
        aHexaMapper.SetInputData(aHexaCopy)

        aHexaActor = vtk.vtkActor()
        aHexaActor.SetMapper(aHexaMapper)
        aHexaActor.AddPosition(12, 0, 0)
        aHexaActor.GetProperty().BackfaceCullingOn()

        # RIB property
        if hasattr(vtk, 'vtkRIBProperty'):
            aRIBProperty = vtk.vtkRIBProperty()
            aRIBProperty.SetVariable("Km", "float")
            aRIBProperty.SetSurfaceShader("LGVeinedmarble")
            aRIBProperty.SetVariable("veinfreq", "float")
            aRIBProperty.AddVariable("warpfreq", "float")
            aRIBProperty.AddVariable("veincolor", "color")
            aRIBProperty.AddSurfaceShaderParameter("veinfreq", " 2")
            aRIBProperty.AddSurfaceShaderParameter("veincolor",
                                                   "1.0000 1.0000 0.9412")
            bRIBProperty = vtk.vtkRIBProperty()
            bRIBProperty.SetVariable("Km", "float")
            bRIBProperty.SetSurfaceShaderParameter("Km", "1.0")
            bRIBProperty.SetDisplacementShader("dented")
            bRIBProperty.SetSurfaceShader("plastic")
        aProperty = vtk.vtkProperty()
        bProperty = vtk.vtkProperty()

        aTriangleActor.SetProperty(aProperty)
        aTriangleStripActor.SetProperty(bProperty)

        ren.SetBackground(.1, .2, .4)

        ren.AddActor(aVoxelActor)
        aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0)
        ren.AddActor(aHexahedronActor)
        aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0)
        ren.AddActor(aTetraActor)
        aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0)
        ren.AddActor(aWedgeActor)
        aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aPyramidActor)
        aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aPixelActor)
        aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aQuadActor)
        aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aTriangleActor)
        aTriangleActor.GetProperty().SetDiffuseColor(.3, 1, .5)
        ren.AddActor(aPolygonActor)
        aPolygonActor.GetProperty().SetDiffuseColor(1, .4, .5)
        ren.AddActor(aTriangleStripActor)
        aTriangleStripActor.GetProperty().SetDiffuseColor(.3, .7, 1)
        ren.AddActor(aLineActor)
        aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1)
        ren.AddActor(aPolyLineActor)
        aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aVertexActor)
        aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPolyVertexActor)
        aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPentaActor)
        aPentaActor.GetProperty().SetDiffuseColor(.2, .4, .7)
        ren.AddActor(aHexaActor)
        aHexaActor.GetProperty().SetDiffuseColor(.7, .5, 1)

        aRIBLight = vtk.vtkRIBLight()
        aRIBLight.SetIntensity(0.7)

        ren.AddLight(aRIBLight)
        aLight = vtk.vtkLight()

        aLight.PositionalOn()
        aLight.SetConeAngle(10.0)
        aLight.SetIntensity(0.7)
        ren.AddLight(aLight)

        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Dolly(2.8)
        ren.ResetCameraClippingRange()

        dir = VTK_TEMP_DIR

        atext = vtk.vtkTexture()
        pnmReader = vtk.vtkBMPReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOff()
        aTriangleActor.SetTexture(atext)

        aRIBLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint())
        aRIBLight.SetPosition(ren.GetActiveCamera().GetPosition())
        aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint())
        aLight.SetPosition(ren.GetActiveCamera().GetPosition())

        # basically have IO/Export ?
        if hasattr(vtk, 'vtkRIBExporter'):
            rib = vtk.vtkRIBExporter()
            rib.SetInput(renWin)
            rib.SetFilePrefix(dir + '/cells')
            rib.SetTexturePrefix(dir + '/cells')
            rib.Write()

            iv = vtk.vtkIVExporter()
            iv.SetInput(renWin)
            iv.SetFileName(dir + "/cells.iv")
            iv.Write()
            os.remove(dir + '/cells.iv')

            obj = vtk.vtkOBJExporter()
            obj.SetInput(renWin)
            obj.SetFilePrefix(dir + "/cells")
            obj.Write()
            os.remove(dir + '/cells.obj')
            os.remove(dir + '/cells.mtl')

            vrml = vtk.vtkVRMLExporter()
            vrml.SetInput(renWin)
            #vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl"))
            #vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl"))
            vrml.SetFileName(dir + "/cells.wrl")
            vrml.SetSpeed(5.5)
            vrml.Write()
            os.remove(dir + '/cells.wrl')

            oogl = vtk.vtkOOGLExporter()
            oogl.SetInput(renWin)
            oogl.SetFileName(dir + "/cells.oogl")
            oogl.Write()
            os.remove(dir + '/cells.oogl')

        # the UnRegister calls are because make object is the same as New,
        # and causes memory leaks. (Python does not treat NewInstance the same as New).
        def DeleteCopies():
            bVoxel.UnRegister(None)
            bHexahedron.UnRegister(None)
            bTetra.UnRegister(None)
            bWedge.UnRegister(None)
            bPyramid.UnRegister(None)
            bPixel.UnRegister(None)
            bQuad.UnRegister(None)
            bTriangle.UnRegister(None)
            bPolygon.UnRegister(None)
            bTriangleStrip.UnRegister(None)
            bLine.UnRegister(None)
            bPolyLine.UnRegister(None)
            bVertex.UnRegister(None)
            bPolyVertex.UnRegister(None)
            bPenta.UnRegister(None)
            bHexa.UnRegister(None)

        DeleteCopies()

        # render and interact with data

        renWin.Render()

        img_file = "cells.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file))
        vtk.test.Testing.interact()
Ejemplo n.º 34
0
def create3D():

    points = []

    ilgis = 0
    for x in range(COUNT):
        ilgis, points = GetForma(ilgis, points)

    points.append([0, ilgis])
    points.append([0, 0])
    points.append([R / 2.0, 0])
    rodData = "translate([0," + str(R / 4.0) + "," + str(
        R / 4.0
    ) + "])rotate ([-90,0,0])  rotate_extrude($fn=200) polygon( points=" + str(
        points) + " );\n"
    rod = open("rod.scad", "w")
    rod.write(rodData)
    rod.close()
    call(["openscad", "-o", "rod.stl", "rod.scad"])
    read = vtk.vtkSTLReader()
    read.SetFileName("rod.stl")
    read.Update()
    tran = vtk.vtkTransform()
    bounds = read.GetOutput().GetBounds()
    tran.Translate(
        -read.GetOutput().GetBounds()[0] - (bounds[1] - bounds[0]) / 2.0,
        -read.GetOutput().GetBounds()[2] - (bounds[3] - bounds[2]) / 2.0,
        -read.GetOutput().GetBounds()[4] - (bounds[5] - bounds[4]) / 2.0)
    tfilter = vtk.vtkTransformFilter()
    tfilter.SetInputData(read.GetOutput())
    tfilter.SetTransform(tran)
    tfilter.Update()

    w = vtk.vtkSTLWriter()
    w.SetFileName("rod.stl")
    w.SetInputData(tfilter.GetOutput())
    w.Update()

    plane1 = vtk.vtkPlane()
    plane1.SetNormal(1, 0, 0)
    plane1.SetOrigin(0, 0, 0)
    plane2 = vtk.vtkPlane()
    plane2.SetNormal(0, 0, 1)
    plane2.SetOrigin(0, 0, 0)

    coll = vtk.vtkPlaneCollection()
    coll.AddItem(plane1)
    coll.AddItem(plane2)

    clip1 = vtk.vtkClipClosedSurface()
    clip1.SetClippingPlanes(coll)
    clip1.GenerateFacesOn()
    clip1.SetInputConnection(tfilter.GetOutputPort())
    clip1.Update()
    beton = vtk.vtkCubeSource()
    beton.SetBounds(-boxSize, boxSize, -ilgis / 2.0, ilgis / 2.0, -boxSize,
                    boxSize)
    beton.Update()
    clip2 = vtk.vtkClipClosedSurface()
    clip2.SetClippingPlanes(coll)
    clip2.GenerateFacesOn()
    clip2.SetInputConnection(beton.GetOutputPort())
    clip2.Update()

    box = vtk.vtkCubeSource()
    b = clip2.GetOutput().GetBounds()
    bbbb = clip1.GetOutput().GetBounds()
    box.SetBounds(b[0], b[1],
                  bbbb[2] - (bbbb[3] - bbbb[2]) * CalcBoxSizeProc / 1000.0,
                  bbbb[3] + (bbbb[3] - bbbb[2]) * CalcBoxSizeProc / 1000.0,
                  b[4], b[5])
    box.Update()
    SaveToSTL(box.GetOutput(), "box.stl")
    SaveToSTL(clip2.GetOutput(), "beton.stl")
    SaveToSTL(clip1.GetOutput(), "rod.stl")

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(clip1.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    ren.AddActor(actor)
    mapper1 = vtk.vtkPolyDataMapper()
    mapper1.SetInputConnection(clip2.GetOutputPort())
    actor1 = vtk.vtkActor()
    actor1.SetMapper(mapper1)
    ren.AddActor(actor1)
Ejemplo n.º 35
0
def main():
    count = 1
    dirname = None
    opacityWindow = 4096.0
    opacityLevel = 2048.0
    blendType = 0
    clip = 0
    reductionFactor = 1.0
    frameRate = 10.0
    fileName = None
    fileType = 0

    independentComponents = True

    while (count < len(sys.argv)):
        if (sys.argv[count] == "?"):
            PrintUsage()
            sys.exit(0)
        elif (sys.argv[count] == "-DICOM"):
            dirname = sys.argv[count + 1]
            count += 2
        elif (sys.argv[count] == "-VTI"):
            fileType = VTI_FILETYPE
            fileName = sys.argv[count + 1]
            count += 2
        elif (sys.argv[count] == "-MHA"):
            fileType = MHA_FILETYPE
            fileName = sys.argv[count + 1]
            count += 2
        elif (sys.argv[count] == "-Clip"):
            clip = 1
            count += 1
        elif (sys.argv[count] == "-MIP"):
            opacityWindow = float(sys.argv[count + 1])
            opacityLevel = float(sys.argv[count + 2])
            blendType = 0
            count += 3
        elif (sys.argv[count] == "-CompositeRamp"):
            opacityWindow = float(sys.argv[count + 1])
            opacityLevel = float(sys.argv[count + 2])
            blendType = 1
            count += 3
        elif (sys.argv[count] == "-CompositeShadeRamp"):
            opacityWindow = float(sys.argv[count + 1])
            opacityLevel = float(sys.argv[count + 2])
            blendType = 2
            count += 3
        elif (sys.argv[count] == "-CT_Skin"):
            blendType = 3
            count += 1
        elif (sys.argv[count] == "-CT_Bone"):
            blendType = 4
            count += 1
        elif (sys.argv[count] == "-CT_Muscle"):
            blendType = 5
            count += 1
        elif (sys.argv[count] == "-RGB_Composite"):
            blendType = 6
            count += 1
        elif (sys.argv[count] == "-FrameRate"):
            frameRate = float(sys.argv[count + 1])
            if (frameRate < 0.01 or frameRate > 60.0):
                print(
                    "Invalid frame rate - use a number between 0.01 and 60.0")
                print("Using default frame rate of 10 frames per second.")
                frameRate = 10.0
            count += 2
        elif (sys.argv[count] == "-ReductionFactor"):
            reductionFactor = float(sys.argv[count + 1])
            if (reductionFactor <= 0.0 or reductionFactor >= 1.0):
                print(
                    "Invalid reduction factor - use a number between 0 and 1 (exclusive)"
                )
                print("Using the default of no reduction.")
                reductionFactor = 1.0
            count += 2
        elif (sys.argv[count] == "-DependentComponents"):
            independentComponents = false
            count += 1
        else:
            print("Unrecognized option: %s\n" % (sys.argv[count]))
            PrintUsage()
            sys.exit(-1)
    if (dirname is None and fileName is None):
        print(
            "Error: you must specify a directory of DICOM data or a .vti file or a .mha!"
        )
        PrintUsage()
        sys.exit(-1)

    # Create the renderer, render window and interactor
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

    # Connect it all. Note that funny arithematic on the
    # SetDesiredUpdateRate - the vtkRenderWindow divides it
    # allocated time across all renderers, and the renderer
    # divides it time across all props. If clip is
    # true then there are two props
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetDesiredUpdateRate(frameRate / (1.0 + clip))

    iren.GetInteractorStyle().SetDefaultRenderer(renderer)

    # Read the data
    reader = None
    _input = None
    if (dirname):
        dicomReader = vtk.vtkDICOMImageReader()
        dicomReader.SetDirectoryName(dirname)
        dicomReader.Update()
        _input = dicomReader.GetOutput()
        reader = dicomReader
    elif (fileType == VTI_FILETYPE):
        xmlReader = vtk.vtkXMLImageDataReader()
        xmlReader.SetFileName(fileName)
        xmlReader.Update()
        _input = xmlReader.GetOutput()
        reader = xmlReader
    elif (fileType == MHA_FILETYPE):
        metaReader = vtk.vtkMetaImageReader()
        metaReader.SetFileName(fileName)
        metaReader.Update()
        _input = metaReader.GetOutput()
        reader = metaReader
    else:
        print("Error! Not VTI or MHA!")
        exit(-1)

    # Verify that we actually have a volume
    dim = _input.GetDimensions()
    if (dim[0] < 2 or dim[1] < 2 or dim[2] < 2):
        print("Error loading data!")
        sys.exit(-1)

    resample = vtk.vtkImageResample()
    if (reductionFactor < 1.0):
        resample.SetInputConnection(reader.GetOutputPort())
        resample.SetAxisMagnificationFactor(0, reductionFactor)
        resample.SetAxisMagnificationFactor(1, reductionFactor)
        resample.SetAxisMagnificationFactor(2, reductionFactor)

    # Create our volume and mapper
    volume = vtk.vtkVolume()
    mapper = vtk.vtkSmartVolumeMapper()

    # Add a box widget if the clip option was selected
    box = vtk.vtkBoxWidget()
    if (clip):
        box.SetInteractor(iren)
        box.SetPlaceFactor(1.01)
        if (reductionFactor < 1.0):
            box.SetInputConnection(resample.GetOutputPort())
        else:
            box.SetInputData(_input)

        box.SetDefaultRenderer(renderer)
        box.InsideOutOn()
        box.PlaceWidget()
        callback = vtkBoxWidgetCallback()
        callback.SetMapper(mapper)
        box.AddObserver(vtk.vtkCommand.InteractionEvent, callback.onExecute)
        box.EnabledOn()
        box.GetSelectedFaceProperty().SetOpacity(0.0)

    if (reductionFactor < 1.0):
        mapper.SetInputConnection(resample.GetOutputPort())
    else:
        mapper.SetInputConnection(reader.GetOutputPort())

    # Set the sample distance on the ray to be 1/2 the average spacing
    spacing = None
    if (reductionFactor < 1.0):
        spacing = resample.GetOutput().GetSpacing()
    else:
        spacing = _input.GetSpacing()

    #  mapper.SetSampleDistance( (spacing[0]+spacing[1]+spacing[2])/6.0 )
    #  mapper.SetMaximumImageSampleDistance(10.0)

    # Create our transfer function
    colorFun = vtk.vtkColorTransferFunction()
    opacityFun = vtk.vtkPiecewiseFunction()

    # Create the property and attach the transfer functions
    _property = vtk.vtkVolumeProperty()
    _property.SetIndependentComponents(independentComponents)
    _property.SetColor(colorFun)
    _property.SetScalarOpacity(opacityFun)
    _property.SetInterpolationTypeToLinear()

    # connect up the volume to the property and the mapper
    volume.SetProperty(_property)
    volume.SetMapper(mapper)

    # Depending on the blend type selected as a command line option,
    # adjust the transfer function
    if (blendType == 0):
        # MIP
        # Create an opacity ramp from the window and level values.
        # Color is white. Blending is MIP.
        colorFun.AddRGBSegment(0.0, 1.0, 1.0, 1.0, 255.0, 1.0, 1.0, 1.0)
        opacityFun.AddSegment(opacityLevel - 0.5 * opacityWindow, 0.0,
                              opacityLevel + 0.5 * opacityWindow, 1.0)
        mapper.SetBlendModeToMaximumIntensity()
    elif blendType == 1:
        # CompositeRamp
        # Create a ramp from the window and level values. Use compositing
        # without shading. Color is a ramp from black to white.
        colorFun.AddRGBSegment(opacityLevel - 0.5 * opacityWindow, 0.0, 0.0,
                               0.0, opacityLevel + 0.5 * opacityWindow, 1.0,
                               1.0, 1.0)
        opacityFun.AddSegment(opacityLevel - 0.5 * opacityWindow, 0.0,
                              opacityLevel + 0.5 * opacityWindow, 1.0)
        mapper.SetBlendModeToComposite()
        _property.ShadeOff()
    elif blendType == 2:
        # CompositeShadeRamp
        # Create a ramp from the window and level values. Use compositing
        # with shading. Color is white.
        colorFun.AddRGBSegment(0.0, 1.0, 1.0, 1.0, 255.0, 1.0, 1.0, 1.0)
        opacityFun.AddSegment(opacityLevel - 0.5 * opacityWindow, 0.0,
                              opacityLevel + 0.5 * opacityWindow, 1.0)
        mapper.SetBlendModeToComposite()
        _property.ShadeOn()

    elif blendType == 3:
        # CT_Skin
        # Use compositing and functions set to highlight skin in CT data
        # Not for use on RGB data
        colorFun.AddRGBPoint(-3024, 0, 0, 0, 0.5, 0.0)
        colorFun.AddRGBPoint(-1000, .62, .36, .18, 0.5, 0.0)
        colorFun.AddRGBPoint(-500, .88, .60, .29, 0.33, 0.45)
        colorFun.AddRGBPoint(3071, .83, .66, 1, 0.5, 0.0)

        opacityFun.AddPoint(-3024, 0, 0.5, 0.0)
        opacityFun.AddPoint(-1000, 0, 0.5, 0.0)
        opacityFun.AddPoint(-500, 1.0, 0.33, 0.45)
        opacityFun.AddPoint(3071, 1.0, 0.5, 0.0)

        mapper.SetBlendModeToComposite()
        _property.ShadeOn()
        _property.SetAmbient(0.1)
        _property.SetDiffuse(0.9)
        _property.SetSpecular(0.2)
        _property.SetSpecularPower(10.0)
        _property.SetScalarOpacityUnitDistance(0.8919)

    elif blendType == 4:
        # CT_Bone
        # Use compositing and functions set to highlight bone in CT data
        # Not for use on RGB data
        colorFun.AddRGBPoint(-3024, 0, 0, 0, 0.5, 0.0)
        colorFun.AddRGBPoint(-16, 0.73, 0.25, 0.30, 0.49, .61)
        colorFun.AddRGBPoint(641, .90, .82, .56, .5, 0.0)
        colorFun.AddRGBPoint(3071, 1, 1, 1, .5, 0.0)

        opacityFun.AddPoint(-3024, 0, 0.5, 0.0)
        opacityFun.AddPoint(-16, 0, .49, .61)
        opacityFun.AddPoint(641, .72, .5, 0.0)
        opacityFun.AddPoint(3071, .71, 0.5, 0.0)

        mapper.SetBlendModeToComposite()
        _property.ShadeOn()
        _property.SetAmbient(0.1)
        _property.SetDiffuse(0.9)
        _property.SetSpecular(0.2)
        _property.SetSpecularPower(10.0)
        _property.SetScalarOpacityUnitDistance(0.8919)

    elif blendType == 5:
        # CT_Muscle
        # Use compositing and functions set to highlight muscle in CT data
        # Not for use on RGB data
        colorFun.AddRGBPoint(-3024, 0, 0, 0, 0.5, 0.0)
        colorFun.AddRGBPoint(-155, .55, .25, .15, 0.5, .92)
        colorFun.AddRGBPoint(217, .88, .60, .29, 0.33, 0.45)
        colorFun.AddRGBPoint(420, 1, .94, .95, 0.5, 0.0)
        colorFun.AddRGBPoint(3071, .83, .66, 1, 0.5, 0.0)

        opacityFun.AddPoint(-3024, 0, 0.5, 0.0)
        opacityFun.AddPoint(-155, 0, 0.5, 0.92)
        opacityFun.AddPoint(217, .68, 0.33, 0.45)
        opacityFun.AddPoint(420, .83, 0.5, 0.0)
        opacityFun.AddPoint(3071, .80, 0.5, 0.0)

        mapper.SetBlendModeToComposite()
        _property.ShadeOn()
        _property.SetAmbient(0.1)
        _property.SetDiffuse(0.9)
        _property.SetSpecular(0.2)
        _property.SetSpecularPower(10.0)
        _property.SetScalarOpacityUnitDistance(0.8919)
    elif blendType == 6:
        # RGB_Composite
        # Use compositing and functions set to highlight red/green/blue regions
        # in RGB data. Not for use on single component data
        opacityFun.AddPoint(0, 0.0)
        opacityFun.AddPoint(5.0, 0.0)
        opacityFun.AddPoint(30.0, 0.05)
        opacityFun.AddPoint(31.0, 0.0)
        opacityFun.AddPoint(90.0, 0.0)
        opacityFun.AddPoint(100.0, 0.3)
        opacityFun.AddPoint(110.0, 0.0)
        opacityFun.AddPoint(190.0, 0.0)
        opacityFun.AddPoint(200.0, 0.4)
        opacityFun.AddPoint(210.0, 0.0)
        opacityFun.AddPoint(245.0, 0.0)
        opacityFun.AddPoint(255.0, 0.5)

        mapper.SetBlendModeToComposite()
        _property.ShadeOff()
        _property.SetScalarOpacityUnitDistance(1.0)
    else:
        print("Unknown blend type.")

    # Set the default window size
    renWin.SetSize(600, 600)
    renWin.Render()

    # Add the volume to the scene
    renderer.AddVolume(volume)

    renderer.ResetCamera()

    # interact with data
    renWin.Render()

    iren.Start()

    return 0
Ejemplo n.º 36
0
def main():
    sphereSource = vtk.vtkSphereSource()
    sphereSource.SetCenter(0.0, 0.0, 0.0)
    sphereSource.SetRadius(1.0)
    sphereSource.Update()

    sphereMapper = vtk.vtkPolyDataMapper()
    sphereMapper.SetInputConnection(sphereSource.GetOutputPort())
    sphereMapper.ScalarVisibilityOff()

    sphereActor = vtk.vtkActor()
    sphereActor.SetMapper(sphereMapper)
    sphereActor.GetProperty().SetOpacity(.3)
    sphereActor.GetProperty().SetColor(1, 0, 0)

    implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance()
    implicitPolyDataDistance.SetInput(sphereSource.GetOutput())

    # Setup a grid
    points = vtk.vtkPoints()
    step = 0.1
    for x in np.arange(-2, 2, step):
        for y in np.arange(-2, 2, step):
            for z in np.arange(-2, 2, step):
                points.InsertNextPoint(x, y, z)

    # Add distances to each point
    signedDistances = vtk.vtkFloatArray()
    signedDistances.SetNumberOfComponents(1)
    signedDistances.SetName("SignedDistances")

    # Evaluate the signed distance function at all of the grid points
    for pointId in range(points.GetNumberOfPoints()):
        p = points.GetPoint(pointId)
        signedDistance = implicitPolyDataDistance.EvaluateFunction(p)
        signedDistances.InsertNextValue(signedDistance)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.GetPointData().SetScalars(signedDistances)

    vertexGlyphFilter = vtk.vtkVertexGlyphFilter()
    vertexGlyphFilter.SetInputData(polyData)
    vertexGlyphFilter.Update()

    signedDistanceMapper = vtk.vtkPolyDataMapper()
    signedDistanceMapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())
    signedDistanceMapper.ScalarVisibilityOn()

    signedDistanceActor = vtk.vtkActor()
    signedDistanceActor.SetMapper(signedDistanceMapper)

    renderer = vtk.vtkRenderer()
    renderer.AddViewProp(sphereActor)
    renderer.AddViewProp(signedDistanceActor)

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    renWinInteractor = vtk.vtkRenderWindowInteractor()
    renWinInteractor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    renWinInteractor.Start()
Ejemplo n.º 37
0
def RenderModel(model, textHeight=5):

    visNodes = []
    for node in model.Nodes:
        visNodes.append(VisNode(node, textHeight))

    visAuxNodes = []
    for auxnode in model.auxNodes:
        visAuxNodes.append(VisNode(auxnode, textHeight, color='red'))

    visMembers = []
    for member in model.Members:
        visMembers.append(VisMember(member, model.Nodes, textHeight))

    visPlates = []
    for plate in model.Plates:
        visPlates.append(VisPlate(plate, model.Nodes, textHeight))

    # Create a window
    window = vtk.vtkRenderWindow()

    # Set the pixel width and length of the window
    window.SetSize(500, 500)

    # Set up the interactor
    # The interactor style determines how user interactions affect the view
    interactor = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleTrackballCamera(
    )  # The trackball camera style behaves a lot like most CAD programs
    interactor.SetInteractorStyle(style)
    interactor.SetRenderWindow(window)

    # Create a renderer
    renderer = vtk.vtkRenderer()
    window.AddRenderer(renderer)

    # Add actors for each member
    for visMember in visMembers:

        # Add the actor for the member
        renderer.AddActor(visMember.actor)

        # Add the actor for the member label
        renderer.AddActor(visMember.lblActor)

        # Set the text to follow the camera as the user interacts
        # This next line will require us to reset the camera when we're done (below)
        visMember.lblActor.SetCamera(renderer.GetActiveCamera())

    # Add actors for each node
    for visNode in visNodes:

        # Add the actor for the node
        renderer.AddActor(visNode.actor)

        # Add the actor for the node label
        renderer.AddActor(visNode.lblActor)

        # Set the text to follow the camera as the user interacts
        # This next line will require us to reset the camera when we're done (below)
        visNode.lblActor.SetCamera(renderer.GetActiveCamera())

    # Add actors for each plate
    for visPlate in visPlates:

        # Add the actors for the plate
        renderer.AddActor(visPlate.actor)

        # Add the actor for the plate label
        renderer.AddActor(visPlate.lblActor)

        # Set the text to follow the camera as the user interacts
        # This next line will require us to reset the camera when we're done (below)
        visPlate.lblActor.SetCamera(renderer.GetActiveCamera())

    # Add actors for each auxnode
    for visAuxNode in visAuxNodes:

        # Add the actor for the node
        renderer.AddActor(visAuxNode.actor)

        # Add the actor for the node label
        renderer.AddActor(visAuxNode.lblActor)

        # Set the text to follow the camera as the user interacts
        # This next line will require us to reset the camera when we're done (below)
        visAuxNode.lblActor.SetCamera(renderer.GetActiveCamera())

    # Setting the background to blue.
    renderer.SetBackground(0.1, 0.1, 0.4)

    # Reset the camera
    renderer.ResetCamera()

    window.Render()
    interactor.Start()
Ejemplo n.º 38
0
def main():
    nx, ny, nz = get_program_parameters()
    colors = vtk.vtkNamedColors()

    angle = 0
    r1 = 50
    r2 = 30
    centerX = 10.0
    centerY = 5.0

    points = vtk.vtkPoints()
    idx = 0
    while angle <= 2.0 * vtk.vtkMath.Pi() + (vtk.vtkMath.Pi() / 60.0):
        points.InsertNextPoint(r1 * math.cos(angle) + centerX,
                               r2 * math.sin(angle) + centerY,
                               0.0)
        angle = angle + (vtk.vtkMath.Pi() / 60.0)
        idx += 1

    line = vtk.vtkPolyLine()
    line.GetPointIds().SetNumberOfIds(idx)
    for i in range(0, idx):
        line.GetPointIds().SetId(i, i)

    lines = vtk.vtkCellArray()
    lines.InsertNextCell(line)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(lines)

    extrude = vtk.vtkLinearExtrusionFilter()
    extrude.SetInputData(polyData)
    extrude.SetExtrusionTypeToNormalExtrusion()
    extrude.SetVector(nx, ny, nz)
    extrude.Update()

    # Create an oriented arrow
    startPoint = [0.0] * 3
    endPoint = [0.0] * 3
    startPoint[0] = centerX
    startPoint[1] = centerY
    startPoint[2] = 0.0
    for i in range(0, 3):
        endPoint[i] = startPoint[i] + extrude.GetVector()[i]

    # Compute a basis
    normalizedX = [0.0] * 3
    normalizedY = [0.0] * 3
    normalizedZ = [0.0] * 3

    # The X axis is a vector from start to end
    vtk.vtkMath.Subtract(endPoint, startPoint, normalizedX)
    length = vtk.vtkMath.Norm(normalizedX)
    vtk.vtkMath.Normalize(normalizedX)

    rng = vtk.vtkMinimalStandardRandomSequence()
    rng.SetSeed(8775070)
    max_r = 10.0

    # The Z axis is an arbitrary vector cross X
    arbitrary = [0.0] * 3
    for i in range(0, 3):
        arbitrary[i] = rng.GetRangeValue(-max_r, max_r)
        rng.Next()
    vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ)
    vtk.vtkMath.Normalize(normalizedZ)

    # The Y axis is Z cross X
    vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY)
    matrix = vtk.vtkMatrix4x4()

    # Create the direction cosine matrix
    matrix.Identity()
    for i in range(0, 3):
        matrix.SetElement(i, 0, normalizedX[i])
        matrix.SetElement(i, 1, normalizedY[i])
        matrix.SetElement(i, 2, normalizedZ[i])

    # Apply the transforms
    transform = vtk.vtkTransform()
    transform.Translate(startPoint)
    transform.Concatenate(matrix)
    transform.Scale(length, length, length)

    arrowSource = vtk.vtkArrowSource()
    arrowSource.SetTipResolution(31)
    arrowSource.SetShaftResolution(21)

    # Transform the polydata
    transformPD = vtk.vtkTransformPolyDataFilter()
    transformPD.SetTransform(transform)
    transformPD.SetInputConnection(arrowSource.GetOutputPort())

    # Create a mapper and actor for the arrow
    arrowMapper = vtk.vtkPolyDataMapper()
    arrowMapper.SetInputConnection(transformPD.GetOutputPort())

    arrowActor = vtk.vtkActor()
    arrowActor.SetMapper(arrowMapper)
    arrowActor.GetProperty().SetColor(colors.GetColor3d("Tomato"))

    tubes = vtk.vtkTubeFilter()
    tubes.SetInputData(polyData)
    tubes.SetRadius(2.0)
    tubes.SetNumberOfSides(21)

    lineMapper = vtk.vtkPolyDataMapper()
    lineMapper.SetInputConnection(tubes.GetOutputPort())

    lineActor = vtk.vtkActor()
    lineActor.SetMapper(lineMapper)
    lineActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(extrude.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    actor.GetProperty().SetOpacity(.7)

    ren = vtk.vtkRenderer()
    ren.SetBackground(colors.GetColor3d("SlateGray"))
    ren.AddActor(actor)
    ren.AddActor(lineActor)
    ren.AddActor(arrowActor)

    renWin = vtk.vtkRenderWindow()
    renWin.SetWindowName("Elliptical Cylinder Demo")
    renWin.AddRenderer(ren)
    renWin.SetSize(600, 600)

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

    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)

    camera = vtk.vtkCamera()
    camera.SetPosition(0, 1, 0)
    camera.SetFocalPoint(0, 0, 0)
    camera.SetViewUp(0, 0, 1)
    camera.Azimuth(30)
    camera.Elevation(30)

    ren.SetActiveCamera(camera)
    ren.ResetCamera()
    ren.ResetCameraClippingRange()

    renWin.Render()
    iren.Start()
Ejemplo n.º 39
0
mapper4.SetColorLevel(1000)
mapper4.SetZSlice(0)
actor1 = vtk.vtkActor2D()
actor1.SetMapper(mapper1)
actor2 = vtk.vtkActor2D()
actor2.SetMapper(mapper2)
actor3 = vtk.vtkActor2D()
actor3.SetMapper(mapper3)
actor4 = vtk.vtkActor2D()
actor4.SetMapper(mapper4)
imager1 = vtk.vtkRenderer()
imager1.AddActor2D(actor1)
imager1.SetViewport(0.5, 0.0, 1.0, 0.5)
imager2 = vtk.vtkRenderer()
imager2.AddActor2D(actor2)
imager2.SetViewport(0.0, 0.0, 0.5, 0.5)
imager3 = vtk.vtkRenderer()
imager3.AddActor2D(actor3)
imager3.SetViewport(0.5, 0.5, 1.0, 1.0)
imager4 = vtk.vtkRenderer()
imager4.AddActor2D(actor4)
imager4.SetViewport(0.0, 0.5, 0.5, 1.0)
imgWin = vtk.vtkRenderWindow()
imgWin.AddRenderer(imager1)
imgWin.AddRenderer(imager2)
imgWin.AddRenderer(imager3)
imgWin.AddRenderer(imager4)
imgWin.SetSize(512, 512)
imgWin.Render()
# --- end of script --
Ejemplo n.º 40
0
def render_cam_view(CADModel,
                    FitResults,
                    filename=None,
                    oversampling=1,
                    AA=1,
                    Edges=False,
                    EdgeColour=(1, 0, 0),
                    EdgeWidth=2,
                    Transparency=False,
                    ROI=None,
                    ROIColour=(0.8, 0, 0),
                    ROIOpacity=0.3,
                    roi_oversize=0,
                    NearestNeighbourRemap=False,
                    Verbose=True,
                    Coords='Display',
                    ScreenSize=None):
    """
    Make CAD model renders from the camera's point of view, including all distortion effects etc.

    INPUTS:

    Required:
    CADModel        - CAD model object
    FitResults      - Fit results for the camera from whose viewpoint to do the render
    
    Optional (keyword):
    filename        - filename, including file extension, to save resulting image (if not specified, the image is not saved).
    oversampling    - the size of the rendered image is  <real camera image size> * oversampling
    AA              - Anti-aliasing factor. Larger numbers look nicer but take more memory to render
    Edges           - Bool, if set to True renders the CAD model in wireframe (but still with occlusion)
    EdgeColour      - 3-element tuple of floats 0-1, If Edges=True, what colour to make the edges in the wireframe (R,G,B)
    EdgeWidth       - If Edges=True, line width for edges
    Transparency    - whether to make black areas (i.e. background) transparent.
    ROI             - An ROI definition object: if supplied, the ROI will be rendered on the image.
    ROIColour       - (R,G,B) colour to render the ROI
    ROIOpacity      - Opacity to render ROI
    qt_avilable_geometry - If being called from a Qt app, this must be used. 

    OUTPUTS:

    im - numpy array with RGB[A] image

    If filename is provided, saves the render with the specified filename
    """

    if Coords.lower() == 'original' and oversampling != 1:
        raise Exception(
            'Cannot render in original coordinates with oversampling!')

    logbase2 = np.log(oversampling) / np.log(2)
    if abs(int(logbase2) - logbase2) > 1e-5:
        raise ValueError('Oversampling must be a power of two!')

    if Verbose:
        tstart = time.time()
        print('[Calcam Renderer] Preparing...')

    # This will be our result. To start with we always render in display coords.
    OutputImage = np.zeros([
        int(FitResults.image_display_shape[1] * oversampling),
        int(FitResults.image_display_shape[0] * oversampling), 3 + Transparency
    ],
                           dtype='uint8')

    # The un-distorted FOV is over-rendered to allow for distortion.
    # FOV_factor is how much to do this by; too small and image edges might be cut off.
    models = []
    for field in FitResults.fit_params:
        models.append(field.model)
    if np.any(np.array(models) == 'fisheye'):
        FOV_factor = 3.
    else:
        FOV_factor = 1.5

    x_pixels = FitResults.image_display_shape[0]
    y_pixels = FitResults.image_display_shape[1]

    renWin = vtk.vtkRenderWindow()
    renWin.OffScreenRenderingOn()

    # Get the screen resolution - even using off screen rendering, if the VTK render window
    # doesn't fit on the screen it causes problems.
    # Maybe slightly hacky way of finding this out? But I don't know a better one.
    if ScreenSize is None:
        try:
            app = qt.QApplication(sys.argv)
            desktopinfo = app.desktop()
            dummydialog = qt.QDialog()
            qt_available_geometry = desktopinfo.availableGeometry(dummydialog)
            ScreenSize = (qt_available_geometry.width(),
                          available_geometry.height())
            del qt_available_geometry, dummydialog, desktopinfo, app
        except:
            ScreenSize = (800, 600)

    # Set up render window for initial, un-distorted window
    renderer = vtk.vtkRenderer()
    renWin.AddRenderer(renderer)

    Camera = renderer.GetActiveCamera()

    # Set the model face colour to black if we only want to see edges
    if Edges:
        CADModel.edges = True
        CADModel.edge_width = EdgeWidth
        # If rendering wireframe, set the CAD model colour to the desired edge colour. Before we do that, save the colours we started with.
        oldColours = []
        for Feature in CADModel.features:
            oldColours.append((Feature[4], Feature[0]))
        CADModel.set_colour(EdgeColour)

    # This whole thing is in a try() except() because it is prone to memory errors, and I need to put the CAD model
    # colour back the way it started if we have a problem.
    try:
        # Add all the bits of the machine
        for Actor in CADModel.get_vtkActors():
            renderer.AddActor(Actor)

        # Add the ROI if provided
        if ROI is not None:
            try:
                n_rois = len(ROI.rois)
                for roi in ROI.rois:
                    ROIActor = roi.get_vtkActor(FitResults.get_pupilpos())
                    ROIActor.GetProperty().SetColor(ROIColour)
                    ROIActor.GetProperty().SetOpacity(ROIOpacity)
                    if roi_oversize > 0:
                        ROIActor.GetProperty().EdgeVisibilityOn()
                        ROIActor.GetProperty().SetLineWidth(roi_oversize * 2.)
                        ROIActor.GetProperty().SetEdgeColor(ROIColour)
                    renderer.AddActor(ROIActor)
            except AttributeError:
                ROIActor = ROI.get_vtkActor(FitResults.get_pupilpos(field=0))
                ROIActor.GetProperty().SetColor(ROIColour)
                ROIActor.GetProperty().SetOpacity(ROIOpacity)
                if roi_oversize > 0:
                    ROIActor.GetProperty().EdgeVisibilityOn()
                    ROIActor.GetProperty().SetLineWidth(roi_oversize * 2.)
                    ROIActor.GetProperty().SetEdgeColor(ROIColour)
                renderer.AddActor(ROIActor)

        # We need a field mask the same size as the output
        FieldMask = cv2.resize(
            FitResults.fieldmask,
            (int(x_pixels * oversampling), int(y_pixels * oversampling)),
            interpolation=cv2.INTER_NEAREST)

        for field in range(FitResults.nfields):

            Cx = FitResults.fit_params[field].cam_matrix[0, 2]
            Cy = FitResults.fit_params[field].cam_matrix[1, 2]
            Fy = FitResults.fit_params[field].cam_matrix[1, 1]

            vtk_win_im = vtk.vtkRenderLargeImage()
            vtk_win_im.SetInput(renderer)

            # Width and height - initial render will be put optical centre in the window centre
            wt = int(2 * FOV_factor * max(Cx, x_pixels - Cx))
            ht = int(2 * FOV_factor * max(Cy, y_pixels - Cy))

            # Make sure the intended render window will fit on the screen
            window_factor = 1
            if wt > ScreenSize[0] or ht > ScreenSize[1]:
                window_factor = int(
                    max(np.ceil(float(wt) / float(ScreenSize[0])),
                        np.ceil(float(ht) / float(ScreenSize[1]))))

            vtk_win_im.SetMagnification(
                int(window_factor * AA * max(oversampling, 1)))

            width = int(wt / window_factor)
            height = int(ht / window_factor)

            renWin.SetSize(width, height)

            # Set up CAD camera
            FOV_y = 360 * np.arctan(ht / (2 * Fy)) / 3.14159
            CamPos = FitResults.get_pupilpos(field=field)
            CamTar = FitResults.get_los_direction(Cx, Cy,
                                                  ForceField=field) + CamPos
            UpVec = -1. * FitResults.get_cam_to_lab_rotation(field=field)[:, 1]
            Camera.SetPosition(CamPos)
            Camera.SetViewAngle(FOV_y)
            Camera.SetFocalPoint(CamTar)
            Camera.SetViewUp(UpVec)

            if Verbose:
                print(
                    '[Calcam Renderer] Rendering (Field {:d}/{:d})...'.format(
                        field + 1, FitResults.nfields))

            # Do the render and grab an image
            renWin.Render()

            vtk_win_im.Update()

            vtk_image = vtk_win_im.GetOutput()

            if field == FitResults.nfields - 1:
                renWin.Finalize()
                if Edges:
                    # Put the colour scheme back to how it was
                    for Feature in oldColours:
                        CADModel.set_colour(Feature[0], Feature[1])
                    Actor.GetProperty().EdgeVisibilityOff()

            vtk_array = vtk_image.GetPointData().GetScalars()
            dims = vtk_image.GetDimensions()
            im = np.flipud(
                vtk.util.numpy_support.vtk_to_numpy(vtk_array).reshape(
                    dims[1], dims[0], 3))

            if Transparency:
                alpha = 255 * np.ones(
                    [np.shape(im)[0], np.shape(im)[1]], dtype='uint8')
                alpha[np.sum(im, axis=2) == 0] = 0
                im = np.dstack((im, alpha))

            im = cv2.resize(im, (int(dims[0] / AA * min(oversampling, 1)),
                                 int(dims[1] / AA * min(oversampling, 1))),
                            interpolation=cv2.INTER_AREA)

            if Verbose:
                print(
                    '[Calcam Renderer] Applying lens distortion (Field {:d}/{:d})...'
                    .format(field + 1, FitResults.nfields))

            # Pixel locations we want on the final image
            [xn, yn] = np.meshgrid(
                np.linspace(0, x_pixels - 1, x_pixels * oversampling),
                np.linspace(0, y_pixels - 1, y_pixels * oversampling))

            xn, yn = FitResults.normalise(xn, yn, field)

            # Transform back to pixel coords where we want to sample the un-distorted render.
            # Both x and y are divided by Fy because the initial render always has Fx = Fy.
            xmap = ((xn * Fy) + (width * window_factor) / 2.) * oversampling
            ymap = ((yn * Fy) + (height * window_factor) / 2.) * oversampling
            xmap = xmap.astype('float32')
            ymap = ymap.astype('float32')

            # Actually apply distortion
            if NearestNeighbourRemap:
                interp_method = cv2.INTER_NEAREST
            else:
                interp_method = cv2.INTER_CUBIC

            im = cv2.remap(im, xmap, ymap, interp_method)

            OutputImage[FieldMask == field, :] = im[FieldMask == field, :]

        CADModel.edges = False

        if Coords.lower() == 'original':
            OutputImage = FitResults.transform.display_to_original_image(
                OutputImage)

        if Verbose:
            print(
                '[Calcam Renderer] Completed in {:.1f} s.'.format(time.time() -
                                                                  tstart))

        # Save the image if given a filename
        if filename is not None:

            # If we have transparency, we can only save as PNG.
            if Transparency and filename[-3:].lower() != 'png':
                print(
                    '[Calcam Renderer] Images with transparency can only be saved as PNG! Overriding output file type to PNG.'
                )
                filename = filename[:-3] + 'png'

            # Re-shuffle the colour channels for saving (openCV needs BGR / BGRA)
            SaveIm = OutputImage
            SaveIm[:, :, :3] = OutputImage[:, :, 2::-1]
            cv2.imwrite(filename, SaveIm)
            if Verbose:
                print(
                    '[Calcam Renderer] Result saved as {:s}'.format(filename))
    except:
        if Edges:
            CADModel.edges = False
            # Put the colour scheme back to how it was
            for Feature in oldColours:
                CADModel.set_colour(Feature[0], Feature[1])
            Actor.GetProperty().EdgeVisibilityOff()
            try:
                renWin.Finalize()
            except:
                pass
        raise

    return OutputImage
Ejemplo n.º 41
0
def main():
    """
    Visualization of 3D grid anchor generation, showing 2D projections
        in BEV and image space, and a 3D display of the anchors
    """
    dataset_config = DatasetBuilder.copy_config(DatasetBuilder.KITTI_TRAIN)
    dataset_config.num_clusters[0] = 1
    dataset = DatasetBuilder.build_kitti_dataset(dataset_config)

    label_cluster_utils = LabelClusterUtils(dataset)
    clusters, _ = label_cluster_utils.get_clusters()

    # Options
    img_idx = 1
    # fake_clusters = np.array([[5, 4, 3], [6, 5, 4]])
    # fake_clusters = np.array([[3, 3, 3], [4, 4, 4]])

    fake_clusters = np.array([[4, 2, 3]])
    fake_anchor_stride = [5.0, 5.0]
    ground_plane = [0, -1, 0, 1.72]

    anchor_3d_generator = grid_anchor_3d_generator.GridAnchor3dGenerator()

    area_extents = np.array([[-40, 40], [-5, 5], [0, 70]])

    # Generate anchors for cars only
    start_time = time.time()
    anchor_boxes_3d = anchor_3d_generator.generate(
        area_3d=dataset.kitti_utils.area_extents,
        anchor_3d_sizes=fake_clusters,
        anchor_stride=fake_anchor_stride,
        ground_plane=ground_plane)
    all_anchors = box_3d_encoder.box_3d_to_anchor(anchor_boxes_3d)
    end_time = time.time()
    print("Anchors generated in {} s".format(end_time - start_time))

    # Project into bev
    bev_boxes, bev_normalized_boxes = \
        anchor_projector.project_to_bev(all_anchors, area_extents[[0, 2]])

    bev_fig, (bev_axes, bev_normalized_axes) = \
        plt.subplots(1, 2, figsize=(16, 7))
    bev_axes.set_xlim(0, 80)
    bev_axes.set_ylim(70, 0)
    bev_normalized_axes.set_xlim(0, 1.0)
    bev_normalized_axes.set_ylim(1, 0.0)

    plt.show(block=False)

    for box in bev_boxes:
        box_w = box[2] - box[0]
        box_h = box[3] - box[1]

        rect = patches.Rectangle((box[0], box[1]),
                                 box_w,
                                 box_h,
                                 linewidth=2,
                                 edgecolor='b',
                                 facecolor='none')

        bev_axes.add_patch(rect)

    for normalized_box in bev_normalized_boxes:
        box_w = normalized_box[2] - normalized_box[0]
        box_h = normalized_box[3] - normalized_box[1]

        rect = patches.Rectangle((normalized_box[0], normalized_box[1]),
                                 box_w,
                                 box_h,
                                 linewidth=2,
                                 edgecolor='b',
                                 facecolor='none')

        bev_normalized_axes.add_patch(rect)

    rgb_fig, rgb_2d_axes, rgb_3d_axes = \
        vis_utils.visualization(dataset.rgb_image_dir, img_idx)
    plt.show(block=False)

    image_path = dataset.get_rgb_image_path(dataset.sample_names[img_idx])
    image_shape = np.array(Image.open(image_path)).shape

    stereo_calib_p2 = calib_utils.read_calibration(dataset.calib_dir,
                                                   img_idx).p2

    start_time = time.time()
    rgb_boxes, rgb_normalized_boxes = \
        anchor_projector.project_to_image_space(all_anchors,
                                                stereo_calib_p2,
                                                image_shape)
    end_time = time.time()
    print("Anchors projected in {} s".format(end_time - start_time))

    # Read the stereo calibration matrix for visualization
    stereo_calib = calib_utils.read_calibration(dataset.calib_dir, 0)
    p = stereo_calib.p2

    # Overlay boxes on images
    anchor_objects = []
    for anchor_idx in range(len(anchor_boxes_3d)):
        anchor_box_3d = anchor_boxes_3d[anchor_idx]

        obj_label = box_3d_encoder.box_3d_to_object_label(anchor_box_3d)

        # Append to a list for visualization in VTK later
        anchor_objects.append(obj_label)

        # Draw 3D boxes
        vis_utils.draw_box_3d(rgb_3d_axes, obj_label, p)

        # Draw 2D boxes
        rgb_box_2d = rgb_boxes[anchor_idx]

        box_x1 = rgb_box_2d[0]
        box_y1 = rgb_box_2d[1]
        box_w = rgb_box_2d[2] - box_x1
        box_h = rgb_box_2d[3] - box_y1

        rect = patches.Rectangle((box_x1, box_y1),
                                 box_w,
                                 box_h,
                                 linewidth=2,
                                 edgecolor='b',
                                 facecolor='none')

        rgb_2d_axes.add_patch(rect)

        if anchor_idx % 32 == 0:
            rgb_fig.canvas.draw()

    plt.show(block=False)

    # Create VtkGroundPlane for ground plane visualization
    vtk_ground_plane = VtkGroundPlane()
    vtk_ground_plane.set_plane(ground_plane, area_extents[[0, 2]])

    # Create VtkAxes
    axes = vtk.vtkAxesActor()
    axes.SetTotalLength(5, 5, 5)

    # Create VtkBoxes for boxes
    vtk_boxes = VtkBoxes()
    vtk_boxes.set_objects(anchor_objects, vtk_boxes.COLOUR_SCHEME_KITTI)

    # Create Voxel Grid Renderer in bottom half
    vtk_renderer = vtk.vtkRenderer()
    vtk_renderer.AddActor(vtk_boxes.vtk_actor)
    vtk_renderer.AddActor(vtk_ground_plane.vtk_actor)
    vtk_renderer.AddActor(axes)
    vtk_renderer.SetBackground(0.2, 0.3, 0.4)

    # Setup Camera
    current_cam = vtk_renderer.GetActiveCamera()
    current_cam.Pitch(170.0)
    current_cam.Roll(180.0)

    # Zooms out to fit all points on screen
    vtk_renderer.ResetCamera()

    # Zoom in slightly
    current_cam.Zoom(2.5)

    # Reset the clipping range to show all points
    vtk_renderer.ResetCameraClippingRange()

    # Setup Render Window
    vtk_render_window = vtk.vtkRenderWindow()
    vtk_render_window.SetWindowName("Anchors")
    vtk_render_window.SetSize(900, 500)
    vtk_render_window.AddRenderer(vtk_renderer)

    # Setup custom interactor style, which handles mouse and key events
    vtk_render_window_interactor = vtk.vtkRenderWindowInteractor()
    vtk_render_window_interactor.SetRenderWindow(vtk_render_window)

    vtk_render_window_interactor.SetInteractorStyle(
        vtk.vtkInteractorStyleTrackballCamera())

    # Render in VTK
    vtk_render_window.Render()
    vtk_render_window_interactor.Start()  # Blocking
Ejemplo n.º 42
0
    def __init__(self, element_color_mapping=None, show_unit_cell=True,
                 show_bonds=False, show_polyhedron=True,
                 poly_radii_tol_factor=0.5, excluded_bonding_elements=None):
        """
        Args:
            element_color_mapping:
                Optional color mapping for the elements, as a dict of
                {symbol: rgb tuple}. For example, {"Fe": (255,123,0), ....}
                If None is specified, a default based on Jmol"s color scheme
                is used.
            show_unit_cell:
                Set to False to not show the unit cell boundaries. Defaults to
                True.
            show_bonds:
                Set to True to show bonds. Defaults to True.
            show_polyhedron:
                Set to True to show polyhedrons. Defaults to False.
            poly_radii_tol_factor:
                The polyhedron and bonding code uses the ionic radii of the
                elements or species to determine if two atoms are bonded. This
                specifies a tolerance scaling factor such that atoms which are
                (1 + poly_radii_tol_factor) * sum of ionic radii apart are
                still considered as bonded.
            excluded_bonding_elements:
                List of atom types to exclude from bonding determination.
                Defaults to an empty list. Useful when trying to visualize a
                certain atom type in the framework (e.g., Li in a Li-ion
                battery cathode material).

        Useful keyboard shortcuts implemented.
            h : Show help
            A/a : Increase/decrease cell by one unit vector in a-direction
            B/b : Increase/decrease cell by one unit vector in b-direction
            C/c : Increase/decrease cell by one unit vector in c-direction
            # : Toggle showing of polyhedrons
            - : Toggle showing of bonds
            [ : Decrease poly_radii_tol_factor by 0.05
            ] : Increase poly_radii_tol_factor by 0.05
            r : Reset camera direction
            o : Orthogonalize structure
            Up/Down : Rotate view along Up direction by 90 clock/anticlockwise
            Left/right : Rotate view along camera direction by 90
            clock/anticlockwise
        """
        # create a rendering window and renderer
        self.ren = vtk.vtkRenderer()
        self.ren_win = vtk.vtkRenderWindow()
        self.ren_win.AddRenderer(self.ren)
        self.ren.SetBackground(1, 1, 1)
        self.title = "Structure Visualizer"
        # create a renderwindowinteractor
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.ren_win)
        self.mapper_map = {}
        self.structure = None

        if element_color_mapping:
            self.el_color_mapping = element_color_mapping
        else:
            module_dir = os.path.dirname(os.path.abspath(__file__))
            config = ConfigParser.SafeConfigParser()
            config.optionxform = str
            config.readfp(open(os.path.join(module_dir,
                                            "ElementColorSchemes.cfg")))

            self.el_color_mapping = {}
            for (el, color) in config.items("VESTA"):
                self.el_color_mapping[el] = [int(i) for i in color.split(",")]
        self.show_unit_cell = show_unit_cell
        self.show_bonds = show_bonds
        self.show_polyhedron = show_polyhedron
        self.poly_radii_tol_factor = poly_radii_tol_factor
        self.excluded_bonding_elements = excluded_bonding_elements if \
            excluded_bonding_elements else []
        self.show_help = True
        self.supercell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
        self.redraw()

        style = StructureInteractorStyle(self)
        self.iren.SetInteractorStyle(style)
Ejemplo n.º 43
0
def test_get_vtk_pane_type_from_render_window():
    assert PaneBase.get_pane_type(
        vtk.vtkRenderWindow()) is VTKRenderWindowSynchronized
    assert PaneBase.get_pane_type(
        vtk.vtkRenderWindow(),
        serialize_on_instantiation=True) is VTKRenderWindow
Ejemplo n.º 44
0
# Setup right wing actor
r_wing_actor = vtk.vtkActor()
r_wing_actor.GetProperty().SetColor((0.6, 0.6, 0.6))
r_wing_actor.GetProperty().SetOpacity(0.7)
r_wing_actor.GetProperty().SetInterpolationToGouraud()
#r_wing_actor.GetProperty().SetAmbient(0.3)
r_wing_actor.SetMapper(wing_mapper)

# Read log file
log_fid = open(log_file, 'r')
log = cPickle.load(log_fid)
log_fid.close()

# Create the Renderer, RenderWindow, and RenderWindowInteractor
ren = vtk.vtkRenderer()
ren_win = vtk.vtkRenderWindow()
ren_win.AddRenderer(ren)
ren.SetBackground(0.0, 0.0, 0.0)
ren_win.FullScreenOn()
ren_win.SwapBuffersOn()

# Create balls
if 1:
    ball_grid = (4, 3)
    ball_spacing = 100
    ball_z = -20.0
    ball = vtk.vtkSphereSource()
    ball.SetRadius(10.0)
    ball.SetThetaResolution(25)
    ball.SetPhiResolution(25)
    mapBall = vtk.vtkPolyDataMapper()
Ejemplo n.º 45
0
def main(argc, argv):
    if (argc != 7):
        print("Usage: " + argv[0] + " Theta Phi MaximumPeels " +
              "OcclusionRatio ForceDepthSortingFlag " +
              "DoNotUseAnyDepthRelatedAlgorithmFlag" + "\n")
        print("100 100 50 0.1 0 0")
        return -1

    colors = vtk.vtkNamedColors()

    theta = int(argv[1])
    phi = int(argv[2])
    maxPeels = int(argv[3])
    occulusionRatio = float(argv[4])
    forceDepthSort = int(argv[5]) == 1
    withoutAnyDepthThings = (argv[6]) == 1

    # Generate a translucent sphere poly data set that partially overlaps:
    translucentGeometry = GenerateOverlappingBunchOfSpheres(theta, phi)

    # generate a basic Mapper and Actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(translucentGeometry.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(0.5)  # translucent !!!
    actor.GetProperty().SetColor(colors.GetColor3d("Crimson"))
    actor.RotateX(-72)  # put the objects in a position where it is easy to see
    # different overlapping regions

    # Create the RenderWindow, Renderer and RenderWindowInteractor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(600, 400)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName("CorrectlyRenderTranslucentGeometry")

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actors to the renderer, set the background and size
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    # Setup view geometry
    renderer.ResetCamera()
    renderer.GetActiveCamera().Zoom(2.2)  # so the object is larger
    renderWindow.Render()

    # Answer the key question: Does this box support GPU Depth Peeling?
    useDepthPeeling = IsDepthPeelingSupported(renderWindow, renderer, True)
    print("DEPTH PEELING SUPPORT: " + {1: "YES", 0: "NO"}[useDepthPeeling])

    success = 0

    # Use depth peeling if available and not explicitly prohibited, otherwise we
    # use manual depth sorting
    print("\n" + "CHOSEN MODE: ")
    if (useDepthPeeling and ~forceDepthSort and ~withoutAnyDepthThings):  # GPU
        print("*** DEPTH PEELING ***")
        # Setup GPU depth peeling with configured parameters
        success = ~SetupEnvironmentForDepthPeeling(renderWindow, renderer,
                                                   maxPeels, occulusionRatio)
    elif (~withoutAnyDepthThings):
        print("*** DEPTH SORTING ***")
        # Setup CPU depth sorting filter
        depthSort = vtk.vtkDepthSortPolyData()
        depthSort.SetInputConnection(translucentGeometry.GetOutputPort())
        depthSort.SetDirectionToBackToFront()
        depthSort.SetVector(1, 1, 1)
        depthSort.SetCamera(renderer.GetActiveCamera())
        depthSort.SortScalarsOff()  # do not really need this here
        # Bring it to the mapper's input
        mapper.SetInputConnection(depthSort.GetOutputPort())
        depthSort.Update()
    else:
        print("*** NEITHER DEPTH PEELING NOR DEPTH SORTING ***")

    # Initialize interaction
    renderWindowInteractor.Initialize()

    # Check the average frame rate when rotating the actor
    endCount = 100
    clock = vtk.vtkTimerLog()
    # Set a user transform for successively rotating the camera position
    transform = vtk.vtkTransform()
    transform.Identity()
    transform.RotateY(2.0)  # rotate 2 degrees around Y-axis at each iteration
    camera = renderer.GetActiveCamera()
    # Start test
    clock.StartTimer()
    for i in range(endCount):
        camPos = camera.GetPosition()
        camPos = transform.TransformPoint(camPos)
        camera.SetPosition(camPos)
        renderWindow.Render()
    clock.StopTimer()
    frameRate = endCount / clock.GetElapsedTime()
    print("AVERAGE FRAME RATE: " + str(frameRate) + " fps")

    # Start interaction
    renderWindowInteractor.Start()

    return success
Ejemplo n.º 46
0
    def testBug(self):
        # Uncomment the next line if you want to run this via
        # `gdb python`.
        #raw_input('Hit Ctrl-C')

        # Load some data.
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(
            os.path.join(VTK_DATA_ROOT, "Data", "headsq", "quarter"))
        v16.SetImageRange(1, 93)
        v16.SetDataSpacing(3.2, 3.2, 1.5)
        v16.Update()

        xMin, xMax, yMin, yMax, zMin, zMax = v16.GetExecutive().GetWholeExtent(
            v16.GetOutputInformation(0))
        img_data = v16.GetOutput()

        # **************************************************
        # Look here for wierdness.

        # Lets create this data using the data from the reader.
        my_img_data = vtk.vtkImageData()
        my_img_data.SetDimensions(img_data.GetDimensions())
        my_img_data.SetExtent(img_data.GetExtent())
        my_img_data.SetSpacing(img_data.GetSpacing())
        my_img_data.SetOrigin(img_data.GetOrigin())
        my_img_data.SetScalarType(img_data.GetScalarType(),
                                  my_img_data.GetInformation())
        my_img_data.GetPointData().SetScalars(
            img_data.GetPointData().GetScalars())
        # hang on to original image data.
        orig_img_data = img_data

        # hijack img_data with our own.  If you comment this out everything is
        # fine.
        img_data = my_img_data
        # **************************************************

        spacing = img_data.GetSpacing()
        sx, sy, sz = spacing

        origin = img_data.GetOrigin()
        ox, oy, oz = origin

        # An outline is shown for context.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputData(img_data)

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # 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)

        # The 3 image plane widgets are used to probe the dataset.
        planeWidgetX = vtk.vtkImagePlaneWidget()
        planeWidgetX.DisplayTextOn()
        planeWidgetX.SetInputData(img_data)
        planeWidgetX.SetPlaneOrientationToXAxes()
        planeWidgetX.SetSliceIndex(32)
        planeWidgetX.SetPicker(picker)
        planeWidgetX.SetKeyPressActivationValue("x")
        prop1 = planeWidgetX.GetPlaneProperty()
        prop1.SetColor(1, 0, 0)

        planeWidgetY = vtk.vtkImagePlaneWidget()
        planeWidgetY.DisplayTextOn()
        planeWidgetY.SetInputData(img_data)
        planeWidgetY.SetPlaneOrientationToYAxes()
        planeWidgetY.SetSliceIndex(32)
        planeWidgetY.SetPicker(picker)
        planeWidgetY.SetKeyPressActivationValue("y")
        prop2 = planeWidgetY.GetPlaneProperty()
        prop2.SetColor(1, 1, 0)
        planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())

        # for the z-slice, turn off texture interpolation:
        # interpolation is now nearest neighbour, to demonstrate
        # cross-hair cursor snapping to pixel centers
        planeWidgetZ = vtk.vtkImagePlaneWidget()
        planeWidgetZ.DisplayTextOn()
        planeWidgetZ.SetInputData(img_data)
        planeWidgetZ.SetPlaneOrientationToZAxes()
        planeWidgetZ.SetSliceIndex(46)
        planeWidgetZ.SetPicker(picker)
        planeWidgetZ.SetKeyPressActivationValue("z")
        prop3 = planeWidgetZ.GetPlaneProperty()
        prop3.SetColor(0, 0, 1)
        planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())

        # Create the RenderWindow and Renderer
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # Add the outline actor to the renderer, set the background
        # color and size
        ren.AddActor(outlineActor)
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()
Ejemplo n.º 47
0
def render_window(actor, title, scalarBar, bounds):
    """ puts a vtk actor on the stage (renders an interactive window)
    
    @param actor                    a (single) actor, or a list of actors (ensemble)
    @param title                    window title 
    @param scalarBar                one or a list of vtkScalarBarActor (optional)
    @param bounds                   spatial bounds (to set axes actor, and camera position and focal point)
    @return a vtkRenderWindowInteractor     use render_window(...).Start() to start interaction loop, or render_window(...).GetRenderWindow(), to write png
    
    (built in)
    Keypress j / Keypress t: toggle between joystick (position sensitive) and trackball (motion sensitive) styles. In joystick style, motion occurs continuously as long as a mouse button is pressed. In trackball style, motion occurs when the mouse button is pressed and the mouse pointer moves.
    Keypress c / Keypress a: toggle between camera and actor modes. In camera mode, mouse events affect the camera position and focal point. In actor mode, mouse events affect the actor that is under the mouse pointer.
    Button 1: rotate the camera around its focal point (if camera mode) or rotate the actor around its origin (if actor mode). The rotation is in the direction defined from the center of the renderer's viewport towards the mouse position. In joystick mode, the magnitude of the rotation is determined by the distance the mouse is from the center of the render window.
    Button 2: pan the camera (if camera mode) or translate the actor (if actor mode). In joystick mode, the direction of pan or translation is from the center of the viewport towards the mouse position. In trackball mode, the direction of motion is the direction the mouse moves. (Note: with 2-button mice, pan is defined as <Shift>-Button 1.)
    Button 3: zoom the camera (if camera mode) or scale the actor (if actor mode). Zoom in/increase scale if the mouse position is in the top half of the viewport; zoom out/decrease scale if the mouse position is in the bottom half. In joystick mode, the amount of zoom is controlled by the distance of the mouse pointer from the horizontal centerline of the window.
    Keypress 3: toggle the render window into and out of stereo mode. By default, red-blue stereo pairs are created. Some systems support Crystal Eyes LCD stereo glasses; you have to invoke SetStereoTypeToCrystalEyes() on the rendering window.
    Keypress e: exit the application.
    Keypress f: fly to the picked point
    Keypress p: perform a pick operation. The render window interactor has an internal instance of vtkCellPicker that it uses to pick.
    Keypress r: reset the camera view along the current view direction. Centers the actors and moves the camera so that all actors are visible.
    Keypress s: modify the representation of all actors so that they are surfaces.
    Keypress u: invoke the user-defined function. Typically, this keypress will bring up an interactor that you can type commands in. Typing u calls UserCallBack() on the vtkRenderWindowInteractor, which invokes a vtkCommand::UserEvent. In other words, to define a user-defined callback, just add an observer to the vtkCommand::UserEvent on the vtkRenderWindowInteractor object.
    Keypress w: modify the representation of all actors so that they are wireframe.
    
    (additional)
    Keypress g: save as png    
    Keypress x,y,z,v: various views    
    """
    colors = vtk.vtkNamedColors()  # Set the background color
    ren = vtk.vtkRenderer()  # Set up window with interaction
    ren.SetBackground(colors.GetColor3d("Silver"))

    # Actors
    if isinstance(actor, list):
        actors = actor  # plural
    else:
        actors = [actor]  # army of one
    for a in actors:
        a.GetProperty().BackfaceCullingOff()
        # a.RotateX(-90)  # x y z -> x z y
        ren.AddActor(
            a)  # Add the actors to the renderer, set the background and size

    if scalarBar:
        #         if isinstance(scalarBar, list):
        #             c = 0.
        #             for sb in scalarBar:  # TODO looks awful
        #                 x = sb.GetPosition()
        #                 y = (x[0] + c, x[1])
        #                 sb.SetPosition(y)
        #                 ren.AddActor2D(sb)
        #                 c -= 0.2
        #         else:
        ren.AddActor2D(scalarBar)

    axes = vtk.vtkAxesActor()
    axes.AxisLabelsOff()  # because i am too lazy to change font size
    translate = vtk.vtkTransform()
    translate.Translate(bounds[0], bounds[2], bounds[4])  # minx, miny, minz
    axes.SetUserTransform(translate)
    ren.AddActor(axes)

    # Camera
    ren.ResetCamera()
    camera = ren.GetActiveCamera()
    camera.ParallelProjectionOn()
    camera.SetFocalPoint([0, 0, 0.5 * (bounds[4] + bounds[5])])
    camera.SetPosition([200, 0, 0.5 * (bounds[4] + bounds[5])])
    camera.SetViewUp(0, 0, 1)
    camera.Azimuth(30)
    camera.Elevation(30)
    camera.OrthogonalizeViewUp()
    camera.SetClippingRange(1, 1000)

    # Render Window
    renWin = vtk.vtkRenderWindow()  # boss
    renWin.SetSize(1000, 1000)
    print("title", title)
    renWin.SetWindowName(title)
    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    renWin.Render()
    iren.CreateRepeatingTimer(
        50)  # [ms] 0.5 s in case a timer event is interested
    iren.AddObserver('KeyPressEvent',
                     lambda obj, ev: keypress_callback_(obj, ev, bounds), 1.0)
    iren.Initialize(
    )  # This allows the interactor to initalize itself. It has to be called before an event loop.
    for a in ren.GetActors():
        a.Modified()  #
    renWin.Render()
    return iren
Ejemplo n.º 48
0
def main():
    grid = vtk.vtkUnstructuredGrid()
    grid_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_VERSION >= 6:
        grid_mapper.SetInputData(grid)
    else:
        grid_mapper.SetInput(grid)
    #if vtk.VTK_VERSION[0] <= 5:
    #    grid_mapper.SetInputConnection(grid.GetProducerPort())
    #else:
    #    grid_mapper.SetInputData(grid)

    nodes = np.array([
        [0., 0., 0.],
        [1., 0., 0.],
        [1., 1., 0.],
        [0., 2., 1.],
    ],
                     dtype='float32')

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points_array = numpy_to_vtk(
        num_array=nodes,
        deep=True,
        array_type=vtk.VTK_FLOAT,
    )
    nelements = 1
    grid.Allocate(nelements, 1000)
    grid.SetPoints(points)
    elem = vtk.vtkQuad()
    pts = elem.GetPointIds()
    pts.SetId(0, 0)
    pts.SetId(1, 1)
    pts.SetId(2, 2)
    pts.SetId(3, 3)
    grid.InsertNextCell(elem.GetCellType(), pts)
    grid.Modified()

    forces = np.array([
        [0., 0.1, 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., .3],
    ],
                      dtype='float32')

    rend = vtk.vtkRenderer()
    if 1:
        maskPts = vtk.vtkMaskPoints()
        if vtk.VTK_VERSION <= 5:
            maskPts.SetInputConnection(grid.GetProducerPort())
        else:
            maskPts.SetInputData(grid)

        arrow = vtk.vtkArrowSource()
        arrow.SetTipResolution(16)
        arrow.SetTipLength(0.3)
        arrow.SetTipRadius(0.1)

        glyph = vtk.vtkGlyph3D()
        glyph.SetSourceConnection(arrow.GetOutputPort())
        glyph.SetInputConnection(maskPts.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleFactor(1)
        glyph.SetColorModeToColorByVector()
        glyph.SetScaleModeToScaleByVector()
        glyph.OrientOn()
        glyph.Update()

        glyph_mapper = vtk.vtkPolyDataMapper()
        glyph_mapper.SetInputConnection(glyph.GetOutputPort())
        glyph_mapper.SetScalarModeToUsePointFieldData()
        glyph_mapper.SetColorModeToMapScalars()
        glyph_mapper.ScalarVisibilityOn()
        glyph_mapper.SelectColorArray('Elevation')
        # Colour by scalars.
        #glyph_mapper.SetScalarRange(scalarRangeElevation)

        glyph_actor = vtk.vtkActor()
        glyph_actor.SetMapper(glyph_mapper)
        glyph_actor.RotateX(-45)
        glyph_actor.RotateZ(45)
        rend.AddViewProp(glyph_actor)
        #rend.AddActor(glyph_actor)

    geom_actor = vtk.vtkActor()
    geom_actor.SetMapper(grid_mapper)
    # ------------------------------------------------------------
    # Create the RenderWindow, Renderer and Interactor
    # ------------------------------------------------------------
    renWin = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()

    renWin.AddRenderer(rend)
    iren.SetRenderWindow(renWin)

    # add actors
    #rend.AddViewProp(geom_actor)
    #rend.AddViewProp(edgeActor)
    rend.AddActor(geom_actor)
    #rend.AddViewProp(glyph_actor)
    #rend.AddActor2D(scalarBar)

    rend.SetBackground(0.7, 0.8, 1.0)
    renWin.SetSize(800, 800)
    renWin.Render()
    iren.Start()
Ejemplo n.º 49
0
def main():
    colors = vtk.vtkNamedColors()

    #  Verify input arguments
    fn = get_program_parameters()
    if fn:
        # Read the image
        jpeg_reader = vtk.vtkJPEGReader()
        if not jpeg_reader.CanReadFile(fn):
            print('Error reading file:', fn)
            return

        jpeg_reader.SetFileName(fn)
        jpeg_reader.Update()
        image_data = jpeg_reader.GetOutput()
    else:
        canvas_source = vtk.vtkImageCanvasSource2D()
        canvas_source.SetExtent(0, 100, 0, 100, 0, 0)
        canvas_source.SetScalarTypeToUnsignedChar()
        canvas_source.SetNumberOfScalarComponents(3)
        canvas_source.SetDrawColor(colors.GetColor4ub('warm_grey'))
        canvas_source.FillBox(0, 100, 0, 100)
        canvas_source.SetDrawColor(colors.GetColor4ub('DarkCyan'))
        canvas_source.FillTriangle(10, 10, 25, 10, 25, 25)
        canvas_source.SetDrawColor(colors.GetColor4ub('LightCoral'))
        canvas_source.FillTube(75, 75, 0, 75, 5.0)
        canvas_source.Update()
        image_data = canvas_source.GetOutput()

    # Create an image actor to display the image
    image_actor = vtk.vtkImageActor()
    image_actor.SetInputData(image_data)

    # Create a renderer to display the image in the background
    background_renderer = vtk.vtkRenderer()

    # Create a superquadric
    superquadric_source = vtk.vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(1.1)
    superquadric_source.SetThetaRoundness(.2)

    # Create a mapper and actor
    superquadric_mapper = vtk.vtkPolyDataMapper()
    superquadric_mapper.SetInputConnection(superquadric_source.GetOutputPort())

    superquadric_actor = vtk.vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)
    superquadric_actor.GetProperty().SetColor(colors.GetColor3d('NavajoWhite'))

    scene_renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()

    # Set up the render window and renderers such that there is
    # a background layer and a foreground layer
    background_renderer.SetLayer(0)
    background_renderer.InteractiveOff()
    scene_renderer.SetLayer(1)
    render_window.SetNumberOfLayers(2)
    render_window.AddRenderer(background_renderer)
    render_window.AddRenderer(scene_renderer)
    render_window.SetWindowName('BackgroundImage')

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # Add actors to the renderers
    scene_renderer.AddActor(superquadric_actor)
    background_renderer.AddActor(image_actor)

    # Render once to figure out where the background camera will be
    render_window.Render()

    # Set up the background camera to fill the renderer with the image
    origin = image_data.GetOrigin()
    spacing = image_data.GetSpacing()
    extent = image_data.GetExtent()

    camera = background_renderer.GetActiveCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
    # xd = (extent[1] - extent[0] + 1) * spacing[0]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    # Render again to set the correct view
    render_window.Render()

    # Interact with the window
    render_window_interactor.Start()
Ejemplo n.º 50
0
def main():
    # x = array of 8 3-tuples of float representing the vertices of a cube:
    x = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0),
         (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)]

    # pts = array of 6 4-tuples of vtkIdType (int) representing the faces
    #     of the cube in terms of the above vertices
    pts = [(0, 1, 2, 3), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5),
           (2, 3, 7, 6), (3, 0, 4, 7)]

    # We'll create the building blocks of polydata including data attributes.
    cube = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    polys = vtk.vtkCellArray()
    scalars = vtk.vtkFloatArray()

    # Load the point, cell, and data attributes.
    for i in range(8):
        points.InsertPoint(i, x[i])
    for i in range(6):
        polys.InsertNextCell(mkVtkIdList(pts[i]))
    for i in range(8):
        scalars.InsertTuple1(i, i)

    # We now assign the pieces to the vtkPolyData.
    cube.SetPoints(points)
    del points
    cube.SetPolys(polys)
    del polys
    cube.GetPointData().SetScalars(scalars)
    del scalars

    # Now we'll look at it.
    cubeMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        cubeMapper.SetInput(cube)
    else:
        cubeMapper.SetInputData(cube)
    cubeMapper.SetScalarRange(0, 7)
    cubeActor = vtk.vtkActor()
    cubeActor.SetMapper(cubeMapper)

    # The usual rendering stuff.
    camera = vtk.vtkCamera()
    camera.SetPosition(1, 1, 1)
    camera.SetFocalPoint(0, 0, 0)

    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

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

    renderer.AddActor(cubeActor)
    renderer.SetActiveCamera(camera)
    renderer.ResetCamera()
    renderer.SetBackground(1, 1, 1)

    renWin.SetSize(300, 300)

    # interact with data
    renWin.Render()
    iren.Start()

    # Clean up
    del cube
    del cubeMapper
    del cubeActor
    del camera
    del renderer
    del renWin
    del iren
def Main():
    global isovalues, contours, planeSource1, planeSource2, planeSource3, plane1, plane2, plane3, clipper1, clipper2, clipper3, clipX, clipY, clipZ, lut, renWin

    print "data: %s" % sys.argv[1]
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(sys.argv[1])
    reader.Update()
    
    print "gradientmag: %s" % sys.argv[2]
    gmreader = vtk.vtkStructuredPointsReader()
    gmreader.SetFileName(sys.argv[2])
    gmreader.Update()
    
    clipX = 0
    clipY = 0
    clipZ = 0
    
    r = reader.GetOutput().GetScalarRange()
    datamin = r[0]
    datamax = r[1]
    
    print "isoval: %s" % sys.argv[3]
    isovalues = loadIsovalueFile(sys.argv[3])
    
    lut = vtk.vtkColorTransferFunction()
    lut.SetColorSpaceToHSV()
    lut.AddHSVPoint(0,0,1,1)
    
    for i in range(4, len(sys.argv)):
        if sys.argv[i] == "--cmap":
            print "colors file: %s" % sys.argv[i+1]
            loadContinuousFile(sys.argv[i+1])
            updateUI(0)
        if sys.argv[i] == "--clip":
            print "clip (%s,%s,%s)" % (sys.argv[i+1],sys.argv[i+2],sys.argv[i+3])
            clipX = float(sys.argv[i+1])
            clipY = float(sys.argv[i+2])
            clipZ = float(sys.argv[i+3])
    
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(reader.GetOutputPort());
    contours.ComputeNormalsOn()
                         
    for i in range(0, len(isovalues)):
        contours.SetValue(i, isovalues[i])

    planeSource1 = vtk.vtkPlaneSource()
    planeSource1.SetNormal(1,0,0)
    planeSource1.SetOrigin(clipX,0,0)
    planeSource2 = vtk.vtkPlaneSource()
    planeSource2.SetNormal(0,1,0)
    planeSource2.SetOrigin(0,clipY,0)
    planeSource3 = vtk.vtkPlaneSource()
    planeSource3.SetNormal(0,0,1)
    planeSource3.SetOrigin(0,0,clipZ)

    plane1 = vtk.vtkPlane()
    plane1.SetNormal(planeSource1.GetNormal())
    plane1.SetOrigin(planeSource1.GetOrigin())
    clipper1 = vtk.vtkClipPolyData()
    clipper1.SetClipFunction(plane1)
    clipper1.SetInputConnection(contours.GetOutputPort())
    clipper1.Update()

    plane2 = vtk.vtkPlane()
    plane2.SetNormal(planeSource2.GetNormal())
    plane2.SetOrigin(planeSource2.GetOrigin())
    clipper2 = vtk.vtkClipPolyData()
    clipper2.SetClipFunction(plane2)
    clipper2.SetInputConnection(clipper1.GetOutputPort())
    clipper2.Update()

    plane3 = vtk.vtkPlane()
    plane3.SetNormal(planeSource3.GetNormal())
    plane3.SetOrigin(planeSource3.GetOrigin())
    clipper3 = vtk.vtkClipPolyData()
    clipper3.SetClipFunction(plane3)
    clipper3.SetInputConnection(clipper2.GetOutputPort())
    clipper3.Update()

    probeFilter = vtk.vtkProbeFilter()
    probeFilter.SetInputConnection(0, clipper3.GetOutputPort())
    probeFilter.SetInputConnection(1, gmreader.GetOutputPort())
    probeFilter.Update()

    clipperMapper = vtk.vtkPolyDataMapper()
    clipperMapper.SetLookupTable(lut)
    clipperMapper.SetInputConnection(probeFilter.GetOutputPort())
    clipperMapper.SetScalarRange(probeFilter.GetOutput().GetScalarRange())

    colorBar = vtkScalarBarActor()
    colorBar.SetLookupTable(clipperMapper.GetLookupTable())
    colorBar.SetTitle("gradient magnitude")
    colorBar.SetNumberOfLabels(6)
    colorBar.SetLabelFormat("%4.0f")
    colorBar.SetPosition(0.9, 0.1)
    colorBar.SetWidth(0.1)
    colorBar.SetHeight(0.7)

    clipperActor=vtk.vtkActor()
    clipperActor.GetProperty().SetRepresentationToWireframe()
    clipperActor.SetMapper(clipperMapper)

    backFaces = vtk.vtkProperty()
    backFaces.SetSpecular(0)
    backFaces.SetDiffuse(0)
    backFaces.SetAmbient(0)
    backFaces.SetAmbientColor(1,0,0)
    clipperActor.SetBackfaceProperty(backFaces)

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    ren.AddActor(clipperActor)
    ren.AddActor(colorBar)
    ren.ResetCamera()
    ren.SetBackground(0.2,0.3,0.4)
    ren.ResetCameraClippingRange()
    renWin.SetSize(1200, 600)

    clipXSlider = vtk.vtkSliderRepresentation2D()
    clipXSlider.SetMinimumValue(0)
    clipXSlider.SetMaximumValue(300)
    clipXSlider.SetValue(clipX)
    clipXSlider.SetTitleText("X")
    clipXSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipXSlider.GetPoint1Coordinate().SetValue(0.0, 0.3)
    clipXSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipXSlider.GetPoint2Coordinate().SetValue(0.2, 0.3)
    clipXSlider.SetSliderLength(0.02)
    clipXSlider.SetSliderWidth(0.03)
    clipXSlider.SetEndCapLength(0.01)
    clipXSlider.SetEndCapWidth(0.03)
    clipXSlider.SetTubeWidth(0.005)
    clipXSlider.SetLabelFormat("%1.2lf")
    clipXSlider.SetTitleHeight(0.02)
    clipXSlider.SetLabelHeight(0.02)
    SliderWidget2 = vtk.vtkSliderWidget()
    SliderWidget2.SetInteractor(iren)
    SliderWidget2.SetRepresentation(clipXSlider)
    SliderWidget2.KeyPressActivationOff()
    SliderWidget2.SetAnimationModeToAnimate()
    SliderWidget2.SetEnabled(True)
    SliderWidget2.AddObserver("InteractionEvent", clipXSliderHandler)

    clipYSlider = vtk.vtkSliderRepresentation2D()
    clipYSlider.SetMinimumValue(0)
    clipYSlider.SetMaximumValue(300)
    clipYSlider.SetValue(clipY)
    clipYSlider.SetTitleText("Y")
    clipYSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipYSlider.GetPoint1Coordinate().SetValue(0.0, 0.2)
    clipYSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipYSlider.GetPoint2Coordinate().SetValue(0.2, 0.2)
    clipYSlider.SetSliderLength(0.02)
    clipYSlider.SetSliderWidth(0.03)
    clipYSlider.SetEndCapLength(0.01)
    clipYSlider.SetEndCapWidth(0.03)
    clipYSlider.SetTubeWidth(0.005)
    clipYSlider.SetLabelFormat("%1.2lf")
    clipYSlider.SetTitleHeight(0.02)
    clipYSlider.SetLabelHeight(0.02)
    SliderWidget3 = vtk.vtkSliderWidget()
    SliderWidget3.SetInteractor(iren)
    SliderWidget3.SetRepresentation(clipYSlider)
    SliderWidget3.KeyPressActivationOff()
    SliderWidget3.SetAnimationModeToAnimate()
    SliderWidget3.SetEnabled(True)
    SliderWidget3.AddObserver("InteractionEvent", clipYSliderHandler)

    clipZSlider = vtk.vtkSliderRepresentation2D()
    clipZSlider.SetMinimumValue(0)
    clipZSlider.SetMaximumValue(300)
    clipZSlider.SetValue(clipZ)
    clipZSlider.SetTitleText("Z")
    clipZSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipZSlider.GetPoint1Coordinate().SetValue(0.0, 0.1)
    clipZSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipZSlider.GetPoint2Coordinate().SetValue(0.2, 0.1)
    clipZSlider.SetSliderLength(0.02)
    clipZSlider.SetSliderWidth(0.03)
    clipZSlider.SetEndCapLength(0.01)
    clipZSlider.SetEndCapWidth(0.03)
    clipZSlider.SetTubeWidth(0.005)
    clipZSlider.SetLabelFormat("%1.2lf")
    clipZSlider.SetTitleHeight(0.02)
    clipZSlider.SetLabelHeight(0.02)
    SliderWidget4 = vtk.vtkSliderWidget()
    SliderWidget4.SetInteractor(iren)
    SliderWidget4.SetRepresentation(clipZSlider)
    SliderWidget4.KeyPressActivationOff()
    SliderWidget4.SetAnimationModeToAnimate()
    SliderWidget4.SetEnabled(True)
    SliderWidget4.AddObserver("InteractionEvent", clipZSliderHandler)

    # Render
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 52
0
def main():
    red_ball = 0
    blue_ball = 0
    white_ball = 0
    balls_coordinates = []
    balls_coordinates_and_color = []
    sphereSource = []
    actor = []
    mapper = []
    balls_numbers = random.randint(3, 20)
    # Read STL
    reader1 = vtk.vtkSTLReader()
    reader1.SetFileName("golf_robot.stl")

    # Create a mapper and actor
    mapper111 = vtk.vtkPolyDataMapper()
    mapper111.SetInputConnection(reader1.GetOutputPort())
    actor111 = vtk.vtkActor()
    actor111.SetMapper(mapper111)
    prop = actor111.GetProperty()

    for a in range(balls_numbers):
        b = "sphereSource" + str(a)
        sphereSource.append(b)
        c = "actor" + str(a)
        actor.append(c)
        d = "mapper" + str(a)
        mapper.append(d)

        balls_coordinates_x = random.randint(1, 10) * 20
        balls_coordinates_y = random.randint(1, 10) * 20
        balls_color = random.randint(1, 3)
        if balls_color == 1:
            red_ball = red_ball + 1
        elif balls_color == 2:
            blue_ball = blue_ball + 1
        elif balls_color == 3:
            white_ball = white_ball + 1
        balls = [balls_coordinates_x, balls_coordinates_y, 0]
        balls_and_color = [
            balls_coordinates_x, balls_coordinates_y, 0, balls_color
        ]
        balls_coordinates.append(balls)
        balls_coordinates_and_color.append(balls_and_color)

    print('balls =', balls_numbers, 'red balls =', red_ball, 'blue balls =',
          blue_ball, 'white balls =', white_ball)
    print(balls_coordinates_and_color)

    for i in range(balls_numbers):
        sphereSource[i] = vtk.vtkSphereSource()
        sphereSource[i].SetCenter(balls_coordinates[i][0:3])
        sphereSource[i].SetRadius(10)
        sphereSource[i].SetThetaResolution(64)
        sphereSource[i].SetPhiResolution(64)

        # Create a mapper and actor
        mapper[i] = vtk.vtkPolyDataMapper()
        mapper[i].SetInputConnection(sphereSource[i].GetOutputPort())
        actor[i] = vtk.vtkActor()
        actor[i].SetMapper(mapper[i])
        if balls_coordinates_and_color[i][3] == 1:
            prop = actor[i].GetProperty().SetColor(1, 0, 0)  #红
        elif balls_coordinates_and_color[i][3] == 2:
            prop = actor[i].GetProperty().SetColor(0, 0, 1)  #蓝
        elif balls_coordinates_and_color[i][3] == 3:
            prop = actor[i].GetProperty()  #白

    # Setup a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    for a in range(balls_numbers):
        # Add the actor to the scene
        renderer.AddActor(actor[a])
    renderer.AddActor(actor111)
    renderer.SetBackground(0, 1, 0)  # Background color white

    actor111.SetOrigin(0, 0, 0)

    # Render and interact
    renderWindow.Render()

    # Initialize must be called prior to creating timer events.
    renderWindowInteractor.Initialize()

    # Sign up to receive TimerEvent
    cb = vtkTimerCallback1()
    cb.actors.append(actor111)
    cb.actors.append(balls_numbers)
    for i in range(balls_numbers):
        cb.balls.append(balls_coordinates_and_color[i])
        cb.mballs.append(actor[i])
    renderWindowInteractor.AddObserver('TimerEvent', cb.execute)
    timerId = renderWindowInteractor.CreateRepeatingTimer(100)

    # start the interaction and timer
    renderWindowInteractor.Start()
Ejemplo n.º 53
0
def main():
    colors = vtk.vtkNamedColors()

    fileName = get_program_parameters()

    # Create a rendering window, renderer and interactor.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(780, 780)
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Make an annotated cube actor with axes and then add it into an orientation marker widget.
    # Three of these need to be made.

    # Right Posterior Superior
    xyzLabels = ['X', 'Y', 'Z']
    scale = [1.5, -1.5, 1.5]
    axes = MakeCubeActor(scale, xyzLabels, colors)
    om = vtk.vtkOrientationMarkerWidget()
    om.SetOrientationMarker(axes)
    # Position upper left in the viewport.
    om.SetViewport(0.0, 0.8, 0.2, 1.0)
    om.SetInteractor(iren)
    om.EnabledOn()
    om.InteractiveOn()

    # Right, Anterior, Superior.
    scale = [1.5, 1.5, 1.5]
    axes1 = MakeCubeActor(scale, xyzLabels, colors)
    om1 = vtk.vtkOrientationMarkerWidget()
    om1.SetOrientationMarker(axes1)
    # Position lower left in the viewport.
    om1.SetViewport(0, 0, 0.2, 0.2)
    om1.SetInteractor(iren)
    om1.EnabledOn()
    om1.InteractiveOn()

    # Left, Posterior, Superior.
    scale = (-1.5, -1.5, 1.5)
    axes2 = MakeCubeActor(scale, xyzLabels, colors)
    om2 = vtk.vtkOrientationMarkerWidget()
    om2.SetOrientationMarker(axes2)
    # Position lower right in the viewport.
    om2.SetViewport(0.8, 0, 1.0, 0.2)
    om2.SetInteractor(iren)
    om2.EnabledOn()
    om2.InteractiveOn()

    # Finally create an annotated cube actor adding it into an orientation marker widget.
    axes3 = MakeAnnotatedCubeActor(colors)
    om3 = vtk.vtkOrientationMarkerWidget()
    om3.SetOrientationMarker(axes3)
    # Position upper right in the viewport.
    om3.SetViewport(0.8, 0.8, 1.0, 1.0)
    om3.SetInteractor(iren)
    om3.EnabledOn()
    om3.InteractiveOn()

    # Read in the model.
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(fileName)
    reader.Update()

    humanMapper = vtk.vtkPolyDataMapper()
    humanMapper.SetInputConnection(reader.GetOutputPort())
    humanMapper.SetScalarModeToUsePointFieldData()
    humanMapper.SelectColorArray("Color")
    humanMapper.SetColorModeToDirectScalars()

    humanActor = vtk.vtkActor()
    humanActor.SetMapper(humanMapper)
    bounds = humanActor.GetBounds()
    # Scale the actor
    humanActor.SetScale(1.0 / max(bounds))
    ren.AddActor(humanActor)

    # Make the planes.
    actors = MakePlanesActors(colors)
    for actor in actors:
        ren.AddViewProp(actor)
    # Label them.
    textActors = AddTextToPlanes()
    for actor in textActors:
        ren.AddViewProp(actor)

    # Interact
    ren.SetBackground2(colors.GetColor3d('OldLace'))
    ren.SetBackground(colors.GetColor3d('MistyRose'))
    ren.GradientBackgroundOn()
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(1.6)
    ren.GetActiveCamera().SetPosition(-2.3, 4.1, 4.2)
    # ren.GetActiveCamera().SetPosition(-3.4, 5.5, 0.0)
    ren.GetActiveCamera().SetViewUp(0.0, 0.0, 1.0)
    ren.ResetCameraClippingRange()
    renWin.Render()
    # Call SetWindowName after renWin.Render() is called.
    renWin.SetWindowName("Anatomical Orientation")

    iren.Initialize()
    iren.Start()
Ejemplo n.º 54
0
def DisplayCone(nc):
    '''
    Create a cone, contour it using the banded contour filter and
        color it with the primary additive and subtractive colors.
    :param: nc: The vtkNamedColor class
    :return: The render window interactor.
    '''
    # Create a cone
    coneSource = vtk.vtkConeSource()
    coneSource.SetCenter(0.0, 0.0, 0.0)
    coneSource.SetRadius(5.0)
    coneSource.SetHeight(10)
    coneSource.SetDirection(0,1,0)
    coneSource.Update()

    bounds = [1.0,-1.0,1.0,-1.0,1.0,-1.0]
    coneSource.GetOutput().GetBounds(bounds)

    elevation = vtk.vtkElevationFilter()
    elevation.SetInputConnection(coneSource.GetOutputPort())
    elevation.SetLowPoint(0,bounds[2],0)
    elevation.SetHighPoint(0,bounds[3],0)

    bcf = vtk.vtkBandedPolyDataContourFilter()
    bcf.SetInputConnection(elevation.GetOutputPort())
    bcf.SetScalarModeToValue()
    bcf.GenerateContourEdgesOn()
    bcf.GenerateValues(7,elevation.GetScalarRange())

    # Build a simple lookup table of
    # primary additive and subtractive colors.
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(7)
    # Test setting and getting a color here.
    # We are also modifying alpha.

    # Convert to a list so that
    # SetColor(name,rgba) works.
    rgba = list(nc.GetColor4d("Red"))
    rgba[3] = 0.5
    nc.SetColor("My Red",rgba)
    rgba = nc.GetColor4d("My Red")
    lut.SetTableValue(0,rgba)
    # Does "My Red" match anything?
    match = FindSynonyms(nc,"My Red")
    print "Matching colors to My Red:", match

    rgba = nc.GetColor4d("DarkGreen")
    rgba[3] = 0.3
    lut.SetTableValue(1,rgba)
    #  Alternatively we can use our wrapper functions:
    lut.SetTableValue(2,nc.GetColor4d("Blue"))
    lut.SetTableValue(3,nc.GetColor4d("Cyan"))
    lut.SetTableValue(4,nc.GetColor4d("Magenta"))
    lut.SetTableValue(5,nc.GetColor4d("Yellow"))
    lut.SetTableValue(6,nc.GetColor4d("White"))
    lut.SetTableRange(elevation.GetScalarRange())
    lut.Build()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(bcf.GetOutputPort())
    mapper.SetLookupTable(lut)
    mapper.SetScalarModeToUseCellData()

    contourLineMapper = vtk.vtkPolyDataMapper()
    contourLineMapper.SetInputData(bcf.GetContourEdgesOutput())
    contourLineMapper.SetScalarRange(elevation.GetScalarRange())
    contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset()

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

    contourLineActor = vtk.vtkActor()
    actor.SetMapper(mapper)
    contourLineActor.SetMapper(contourLineMapper)
    contourLineActor.GetProperty().SetColor(
        nc.GetColor3d("black"))

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.AddActor(contourLineActor)
    renderer.SetBackground(
        nc.GetColor3d("SteelBlue"))

    renderWindow.Render()

    fnsave = "TestNamedColorsIntegration.png"
    renLgeIm = vtk.vtkRenderLargeImage()
    imgWriter = vtk.vtkPNGWriter()
    renLgeIm.SetInput(renderer)
    renLgeIm.SetMagnification(1)
    imgWriter.SetInputConnection(renLgeIm.GetOutputPort())
    imgWriter.SetFileName(fnsave)
    imgWriter.Write()

    return renderWindowInteractor
Ejemplo n.º 55
0
    def CurvaturesDemo(self):

        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource()
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution(64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness(1)
        torus.SetThickness(0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1)

        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)

        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)

        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())

        # The quadric has nasty discontinuities from the way the edges are generated
        # so let's pass it though a CleanPolyDataFilter and merge any points which
        # are coincident, or very close

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)

        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)

        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)

        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0))

        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()

        curvatures = list()
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()

        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        names = [
            'Torus - Gaussian Curvature', 'Torus - Mean Curvature',
            'Gaussian Curvature', 'Mean Curvature'
        ]

        # Link the pipeline together.
        for idx, item in enumerate(sources):
            sources[idx].Update()

            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 2

        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)

        rendererSize = 300

        # Create the RenderWindow
        #
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(rendererSize * gridDimensions,
                             rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - (row + 1)) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - row) * rendererSize /
                    (gridDimensions * rendererSize))

                if idx > (len(sources) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                renderWindow.AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4, 0.3, 0.2)

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

        renderWindow.Render()

        interactor.Start()
Ejemplo n.º 56
0
def main():
    # Setting Paths
    cam = 2

    # dataset_dir = '/media/bradenhurl/hd/gta/object/'
    data_set = 'training'
    dataset_dir = os.path.expanduser('~') + '/wavedata-dev/demos/gta'
    #dataset_dir = os.path.expanduser('~') + '/Kitti/object/'
    dataset_dir = os.path.expanduser(
        '~') + '/GTAData/TruPercept/object_tru_percept8/'

    #Set to true to see predictions (results) from all perspectives
    use_results = True
    altPerspective = False
    perspID = 48133
    perspStr = '%07d' % perspID
    altPerspect_dir = os.path.join(dataset_dir, data_set + '/alt_perspective/')
    if altPerspective:
        data_set = data_set + '/alt_perspective/' + perspStr

    fromWiseWindows = False
    useEVE = False
    if fromWiseWindows:
        data_set = 'object'
        if useEVE:
            dataset_dir = '/media/bradenhurl/hd/data/eve/'
        else:
            dataset_dir = '/media/bradenhurl/hd/data/'
    image_dir = os.path.join(dataset_dir, data_set) + '/image_2'
    velo_dir = os.path.join(dataset_dir, data_set) + '/velodyne'
    calib_dir = os.path.join(dataset_dir, data_set) + '/calib'

    if use_results:
        label_dir = os.path.join(dataset_dir, data_set) + '/predictions'
    else:
        label_dir = os.path.join(dataset_dir, data_set) + '/label_2'

    base_dir = os.path.join(dataset_dir, data_set)

    comparePCs = False
    if comparePCs:
        velo_dir2 = os.path.join(dataset_dir, data_set) + '/velodyne'

    tracking = False
    if tracking:
        seq_idx = 1
        data_set = '%04d' % seq_idx
        dataset_dir = '/media/bradenhurl/hd/GTAData/August-01/tracking'
        image_dir = os.path.join(dataset_dir, 'images', data_set)
        label_dir = os.path.join(dataset_dir, 'labels', data_set)
        velo_dir = os.path.join(dataset_dir, 'velodyne', data_set)
        calib_dir = os.path.join(dataset_dir, 'training', 'calib', '0000')

    #Used for visualizing inferences
    #label_dir = '/media/bradenhurl/hd/avod/avod/data/outputs/pyramid_people_gta_40k'
    #label_dir = label_dir + '/predictions/kitti_predictions_3d/test/0.02/154000/data/'

    closeView = False
    pitch = 170
    pointSize = 3
    zoom = 1
    if closeView:
        pitch = 180.5
        pointSize = 3
        zoom = 35

    image_list = os.listdir(image_dir)

    fulcrum_of_points = True
    use_intensity = False
    img_idx = 2

    print('=== Loading image: {:06d}.png ==='.format(img_idx))
    print(image_dir)

    image = cv2.imread(image_dir + '/{:06d}.png'.format(img_idx))
    image_shape = (image.shape[1], image.shape[0])

    if use_intensity:
        point_cloud, intensity = obj_utils.get_lidar_point_cloud(
            img_idx, calib_dir, velo_dir, ret_i=use_intensity)
    else:
        point_cloud = obj_utils.get_lidar_point_cloud(img_idx,
                                                      calib_dir,
                                                      velo_dir,
                                                      im_size=image_shape)

    if comparePCs:
        point_cloud2 = obj_utils.get_lidar_point_cloud(img_idx,
                                                       calib_dir,
                                                       velo_dir2,
                                                       im_size=image_shape)
        point_cloud = np.hstack((point_cloud, point_cloud2))

    # Reshape points into N x [x, y, z]
    all_points = np.array(point_cloud).transpose().reshape((-1, 3))

    # Define Fixed Sizes for the voxel grid
    x_min = -85
    x_max = 85
    y_min = -5
    y_max = 5
    z_min = 3
    z_max = 85

    x_min = min(point_cloud[0])
    x_max = max(point_cloud[0])
    y_min = min(point_cloud[1])
    y_max = max(point_cloud[1])
    #z_min = min(point_cloud[2])
    z_max = max(point_cloud[2])

    # Filter points within certain xyz range
    area_filter = (point_cloud[0] > x_min) & (point_cloud[0] < x_max) & \
                  (point_cloud[1] > y_min) & (point_cloud[1] < y_max) & \
                  (point_cloud[2] > z_min) & (point_cloud[2] < z_max)

    all_points = all_points[area_filter]

    #point_colours = np.zeros(point_cloud.shape[1],0)
    #print(point_colours.shape)

    if fulcrum_of_points:
        # Get point colours
        point_colours = vis_utils.project_img_to_point_cloud(
            all_points, image, calib_dir, img_idx)
        print("Point colours shape: ", point_colours.shape)
        print("Sample 0 of colour: ", point_colours[0])
    elif use_intensity:
        adjusted = intensity == 65535
        intensity = intensity > 0
        intensity = np.expand_dims(intensity, -1)
        point_colours = np.hstack(
            (intensity * 255, intensity * 255 - adjusted * 255,
             intensity * 255 - adjusted * 255))
        print("Intensity shape:", point_colours.shape)
        print("Intensity sample: ", point_colours[0])

    # Create Voxel Grid
    voxel_grid = VoxelGrid()
    voxel_grid_extents = [[x_min, x_max], [y_min, y_max], [z_min, z_max]]
    print(voxel_grid_extents)

    start_time = time.time()
    voxel_grid.voxelize(all_points, 0.2, voxel_grid_extents)
    end_time = time.time()
    print("Voxelized in {} s".format(end_time - start_time))

    # Get bounding boxes
    gt_detections = obj_utils.read_labels(label_dir,
                                          img_idx,
                                          results=use_results)
    if gt_detections is None:
        gt_detections = []

    #perspective_utils.to_world(gt_detections, base_dir, img_idx)
    #perspective_utils.to_perspective(gt_detections, base_dir, img_idx)
    for entity_str in os.listdir(altPerspect_dir):
        if os.path.isdir(os.path.join(altPerspect_dir, entity_str)):
            perspect_detections = perspective_utils.get_detections(
                base_dir,
                altPerspect_dir,
                img_idx,
                perspID,
                entity_str,
                results=use_results)
            if perspect_detections != None:
                if use_results:
                    stripped_detections = trust_utils.strip_objs(
                        perspect_detections)
                    gt_detections = gt_detections + stripped_detections
                else:
                    gt_detections = gt_detections + perspect_detections

    # Create VtkPointCloud for visualization
    vtk_point_cloud = VtkPointCloud()
    if fulcrum_of_points or use_intensity:
        vtk_point_cloud.set_points(all_points, point_colours)
    else:
        vtk_point_cloud.set_points(all_points)
    vtk_point_cloud.vtk_actor.GetProperty().SetPointSize(pointSize)

    # Create VtkVoxelGrid for visualization
    vtk_voxel_grid = VtkVoxelGrid()
    vtk_voxel_grid.set_voxels(voxel_grid)

    COLOUR_SCHEME_PAPER = {
        "Car": (0, 0, 255),  # Blue
        "Pedestrian": (255, 0, 0),  # Red
        "Bus": (0, 0, 255),  #Blue
        "Cyclist": (150, 50, 100),  # Purple
        "Van": (255, 150, 150),  # Peach
        "Person_sitting": (150, 200, 255),  # Sky Blue
        "Truck": (0, 0, 255),  # Light Grey
        "Tram": (150, 150, 150),  # Grey
        "Misc": (100, 100, 100),  # Dark Grey
        "DontCare": (255, 255, 255),  # White
    }

    # Create VtkBoxes for boxes
    vtk_boxes = VtkBoxes()
    vtk_boxes.set_objects(gt_detections,
                          COLOUR_SCHEME_PAPER)  #vtk_boxes.COLOUR_SCHEME_KITTI)

    # Create Axes
    axes = vtk.vtkAxesActor()
    axes.SetTotalLength(5, 5, 5)

    # Create Voxel Grid Renderer in bottom half
    vtk_renderer = vtk.vtkRenderer()
    vtk_renderer.AddActor(vtk_point_cloud.vtk_actor)
    vtk_renderer.AddActor(vtk_voxel_grid.vtk_actor)
    vtk_renderer.AddActor(vtk_boxes.vtk_actor)
    #vtk_renderer.AddActor(axes)
    vtk_renderer.SetBackground(0.2, 0.3, 0.4)

    # Setup Camera
    current_cam = vtk_renderer.GetActiveCamera()
    current_cam.Pitch(pitch)
    current_cam.Roll(180.0)

    # Zooms out to fit all points on screen
    vtk_renderer.ResetCamera()

    # Zoom in slightly
    current_cam.Zoom(zoom)

    # Reset the clipping range to show all points
    vtk_renderer.ResetCameraClippingRange()

    # Setup Render Window
    vtk_render_window = vtk.vtkRenderWindow()
    vtk_render_window.SetWindowName(
        "Point Cloud and Voxel Grid, Image {}".format(img_idx))
    vtk_render_window.SetSize(1920, 1080)
    vtk_render_window.AddRenderer(vtk_renderer)

    # Setup custom interactor style, which handles mouse and key events
    vtk_render_window_interactor = vtk.vtkRenderWindowInteractor()
    vtk_render_window_interactor.SetRenderWindow(vtk_render_window)

    # Add custom interactor to toggle actor visibilities

    vtk_render_window_interactor.SetInteractorStyle(
        vis_utils.ToggleActorsInteractorStyle([
            vtk_point_cloud.vtk_actor,
            vtk_voxel_grid.vtk_actor,
            vtk_boxes.vtk_actor,
        ]))

    # Show image
    image = cv2.imread(image_dir + "/%06d.png" % img_idx)
    cv2.imshow("Press any key to continue", image)
    cv2.waitKey()

    # Render in VTK
    vtk_render_window.Render()
    vtk_render_window_interactor.Start()  # Blocking
Ejemplo n.º 57
0
def main():
    inputFilename = 'element_labels_input.vtk'

    # read file
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(inputFilename)
    reader.ReadAllScalarsOn()
    reader.SetScalarsName(reader.GetScalarsNameInFile(0))
    reader.Update()

    ncells = reader.GetOutput().GetNumberOfCells()
    npoints = reader.GetOutput().GetNumberOfPoints()

    # get attributes
    ugrid = reader.GetOutput()
    cell_data = ugrid.GetCellData()
    point_data = ugrid.GetPointData()
    cell_scalars = cell_data.GetScalars(reader.GetScalarsNameInFile(0))

    # validate that attributes are read correctly
    print('name0:')
    for i in range(ncells):
        print(i, ": ", cell_scalars.GetComponent(i, 0))

    cell_scalars = cell_data.GetScalars(reader.GetScalarsNameInFile(1))
    print('\nname1:')
    for i in range(ncells):
        print(i, ": ", cell_scalars.GetComponent(i, 0))

    point_scalars = point_data.GetScalars(reader.GetScalarsNameInFile(0))
    print(point_scalars)
    print('\nname2:')
    for i in range(npoints):
        print(i, ": ", point_scalars.GetComponent(i, 0))
    #point_scalars = cell_data.GetScalars(reader.GetScalarsNameInFile(2))
    #print(point_scalars)

    # geometry filter
    geometry_filter = vtk.vtkUnstructuredGridGeometryFilter()
    geometry_filter.SetInputConnection(reader.GetOutputPort())
    geometry_filter.Update()

    # Generate data arrays containing point and cell ids
    ids = vtk.vtkIdFilter()
    ids.SetInputConnection(geometry_filter.GetOutputPort())
    ids.PointIdsOff()
    ids.CellIdsOff()
    ids.FieldDataOn()

    # Create labels for cells
    cell_centers = vtk.vtkCellCenters()
    cell_centers.SetInputConnection(ids.GetOutputPort())

    node_points = vtk.vtkVertexGlyphFilter()
    node_points.SetInputConnection(ids.GetOutputPort())
    node_points.Update()
    #node_points = vtk.vtkPointCentered()
    #node_points.SetInputConnection(ids.GetOutputPort())

    # lut
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(ncells)
    lut.Build()
    lut.SetTableValue(0, 1, 0, 0, 1)  # red.
    lut.SetTableValue(1, 0, 1, 0, 1)  # green.
    lut.SetTableValue(2, 0, 0, 1, 1)  # blue.

    # mapper
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(geometry_filter.GetOutputPort())
    mapper.SetScalarVisibility(1)
    if apply_colors:
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUseCellData()
        mapper.SetScalarRange(11, 13)
    mapper.GetInput().GetCellData().SetActiveScalars("cell_tag")

    # label mapper
    cell_label_mapper = vtk.vtkLabeledDataMapper()
    cell_label_mapper.SetInputConnection(cell_centers.GetOutputPort())
    cell_label_mapper.SetLabelModeToLabelScalars()

    #point_label_mapper = vtk.vtkLabeledDataMapper()
    #point_label_mapper.SetInputConnection(node_points.GetOutputPort())
    #point_label_mapper.SetLabelModeToLabelScalars()

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetRepresentationToWireframe()

    # label actor
    cell_label_actor = vtk.vtkActor2D()
    cell_label_actor.SetMapper(cell_label_mapper)

    #point_label_actor = vtk.vtkActor2D()
    #point_label_actor.SetMapper(point_label_mapper)

    # renderer
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(actor)
    renderer.AddActor(cell_label_actor)
    #renderer.AddActor(point_label_actor)
    renderWindow.Render()
    renderWindowInteractor.Start()
Ejemplo n.º 58
0
def main():
    xyzFn, qFn = get_program_parameters()
    colors = vtk.vtkNamedColors()

    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(xyzFn)
    pl3d.SetQFileName(qFn)
    pl3d.SetScalarFunctionNumber(100)
    pl3d.SetVectorFunctionNumber(202)
    pl3d.Update()

    pl3dOutput = pl3d.GetOutput().GetBlock(0)

    plane = vtk.vtkStructuredGridGeometryFilter()
    plane.SetInputData(pl3dOutput)
    plane.SetExtent(1, 100, 1, 100, 7, 7)

    lut = vtk.vtkLookupTable()

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetLookupTable(lut)
    planeMapper.SetInputConnection(plane.GetOutputPort())
    planeMapper.SetScalarRange(pl3dOutput.GetScalarRange())

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)

    # This creates an outline around the data.

    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(pl3dOutput)

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)

    # Much of the following is commented out. To try different lookup tables,
    # uncomment the appropriate portions.
    #

    # This creates a black to white lut.
    # lut.SetHueRange(0, 0)
    # lut.SetSaturationRange(0, 0)
    # lut.SetValueRange(0.2, 1.0)

    # This creates a red to blue lut.
    # lut.SetHueRange(0.0, 0.667)

    # This creates a blue to red lut.
    # lut.SetHueRange(0.667, 0.0)

    # This creates a weird effect. The Build() method causes the lookup table
    # to allocate memory and create a table based on the correct hue, saturation,
    # value, and alpha (transparency) range. Here we then manually overwrite the
    # values generated by the Build() method.
    lut.SetNumberOfColors(256)
    lut.SetHueRange(0.0, 0.667)
    lut.Build()

    # Create the RenderWindow, Renderer and both Actors.
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    #
    ren1.AddActor(outlineActor)
    ren1.AddActor(planeActor)

    ren1.SetBackground(colors.GetColor3d("SlateGray"))
    ren1.TwoSidedLightingOff()

    renWin.SetSize(512, 512)

    iren.Initialize()

    cam1 = ren1.GetActiveCamera()
    cam1.SetClippingRange(3.95297, 50)
    cam1.SetFocalPoint(8.88908, 0.595038, 29.3342)
    cam1.SetPosition(-12.3332, 31.7479, 41.2387)
    cam1.SetViewUp(0.060772, -0.319905, 0.945498)

    iren.Start()
Ejemplo n.º 59
0
renderer0 = vtk.vtkRenderer()
renderer0.SetViewport(0., 0., 0.5, 1.)

renderer1 = vtk.vtkRenderer()
renderer1.SetViewport(0.5, 0., 1., 1.)

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(CreateCross(20.0))
global _Cross
_Cross = vtk.vtkActor()
_Cross.GetProperty().SetLineWidth(5)
_Cross.SetPosition(0.0, 50.006, 0.0)
_Cross.SetMapper(mapper)

global renderWindow
renderWindow = vtk.vtkRenderWindow()
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

camera = vtk.vtkCamera()

renderWindow.AddRenderer(renderer1)
renderWindow.AddRenderer(renderer0)  # This the active renderer

imageStyle = vtk.vtkInteractorStyleImage()
imageStyle.SetDefaultRenderer(renderer1)

switchStyle = vtk.vtkInteractorStyleSwitch()
switchStyle.SetDefaultRenderer(renderer0)

renderWindowInteractor.SetInteractorStyle(switchStyle)
Ejemplo n.º 60
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the RenderWindow, Renderer and Interactor.
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Generate the tensors.
    ptLoad = vtk.vtkPointLoad()
    ptLoad.SetLoadValue(100.0)
    ptLoad.SetSampleDimensions(20, 20, 20)
    ptLoad.ComputeEffectiveStressOn()
    ptLoad.SetModelBounds(-10, 10, -10, 10, -10, 10)
    ptLoad.Update()

    # Generate the hyperstreamlines.
    s1 = vtk.vtkHyperStreamline()
    s1.SetInputData(ptLoad.GetOutput())
    s1.SetStartPosition(9, 9, -9)
    s1.IntegrateMinorEigenvector()
    s1.SetMaximumPropagationDistance(18.0)
    s1.SetIntegrationStepLength(0.1)
    s1.SetStepLength(0.01)
    s1.SetRadius(0.25)
    s1.SetNumberOfSides(18)
    s1.SetIntegrationDirectionToIntegrateBothDirections()
    s1.Update()

    # Map the hyperstreamlines.
    lut = vtk.vtkLogLookupTable()
    lut.SetHueRange(.6667, 0.0)

    s1Mapper = vtk.vtkPolyDataMapper()
    s1Mapper.SetInputConnection(s1.GetOutputPort())
    s1Mapper.SetLookupTable(lut)
    s1Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s1Actor = vtk.vtkActor()
    s1Actor.SetMapper(s1Mapper)

    s2 = vtk.vtkHyperStreamline()
    s2.SetInputData(ptLoad.GetOutput())
    s2.SetStartPosition(-9, -9, -9)
    s2.IntegrateMinorEigenvector()
    s2.SetMaximumPropagationDistance(18.0)
    s2.SetIntegrationStepLength(0.1)
    s2.SetStepLength(0.01)
    s2.SetRadius(0.25)
    s2.SetNumberOfSides(18)
    s2.SetIntegrationDirectionToIntegrateBothDirections()
    s2.Update()

    s2Mapper = vtk.vtkPolyDataMapper()
    s2Mapper.SetInputConnection(s2.GetOutputPort())
    s2Mapper.SetLookupTable(lut)
    s2Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s2Actor = vtk.vtkActor()
    s2Actor.SetMapper(s2Mapper)

    s3 = vtk.vtkHyperStreamline()
    s3.SetInputData(ptLoad.GetOutput())
    s3.SetStartPosition(9, -9, -9)
    s3.IntegrateMinorEigenvector()
    s3.SetMaximumPropagationDistance(18.0)
    s3.SetIntegrationStepLength(0.1)
    s3.SetStepLength(0.01)
    s3.SetRadius(0.25)
    s3.SetNumberOfSides(18)
    s3.SetIntegrationDirectionToIntegrateBothDirections()
    s3.Update()

    s3Mapper = vtk.vtkPolyDataMapper()
    s3Mapper.SetInputConnection(s3.GetOutputPort())
    s3Mapper.SetLookupTable(lut)
    s3Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s3Actor = vtk.vtkActor()
    s3Actor.SetMapper(s3Mapper)

    s4 = vtk.vtkHyperStreamline()
    s4.SetInputData(ptLoad.GetOutput())
    s4.SetStartPosition(-9, 9, -9)
    s4.IntegrateMinorEigenvector()
    s4.SetMaximumPropagationDistance(18.0)
    s4.SetIntegrationStepLength(0.1)
    s4.SetStepLength(0.01)
    s4.SetRadius(0.25)
    s4.SetNumberOfSides(18)
    s4.SetIntegrationDirectionToIntegrateBothDirections()
    s4.Update()

    s4Mapper = vtk.vtkPolyDataMapper()
    s4Mapper.SetInputConnection(s4.GetOutputPort())
    s4Mapper.SetLookupTable(lut)
    s4Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s4Actor = vtk.vtkActor()
    s4Actor.SetMapper(s4Mapper)

    # A plane for context.
    #
    g = vtk.vtkImageDataGeometryFilter()
    g.SetInputData(ptLoad.GetOutput())
    g.SetExtent(0, 100, 0, 100, 0, 0)
    g.Update()  # for scalar range

    gm = vtk.vtkPolyDataMapper()
    gm.SetInputConnection(g.GetOutputPort())
    gm.SetScalarRange(g.GetOutput().GetScalarRange())

    ga = vtk.vtkActor()
    ga.SetMapper(gm)

    # Create an outline around the data.
    #
    outline = vtk.vtkOutlineFilter()
    outline.SetInputData(ptLoad.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # Create a cone indicating the application of the load.
    #
    coneSrc = vtk.vtkConeSource()
    coneSrc.SetRadius(0.5)
    coneSrc.SetHeight(2)

    coneMap = vtk.vtkPolyDataMapper()
    coneMap.SetInputConnection(coneSrc.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMap)
    coneActor.SetPosition(0, 0, 11)
    coneActor.RotateY(90)
    coneActor.GetProperty().SetColor(colors.GetColor3d('Tomato'))

    camera = vtk.vtkCamera()
    camera.SetFocalPoint(0.113766, -1.13665, -1.01919)
    camera.SetPosition(-29.4886, -63.1488, 26.5807)
    camera.SetViewAngle(24.4617)
    camera.SetViewUp(0.17138, 0.331163, 0.927879)
    camera.SetClippingRange(1, 100)

    ren1.AddActor(s1Actor)
    ren1.AddActor(s2Actor)
    ren1.AddActor(s3Actor)
    ren1.AddActor(s4Actor)
    ren1.AddActor(outlineActor)
    ren1.AddActor(coneActor)
    ren1.AddActor(ga)
    ren1.SetBackground(colors.GetColor3d('SlateGray'))
    ren1.SetActiveCamera(camera)

    renWin.SetSize(640, 480)
    renWin.SetWindowName('HyperStreamline')

    renWin.Render()
    iren.Start()