def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(20)
    pointSource.Update()

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInputConnection(pointSource.GetOutputPort())
    idFilter.SetIdsArrayName("OriginalIds")
    idFilter.Update()

    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(idFilter.GetOutputPort())
    surfaceFilter.Update()

    poly_input = surfaceFilter.GetOutput()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()

    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

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

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    areaPicker = vtk.vtkAreaPicker()
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetPicker(areaPicker)
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    #renderer.SetBackground(1,1,1) # Background color white

    renderWindow.Render()

    style = vtk.vtkRenderWindowInteractor()
    #style = myInteractorStyle()
    #style = InteractorStyle()
    #style = QVTKRenderWindowInteractor()
    #style.SetPoints(poly_input)
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindowInteractor.Start()
Exemple #2
0
 def createRenderWindow(self):
     self.renderer = vtk.vtkRenderer()
     renWin = vtk.vtkRenderWindow()
     renWin.AddRenderer( self.renderer )
     self.renderWindowInteractor = vtk.vtkRenderWindowInteractor()
     self.renderWindowInteractor.SetRenderWindow(renWin)            
     return renWin
Exemple #3
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()
Exemple #4
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()
Exemple #5
0
 def __init__(self,ext_actors=None): #ext_actors is a list of any external vtkActors.
     #initializations:
     self.renderer  = vtk.vtkRenderer()
     self.window    = vtk.vtkRenderWindow()
     self.window.SetSize(1000,1000)
     self.mapper    = vtk.vtkPolyDataMapper()
     self.points    = vtk.vtkPoints()
     self.poly_data = vtk.vtkPolyData()
     self.glyph3d   = vtk.vtkGlyph3D()
     self.actor     = vtk.vtkActor()
     self.point_s   = vtk.vtkPointSource()
     self.sphere    = vtk.vtkSphereSource() 
     self.interactor= vtk.vtkRenderWindowInteractor()
     self.inter_sty = PdbInteractorStyle()
     self.axes_actor= vtk.vtkAxesActor()
     #configurations:
     self.point_s.SetNumberOfPoints(1)
     self.sphere.SetRadius(1.0)
     self.interactor.SetInteractorStyle(self.inter_sty)
     self.interactor.SetRenderWindow(self.window)
     self.axes_actor.SetTotalLength(100,100,100)
     if ext_actors:
         self.ex_actors = ext_actors
     else:
         self.ex_actors=[]
    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()
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()
    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)
    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
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()
Exemple #11
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()
Exemple #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()
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()
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()
Exemple #15
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);
Exemple #16
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()
Exemple #17
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()
    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
Exemple #19
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
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()
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
	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()
Exemple #23
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()
Exemple #24
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()
Exemple #25
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)
def ex():
    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    WIDTH=640
    HEIGHT=480
    renWin.SetSize(WIDTH,HEIGHT)
 
    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
 
    # create cone
    cone = vtk.vtkConeSource()
    cone.SetResolution(60)
    cone.SetCenter(-2,0,0)
 
    # mapper
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
 
    # actor
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
 
    # assign actor to the renderer
    ren.AddActor(coneActor)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemple #27
0
def showact(actors):
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    try:
        for a in actors:
            renderer.AddActor(a)
    except:
        renderer.AddActor(actors)

    renderWindow.Render()
    renderWindowInteractor.Start()

# def showact2(actors):
#     renderer = vtk.vtkRenderer()
#     renderWindow = vtk.vtkRenderWindow()
#     renderWindow.AddRenderer(renderer)
#     renderWindowInteractor = vtk.vtkRenderWindowInteractor()
#     renderWindowInteractor.SetRenderWindow(renderWindow)
#     for a in actors:
#         renderer.AddActor(a)
#     renderer.AddActor(actors)
#
#     renderWindow.Render()
#     renderWindowInteractor.Start()
Exemple #28
0
def main(pairs):

    import __main__ as _main_module

    renderer = vtk.vtkRenderer()

    for op, file in pairs:
        handler_name = g_op_map[op]
        handler = _main_module.__dict__[handler_name]
        fname = file
        if not os.access(fname, os.R_OK):
            print "Missing file %s" % (fname)
            sys.exit(1)
        else:
            handler(fname, renderer)

    show_axes(renderer)

    # Create the usual rendering stuff.
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    renWin.SetSize(1000, 750)
    iren = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)
    iren.SetRenderWindow(renWin)

    # color
    renderer.SetBackground(.1, .2, .4)

    # Render the scene and start interaction.
    iren.Initialize()
    renWin.Render()
    iren.Start()
def DiscreteMarchingCubes(image):
    
    # Main part of discretemarchingcubes
    discreteCubes = vtk.vtkDiscreteMarchingCubes()
    discreteCubes.SetInputData(image)
    discreteCubes.GenerateValues( 116, 1-50,116-50);
    discreteCubes.Update()
    for i in range(0,116):
        print discreteCubes.GetValue(i)


    lut = CreateLookUpTable(color_map);

    # visualization
    print "visualizing..."
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(discreteCubes.GetOutput())
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(0,4)
    mapper.SetLookupTable(lut)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()
    window.SetInteractor(interactor)
    
    window.Render()
    interactor.Start()
Exemple #30
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
Exemple #31
0
def main():
    colors = vtk.vtkNamedColors()

    x = [[0, 0, 0], [1, 0, 0], [2, 0, 0], [0, 1, 0], [1, 1, 0], [2, 1, 0], [0, 0, 1], [1, 0, 1], [2, 0, 1], [0, 1, 1],
         [1, 1, 1], [2, 1, 1], [0, 1, 2], [1, 1, 2], [2, 1, 2], [0, 1, 3], [1, 1, 3], [2, 1, 3], [0, 1, 4], [1, 1, 4],
         [2, 1, 4], [0, 1, 5], [1, 1, 5], [2, 1, 5], [0, 1, 6], [1, 1, 6], [2, 1, 6]]
    # Here we have kept consistency with the Cxx example of the same name.
    # This means we will use slicing in ugrid.InsertNextCell to ensure that the correct
    #  number of points are used.
    pts = [[0, 1, 4, 3, 6, 7, 10, 9], [1, 2, 5, 4, 7, 8, 11, 10], [6, 10, 9, 12, 0, 0, 0, 0],
           [8, 11, 10, 14, 0, 0, 0, 0], [16, 17, 14, 13, 12, 15, 0, 0], [18, 15, 19, 16, 20, 17, 0, 0],
           [22, 23, 20, 19, 0, 0, 0, 0], [21, 22, 18, 0, 0, 0, 0, 0], [22, 19, 18, 0, 0, 0, 0, 0],
           [23, 26, 0, 0, 0, 0, 0, 0], [21, 24, 0, 0, 0, 0, 0, 0], [25, 0, 0, 0, 0, 0, 0, 0]]
    print(len(x), len(pts))

    renderer = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    points = vtk.vtkPoints()
    for i in range(0, len(x)):
        points.InsertPoint(i, x[i])

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.Allocate(100)
    ugrid.InsertNextCell(vtk.VTK_HEXAHEDRON, 8, pts[0])
    ugrid.InsertNextCell(vtk.VTK_HEXAHEDRON, 8, pts[1])
    ugrid.InsertNextCell(vtk.VTK_TETRA, 4, pts[2][:4])
    ugrid.InsertNextCell(vtk.VTK_TETRA, 4, pts[3][:4])
    ugrid.InsertNextCell(vtk.VTK_POLYGON, 6, pts[4][:6])
    ugrid.InsertNextCell(vtk.VTK_TRIANGLE_STRIP, 6, pts[5][:6])
    ugrid.InsertNextCell(vtk.VTK_QUAD, 4, pts[6][:4])
    ugrid.InsertNextCell(vtk.VTK_TRIANGLE, 3, pts[7][:3])
    ugrid.InsertNextCell(vtk.VTK_TRIANGLE, 3, pts[8][:3])
    ugrid.InsertNextCell(vtk.VTK_LINE, 2, pts[9][:2])
    ugrid.InsertNextCell(vtk.VTK_LINE, 2, pts[10][:2])
    ugrid.InsertNextCell(vtk.VTK_VERTEX, 1, pts[11][:1])

    ugrid.SetPoints(points)

    ugridMapper = vtk.vtkDataSetMapper()
    ugridMapper.SetInputData(ugrid)

    ugridActor = vtk.vtkActor()
    ugridActor.SetMapper(ugridMapper)
    ugridActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))
    ugridActor.GetProperty().EdgeVisibilityOn()

    renderer.AddActor(ugridActor)
    renderer.SetBackground(colors.GetColor3d("Beige"))

    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(60.0)
    renderer.GetActiveCamera().Azimuth(30.0)
    renderer.GetActiveCamera().Dolly(1.2)

    renWin.SetSize(640, 480)

    # Interact with the data.
    renWin.Render()

    iren.Start()
Exemple #32
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the color for the population.
    popColor = map(lambda x: x / 255.0, [230, 230, 230])
    colors.SetColor("BkgColor", *popColor)

    fileName = get_program_parameters()

    keys = [
        'NUMBER_POINTS', 'MONTHLY_PAYMENT', 'INTEREST_RATE', 'LOAN_AMOUNT',
        'TIME_LATE'
    ]

    # Read in the data and make an unstructured data set.
    dataSet = make_dataset(fileName, keys)

    # Construct the pipeline for the original population.
    popSplatter = vtk.vtkGaussianSplatter()
    popSplatter.SetInputData(dataSet)
    popSplatter.SetSampleDimensions(100, 100, 100)
    popSplatter.SetRadius(0.05)
    popSplatter.ScalarWarpingOff()

    popSurface = vtk.vtkContourFilter()
    popSurface.SetInputConnection(popSplatter.GetOutputPort())
    popSurface.SetValue(0, 0.01)

    popMapper = vtk.vtkPolyDataMapper()
    popMapper.SetInputConnection(popSurface.GetOutputPort())
    popMapper.ScalarVisibilityOff()

    popActor = vtk.vtkActor()
    popActor.SetMapper(popMapper)
    popActor.GetProperty().SetOpacity(0.3)
    popActor.GetProperty().SetColor(.9, .9, .9)

    # Construct the pipeline for the delinquent population.
    lateSplatter = vtk.vtkGaussianSplatter()
    lateSplatter.SetInputData(dataSet)
    lateSplatter.SetSampleDimensions(50, 50, 50)
    lateSplatter.SetRadius(0.05)
    lateSplatter.SetScaleFactor(0.005)

    lateSurface = vtk.vtkContourFilter()
    lateSurface.SetInputConnection(lateSplatter.GetOutputPort())
    lateSurface.SetValue(0, 0.01)

    lateMapper = vtk.vtkPolyDataMapper()
    lateMapper.SetInputConnection(lateSurface.GetOutputPort())
    lateMapper.ScalarVisibilityOff()

    lateActor = vtk.vtkActor()
    lateActor.SetMapper(lateMapper)
    lateActor.GetProperty().SetColor(colors.GetColor3d("Red"))

    # Create axes.
    popSplatter.Update()
    bounds = popSplatter.GetOutput().GetBounds()

    axes = vtk.vtkAxes()
    axes.SetOrigin(bounds[0], bounds[2], bounds[4])
    axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5)

    axesTubes = vtk.vtkTubeFilter()
    axesTubes.SetInputConnection(axes.GetOutputPort())
    axesTubes.SetRadius(axes.GetScaleFactor() / 25.0)
    axesTubes.SetNumberOfSides(6)

    axesMapper = vtk.vtkPolyDataMapper()
    axesMapper.SetInputConnection(axesTubes.GetOutputPort())

    axesActor = vtk.vtkActor()
    axesActor.SetMapper(axesMapper)

    # Graphics stuff.
    renderer = vtk.vtkRenderer()

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

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

    # Set up the renderer.
    renderer.AddActor(lateActor)
    renderer.AddActor(axesActor)
    renderer.AddActor(popActor)
    renderer.SetBackground(colors.GetColor3d("Wheat"))
    renWin.SetSize(640, 480)

    renderer.ResetCamera()
    renderer.GetActiveCamera().Dolly(1.3)
    renderer.ResetCameraClippingRange()

    # Interact with the data.
    renWin.Render()
    interactor.Start()
    def preview(self):
        zbin, ybin, xbin = self.shape
        data_importer = vtk.vtkImageImport()

        g = self.geo.flatten()
        g = np.uint8(g)
        data_string = g.tostring()
        data_importer.CopyImportVoidPointer(data_string, len(data_string))
        data_importer.SetDataScalarTypeToUnsignedChar()
        data_importer.SetNumberOfScalarComponents(1)

        data_importer.SetDataExtent(0, xbin - 1, 0, ybin - 1, 0, zbin - 1)
        data_importer.SetWholeExtent(0, xbin - 1, 0, ybin - 1, 0, zbin - 1)

        # Create transfer mapping scalar value to opacity
        opacity_transfer_function = vtk.vtkPiecewiseFunction()
        opacity_transfer_function.AddPoint(0, 0.0)
        opacity_transfer_function.AddPoint(1, 0.2)
        opacity_transfer_function.AddPoint(2, 0.005)
        opacity_transfer_function.AddPoint(3, 1)

        # Create transfer mapping scalar value to color
        color_transfer_function = vtk.vtkColorTransferFunction()
        color_transfer_function.AddRGBPoint(0, 0.0, 0.0, 1.0)
        color_transfer_function.AddRGBPoint(1, 1.0, 0.0, 0.0)
        color_transfer_function.AddRGBPoint(2, 0.0, 0.0, 1.0)
        color_transfer_function.AddRGBPoint(3, 1.0, 1.0, 1.0)

        # The property describes how the data will look
        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_transfer_function)
        volume_property.SetScalarOpacity(opacity_transfer_function)
        volume_property.SetInterpolationTypeToLinear()

        # The mapper / ray cast function know how to render the data
        volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
        volume_mapper.SetBlendModeToComposite()
        volume_mapper.SetInputConnection(data_importer.GetOutputPort())

        # The volume holds the mapper and the property and
        # can be used to position/orient the volume
        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_property)

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

        ren.AddVolume(volume)
        ren.SetBackground(1, 1, 1)
        ren_win.SetSize(600, 600)
        ren_win.Render()

        def check_abort(obj, event):
            if obj.GetEventPending() != 0:
                obj.SetAbortRender(1)

        ren_win.AddObserver('AbortCheckEvent', check_abort)

        iren.Initialize()
        ren_win.Render()
        iren.Start()
def main():
    colors = vtk.vtkNamedColors()

    # We begin by creating the data we want to render.
    # For this tutorial, we create a 3D-image containing three overlaping cubes.
    # This data can of course easily be replaced by data from a medical CT-scan or anything else three dimensional.
    # The only limit is that the data must be reduced to unsigned 8 bit or 16 bit integers.
    data_matrix = matfile
    data_matrix = data_matrix.astype(np.float64) / np.max(data_matrix)  # normalize the data to 0 - 1
    data_matrix = (2**8-1) * data_matrix  # Now scale by 255
    data_matrix = data_matrix.astype(np.uint8)  # uint 16
    data_matrix_colors=np.unique(data_matrix)


    # For VTK to be able to use the data, it must be stored as a VTK-image.
    #  This can be done by the vtkImageImport-class which
    # imports raw data and stores it.
    dataImporter = vtk.vtkImageImport()
    # The previously created array is converted to a string of chars and imported.
    data_string = data_matrix.tostring()
    dataImporter.CopyImportVoidPointer(data_string, len(data_string))
    # The type of the newly imported data is set to unsigned char (uint8)
    dataImporter.SetDataScalarTypeToUnsignedChar()
    # Because the data that is imported only contains an intensity value
    #  (it isnt RGB-coded or someting similar), the importer must be told this is the case.
    dataImporter.SetNumberOfScalarComponents(1)
    # The following two functions describe how the data is stored and the dimensions of the array it is stored in.
    #  For this simple case, all axes are of length and begins with the first element.
    #  For other data, this is probably not the case.
    # I have to admit however, that I honestly dont know the difference between SetDataExtent()
    #  and SetWholeExtent() although VTK complains if not both are used.
    w, h, d = data_matrix.shape
    dataImporter.SetDataExtent(0, h - 1, 0, d - 1, 0, w - 1)
    dataImporter.SetWholeExtent(0, h - 1, 0, d - 1, 0, w - 1)

    # The following class is used to store transparency-values for later retrival.
    #  In our case, we want the value 0 to be
    # completely transpenernt whereas the three different cubes are given different transparency-values to show how it works.
    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.02)
    alphaChannelFunc.AddPoint(120, 0.2)
    alphaChannelFunc.AddPoint(255, 1)
    #alphaChannelFunc.AddPoint(150, 0.2)
    #alphaChannelFunc.AddPoint(200, 0.1)
    #alphaChannelFunc.AddPoint(255, 0.0)

    # This class stores color data and can create color tables from a few color points.
    #  For this demo, we want the three cubes to be of the colors red green and blue.
    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(0, 0, 0.0, 0.0)
    colorFunc.AddRGBPoint(200, 0.8, 0.36, 0.36)
    colorFunc.AddRGBPoint(255, 1, 0.4, 0)

    # The previous two classes stored properties.
    #  Because we want to apply these properties to the volume we want to render,
    # we have to store them in a class that stores volume properties.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

    # The class vtkVolume is used to pair the previously declared volume as well as the properties
    #  to be used when rendering that volume.
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    # With almost everything else ready, its time to initialize the renderer and window, as well as
    #  creating a method for exiting the application
    renderer = vtk.vtkRenderer()
    renderWin = vtk.vtkRenderWindow()
    renderWin.AddRenderer(renderer)
    renderInteractor = vtk.vtkRenderWindowInteractor()
    renderInteractor.SetRenderWindow(renderWin)

    # We add the volume to the renderer ...
    renderer.AddVolume(volume)
    renderer.SetBackground(colors.GetColor3d("MistyRose"))

    # ... and set window size.
    renderWin.SetSize(600, 600)

    # A simple function to be called when the user decides to quit the application.
    def exitCheck(obj, event):
        if obj.GetEventPending() != 0:
            obj.SetAbortRender(1)

    # Tell the application to use the function as an exit check.
    renderWin.AddObserver("AbortCheckEvent", exitCheck)

    renderInteractor.Initialize()
    # Because nothing will be rendered without any input, we order the first render manually
    #  before control is handed over to the main-loop.
    renderWin.Render()
    renderInteractor.Start()
Exemple #35
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor("BkgColor", [51, 77, 102, 255])

    sourceObjects = list()
    sourceObjects.append(vtk.vtkSphereSource())
    sourceObjects[-1].SetPhiResolution(21)
    sourceObjects[-1].SetThetaResolution(21)

    sourceObjects.append(vtk.vtkConeSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCylinderSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCubeSource())
    sourceObjects.append(vtk.vtkPlaneSource())
    sourceObjects.append(vtk.vtkTextSource())
    sourceObjects[-1].SetText("Hello")
    sourceObjects[-1].BackingOff()

    sourceObjects.append(vtk.vtkPointSource())
    sourceObjects[-1].SetNumberOfPoints(500)

    sourceObjects.append(vtk.vtkDiskSource())
    sourceObjects[-1].SetCircumferentialResolution(51)

    sourceObjects.append(vtk.vtkLineSource())

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

    # Create one text property for all.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d("Red"))

    # Create a source, renderer, mapper, and actor
    # for each object.
    for i in range(0, len(sourceObjects)):
        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Seashell"))
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(sourceObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)
        renderers.append(vtk.vtkRenderer())

    gridDimensions = 3

    # We need a renderer even if there is no actor.
    for i in range(len(sourceObjects), gridDimensions**2):
        renderers.append(vtk.vtkRenderer())

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Source Objects Demo")
    rendererSize = 300
    renderWindow.SetSize(rendererSize * gridDimensions,
                         rendererSize * gridDimensions)

    for row in range(0, gridDimensions):
        for col in range(0, gridDimensions):
            index = row * gridDimensions + col
            x0 = float(col) / gridDimensions
            y0 = float(gridDimensions - row - 1) / gridDimensions
            x1 = float(col + 1) / gridDimensions
            y1 = float(gridDimensions - row) / gridDimensions
            renderWindow.AddRenderer(renderers[index])
            renderers[index].SetViewport(x0, y0, x1, y1)

            if index > (len(sourceObjects) - 1):
                continue

            renderers[index].AddActor(actors[index])
            renderers[index].AddActor(textactors[index])
            renderers[index].SetBackground(colors.GetColor3d("BkgColor"))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(30)
            renderers[index].GetActiveCamera().Zoom(0.8)
            renderers[index].ResetCameraClippingRange()

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

    renderWindow.Render()
    interactor.Start()
Exemple #36
0
    def testImagePlaneWidget(self):
        "A more rigorous test using the image plane widget."
        # This test is largely copied from
        # Widgets/Python/TestImagePlaneWidget.py

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

        # Now create another actor with an opacity < 1 and with some
        # scalars.
        p = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        pts.InsertNextPoint((0,0,0))
        sc = vtk.vtkFloatArray()
        sc.InsertNextValue(1.0)
        p.SetPoints(pts)
        p.GetPointData().SetScalars(sc)
        m = vtk.vtkPolyDataMapper()
        m.SetInputData(p)
        # Share the lookup table of the widgets.
        m.SetLookupTable(planeWidgetX.GetLookupTable())
        m.UseLookupTableScalarRangeOn()
        dummyActor = vtk.vtkActor()
        dummyActor.SetMapper(m)
        dummyActor.GetProperty().SetOpacity(0.0)

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

        # Add the dummy actor.
        ren.AddActor(dummyActor)
        # 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()
Exemple #37
0
  def viewer(self):
    try:
      import vtk
    except ImportError:
      print("The mesh viewer requires the OpenGL based vtk. Try: pip install vtk --upgrade")
      return

    colors = vtk.vtkNamedColors()
    # Set the background color.
    bkg = map(lambda x: x / 255.0, [40, 40, 40, 255])
    colors.SetColor("BkgColor", *bkg)

    # This creates a point cloud model
    points = vtk.vtkPoints()
    verts = vtk.vtkCellArray()
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetVerts(verts)
    for vertex in self.vertices:
      pid = points.InsertNextPoint(vertex)
      verts.InsertNextCell(1)
      verts.InsertCellPoint(pid)

    # The mapper is responsible for pushing the geometry into the graphics
    # library. It may also do color mapping, if scalars or other
    # attributes are defined.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)

    # The actor is a grouping mechanism: besides the geometry (mapper), it
    # also has a property, transformation matrix, and/or texture map.
    # Here we set its color and rotate it -22.5 degrees.
    cylinderActor = vtk.vtkActor()
    cylinderActor.SetMapper(mapper)
    cylinderActor.GetProperty().SetColor(colors.GetColor3d("Mint"))
    cylinderActor.RotateX(30.0)
    cylinderActor.RotateY(-45.0)

    # Create the graphics structure. The renderer renders into the render
    # window. The render window interactor captures mouse events and will
    # perform appropriate camera or actor manipulation depending on the
    # nature of the events.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size
    ren.AddActor(cylinderActor)
    ren.SetBackground(colors.GetColor3d("BkgColor"))
    renWin.SetSize(800, 800)

    text = "Point Cloud Rendering of Mesh Object"
    if self.segid is not None:
      renWin.SetWindowName(text + " (Label {})".format(self.segid))
    else:
      renWin.SetWindowName(text)

    # This allows the interactor to initalize itself. It has to be
    # called before an event loop.
    iren.Initialize()

    # We'll zoom in a little by accessing the camera and invoking a "Zoom"
    # method on it.
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(1.5)
    renWin.Render()

    # Start the event loop.
    iren.Start()    
def main():
    folder = get_program_parameters()

    # Read all the DICOM files in the specified directory.
    reader = vtk.vtkDICOMImageReader()

    reader.SetDirectoryName(folder)
    reader.Update()

    # Visualize
    imageViewer = vtk.vtkImageViewer2()
    imageViewer.SetInputConnection(reader.GetOutputPort())

    # slice status message
    sliceTextProp = vtk.vtkTextProperty()
    sliceTextProp.SetFontFamilyToCourier()
    sliceTextProp.SetFontSize(20)
    sliceTextProp.SetVerticalJustificationToBottom()
    sliceTextProp.SetJustificationToLeft()

    sliceTextMapper = vtk.vtkTextMapper()
    msg = StatusMessage.Format(imageViewer.GetSliceMin(),
                               imageViewer.GetSliceMax())
    sliceTextMapper.SetInput(msg)
    sliceTextMapper.SetTextProperty(sliceTextProp)

    sliceTextActor = vtk.vtkActor2D()
    sliceTextActor.SetMapper(sliceTextMapper)
    sliceTextActor.SetPosition(15, 10)

    # usage hint message
    usageTextProp = vtk.vtkTextProperty()
    usageTextProp.SetFontFamilyToCourier()
    usageTextProp.SetFontSize(20)
    usageTextProp.SetVerticalJustificationToTop()
    usageTextProp.SetJustificationToLeft()

    usageTextMapper = vtk.vtkTextMapper()
    usageTextMapper.SetInput(
        "- Slice with mouse wheel\n  or Up/Down-Key\n- Zoom with pressed right\n  mouse button while dragging"
    )
    usageTextMapper.SetTextProperty(usageTextProp)

    usageTextActor = vtk.vtkActor2D()
    usageTextActor.SetMapper(usageTextMapper)
    usageTextActor.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    usageTextActor.GetPositionCoordinate().SetValue(0.05, 0.95)

    # create an interactor with our own style (inherit from vtkInteractorStyleImage)
    # in order to catch mousewheel and key events
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    # make imageviewer2 and sliceTextMapper visible to our interactorstyle
    # to enable slice status message updates when scrolling through the slices

    imageViewer.SetupInteractor(renderWindowInteractor)

    # make the interactor use our own interactorstyle
    # cause SetupInteractor() is defining it's own default interatorstyle
    # this must be called after SetupInteractor()
    # add slice status message and usage hint message to the renderer
    imageViewer.GetRenderer().AddActor2D(sliceTextActor)
    imageViewer.GetRenderer().AddActor2D(usageTextActor)

    renderWindowInteractor.AddObserver("LeftButtonPressEvent", OnKeyDown)
    renderWindowInteractor.AddObserver("LeftButtonReleaseEvent",
                                       OnMouseWheelForward)
    renderWindowInteractor.AddObserver("MiddleButtonPressEvent",
                                       OnMouseWheelBackward)

    # initialize rendering and interaction
    imageViewer.GetRenderWindow().SetSize(400, 300)
    imageViewer.GetRenderer().SetBackground(0.2, 0.3, 0.4)
    imageViewer.Render()
    imageViewer.GetRenderer().ResetCamera()
    imageViewer.Render()
    renderWindowInteractor.Start()
    def test(self):
        dataRoot = vtkGetDataRoot()
        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName("" + str(dataRoot) + "/Data/vase_4comp.vti")

        volume = vtk.vtkVolume()
        #mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        mapper = vtk.vtkGPUVolumeRayCastMapper()
        mapper.SetBlendModeToMaximumIntensity()
        mapper.SetSampleDistance(0.1)
        mapper.SetAutoAdjustSampleDistances(0)
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        iRen = vtk.vtkRenderWindowInteractor()

        # Set connections
        mapper.SetInputConnection(reader.GetOutputPort())
        volume.SetMapper(mapper)
        ren.AddViewProp(volume)
        renWin.AddRenderer(ren)
        iRen.SetRenderWindow(renWin)

        # Define opacity transfer function and color functions
        opacityFunc1 = vtk.vtkPiecewiseFunction()
        opacityFunc1.AddPoint(0.0, 0.0)
        opacityFunc1.AddPoint(60.0, 0.1)
        opacityFunc1.AddPoint(255.0, 0.0)

        opacityFunc2 = vtk.vtkPiecewiseFunction()
        opacityFunc2.AddPoint(0.0, 0.0)
        opacityFunc2.AddPoint(60.0, 0.0)
        opacityFunc2.AddPoint(120.0, 0.1)
        opacityFunc1.AddPoint(255.0, 0.0)

        opacityFunc3 = vtk.vtkPiecewiseFunction()
        opacityFunc3.AddPoint(0.0, 0.0)
        opacityFunc3.AddPoint(120.0, 0.0)
        opacityFunc3.AddPoint(180.0, 0.1)
        opacityFunc3.AddPoint(255.0, 0.0)

        opacityFunc4 = vtk.vtkPiecewiseFunction()
        opacityFunc4.AddPoint(0.0, 0.0)
        opacityFunc4.AddPoint(180.0, 0.0)
        opacityFunc4.AddPoint(255.0, 0.1)

        # Color transfer functions
        color1 = vtk.vtkColorTransferFunction()
        color1.AddRGBPoint(0.0, 1.0, 0.0, 0.0)
        color1.AddRGBPoint(60.0, 1.0, 0.0, 0.0)

        color2 = vtk.vtkColorTransferFunction()
        color2.AddRGBPoint(60.0, 0.0, 0.0, 1.0)
        color2.AddRGBPoint(120.0, 0.0, 0.0, 1.0)

        color3 = vtk.vtkColorTransferFunction()
        color3.AddRGBPoint(120.0, 0.0, 1.0, 0.0)
        color3.AddRGBPoint(180.0, 0.0, 1.0, 0.0)

        color4 = vtk.vtkColorTransferFunction()
        color4.AddRGBPoint(180.0, 0.0, 0.0, 0.0)
        color4.AddRGBPoint(239.0, 0.0, 0.0, 0.0)

        # Now set the opacity and the color
        volumeProperty = volume.GetProperty()
        volumeProperty.SetIndependentComponents(1)
        volumeProperty.SetScalarOpacity(0, opacityFunc1)
        volumeProperty.SetScalarOpacity(1, opacityFunc2)
        volumeProperty.SetScalarOpacity(2, opacityFunc3)
        volumeProperty.SetScalarOpacity(3, opacityFunc4)
        volumeProperty.SetColor(0, color1)
        volumeProperty.SetColor(1, color2)
        volumeProperty.SetColor(2, color3)
        volumeProperty.SetColor(3, color4)

        iRen.Initialize()
        ren.SetBackground(0.1, 0.4, 0.2)
        ren.ResetCamera()
        renWin.Render()

        img_file = "TestGPURayCastIndependentComponentMIP.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=10)
        vtk.test.Testing.interact()
Exemple #40
0
def view_patch_vtk(r, azimuth=90, elevation=0, roll=-90, outfile=0, show=1):

    c = r.vColor
    ro = r
    r = createPolyData(r.vertices, r.faces)

    Colors = vtkUnsignedCharArray()
    Colors.SetNumberOfComponents(3)
    Colors.SetName("Colors")

    for i in range(len(ro.vertices)):
        Colors.InsertNextTuple3(255 * c[i, 0], 255 * c[i, 1], 255 * c[i, 2])

    r.GetPointData().SetScalars(Colors)
    r.Modified()
    # ##    r.Update()
    # mapper
    mapper = vtkPolyDataMapper()
    if VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(r)
    else:
        #       mapper.SetInputConnection(r.GetOutputPort())
        mapper.SetInputData(r)

    actor = vtkActor()
    actor.SetMapper(mapper)
    #    actor.GetProperty().SetInterpolationToPhong()
    normals = vtkPolyDataNormals()
    normals.SetInputData(r)
    normals.ComputePointNormalsOn()
    normals.ComputeCellNormalsOn()
    #    normals.SplittingOff()
    normals.AutoOrientNormalsOn()
    normals.ConsistencyOn()
    #normals.SetFeatureAngle(4.01)
    normals.Update()
    mapper.SetInputData(normals.GetOutput())

    ren = vtkRenderer()
    ren.TwoSidedLightingOff()
    renWin = vtkRenderWindow()
    renWin.SetSize(1600, 1600)
    #    renWin.SetDPI(200)
    if show == 0:
        renWin.SetOffScreenRendering(1)

    renWin.AddRenderer(ren)
    # create a renderwindowinteractor
    iren = vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren.SetBackground(256.0 / 256, 256.0 / 256, 256.0 / 256)

    ren.AddActor(actor)

    # enable user interface interactor
    iren.Initialize()

    renWin.Render()
    ren.GetActiveCamera().Azimuth(azimuth)
    ren.GetActiveCamera().Elevation(elevation)
    ren.GetActiveCamera().Roll(roll)
    renWin.Render()
    #  windowToImageFilter->SetInput(renderWindow);
    #  windowToImageFilter->SetMagnification(3); //set the resolution of the output image (3 times the current resolution of vtk render window)
    #  windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
    #  windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
    #  windowToImageFilter->Update();

    if outfile != 0:
        w2i = vtkWindowToImageFilter()
        writer = vtkPNGWriter()
        #        iren.SetDPI(200)
        w2i.SetInput(renWin)
        w2i.SetInputBufferTypeToRGBA()
        w2i.ReadFrontBufferOff()
        w2i.Update()
        writer.SetInputData(w2i.GetOutput())
        writer.SetFileName(outfile)
        iren.Render()
        writer.Write()

        image = Image.open(outfile)
        image.load()
        #        imageSize = image.size
        imageBox = image.getbbox()
        print(image.getbbox())
        cropped = image.crop(imageBox)
        print(cropped.getbbox())
        cropped.save(outfile)

    if show != 0:
        iren.Start()

    close_window(iren)
    del renWin, iren
Exemple #41
0
def main():
    file_name, color_scheme = get_program_parameters()

    color_scheme = abs(color_scheme)
    if color_scheme > 2:
        color_scheme = 0

    colors = vtk.vtkNamedColors()

    # Read a vtk file
    #
    plate = vtk.vtkPolyDataReader()
    plate.SetFileName(file_name)
    plate.SetVectorsName("mode8")
    plate.Update()

    warp = vtk.vtkWarpVector()
    warp.SetInputConnection(plate.GetOutputPort())
    warp.SetScaleFactor(0.5)

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(warp.GetOutputPort())

    color = vtk.vtkVectorDot()
    color.SetInputConnection(normals.GetOutputPort())

    lut = vtk.vtkLookupTable()
    MakeLUT(color_scheme, lut)

    plateMapper = vtk.vtkDataSetMapper()
    plateMapper.SetInputConnection(color.GetOutputPort())
    plateMapper.SetLookupTable(lut)
    plateMapper.SetScalarRange(-1, 1)

    plateActor = vtk.vtkActor()
    plateActor.SetMapper(plateMapper)

    # Create the RenderWindow, Renderer and both Actors
    #
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

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

    # Add the actors to the renderer, set the background and size
    #
    ren.AddActor(plateActor)
    ren.SetBackground(colors.GetColor3d("Wheat"))
    renWin.SetSize(512, 512)

    ren.GetActiveCamera().SetPosition(13.3991, 14.0764, 9.97787)
    ren.GetActiveCamera().SetFocalPoint(1.50437, 0.481517, 4.52992)
    ren.GetActiveCamera().SetViewAngle(30)
    ren.GetActiveCamera().SetViewUp(-0.120861, 0.458556, -0.880408)
    ren.GetActiveCamera().SetClippingRange(12.5724, 26.8374)
    # Render the image.
    renWin.Render()

    iren.Start()
Exemple #42
0
def main():
    def FlatInterpolation():
        for actor in actors:
            actor.GetProperty().SetInterpolationToFlat()
        renWin.Render()

    def GouraudInterpolation():
        for actor in actors:
            actor.GetProperty().SetInterpolationToGouraud()
        renWin.Render()

    sourceToUse, displayNormals, gouraudInterpolation, glyphPoints = GetProgramParameters(
    )

    if sourceToUse in Sources().sources:
        src = Sources().sources[sourceToUse]
    else:
        print('The source {:s} is not available.'.format(sourceToUse))
        print('Available sources are:\n',
              ', '.join(sorted(list(Sources().sources.keys()))))
        return

    src.Update()

    # The size of the render window.
    renWinXSize = 1200
    renWinYSize = renWinXSize // 3
    minRenWinDim = min(renWinXSize, renWinYSize)

    # [xMin, xMax, yMin, yMax, zMin, zMax]
    bounds = src.GetOutput().GetBounds()
    # Use this to scale the normal glyph.
    scaleFactor = min(map(lambda x, y: x - y, bounds[1::2], bounds[::2])) * 0.2
    src.GetOutput().GetPointData().GetScalars().SetName("Elevation")
    scalarRange = src.GetOutput().GetScalarRange()

    butterfly = vtk.vtkButterflySubdivisionFilter()
    butterfly.SetInputConnection(src.GetOutputPort())
    butterfly.SetNumberOfSubdivisions(3)
    butterfly.Update()

    linear = vtk.vtkLinearSubdivisionFilter()
    linear.SetInputConnection(src.GetOutputPort())
    linear.SetNumberOfSubdivisions(3)
    linear.Update()

    lut = MakeLUT(scalarRange)

    actors = list()
    actors.append(MakeSurfaceActor(butterfly, scalarRange, lut))
    actors.append(MakeSurfaceActor(linear, scalarRange, lut))
    actors.append(MakeSurfaceActor(src, scalarRange, lut))

    # Let's visualise the normals.
    glyphActors = list()
    if displayNormals:
        glyphActors.append(
            GlyphActor(butterfly, glyphPoints, scalarRange, scaleFactor, lut))
        glyphActors.append(
            GlyphActor(linear, glyphPoints, scalarRange, scaleFactor, lut))
        glyphActors.append(
            GlyphActor(src, glyphPoints, scalarRange, scaleFactor, lut))

    labelActors = list()
    labelActors.append(MakeLabel('Butterfly Subdivision', minRenWinDim))
    labelActors.append(MakeLabel('Linear Subdivision', minRenWinDim))
    labelActors.append(MakeLabel('Original', minRenWinDim))

    ren = list()
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren[2].SetViewport(0, 0, 1.0 / 3.0, 1)  # Original
    ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1)  # Linear
    ren[0].SetViewport(2.0 / 3.0, 0, 1, 1)  # Butterfly

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

    # Orientation markers.
    om = list()
    # Make the imaging pipelines.
    for i in range(0, len(ren)):
        renWin.AddRenderer(ren[i])

        ren[i].AddActor(actors[i])
        ren[i].AddActor(labelActors[i])
        ren[i].SetBackground(nc.GetColor3d('SlateGray'))

        if displayNormals:
            ren[i].AddActor(glyphActors[i])

        om.append(MakeOrientationMarker(ren[i], iren))

    if gouraudInterpolation:
        GouraudInterpolation()
    else:
        FlatInterpolation()

    renWin.SetSize(renWinXSize, renWinYSize)
    renWin.Render()
    # renWin.SetWindowName() needs to be called after renWin.Render()
    renWin.SetWindowName('Point Data Subdivision Example')

    iren.Initialize()
    # WritePNG(iren.GetRenderWindow().GetRenderers().GetFirstRenderer(), "TestPointDataSubdivision.png")
    iren.Start()
def main():

    ####################
    # Options
    ####################

    # drive_id = '2011_09_26_drive_0001_sync'  # No moving cars, depth completion sample 0 area
    # drive_id = '2011_09_26_drive_0002_sync'  # depth completion sample 0
    # drive_id = '2011_09_26_drive_0005_sync'  # (gps bad)
    # drive_id = '2011_09_26_drive_0005_sync'  # (moving) (gps bad)
    # drive_id = '2011_09_26_drive_0009_sync'  # missing velo?
    # drive_id = '2011_09_26_drive_0011_sync'  # both moving, then traffic light)
    # drive_id = '2011_09_26_drive_0013_sync'  # both moving
    # drive_id = '2011_09_26_drive_0014_sync'  # both moving, sample 104
    # drive_id = '2011_09_26_drive_0015_sync'  # both moving
    # drive_id = '2011_09_26_drive_0017_sync'  # other only, traffic light, moving across
    # drive_id = '2011_09_26_drive_0018_sync'  # other only, traffic light, forward
    # drive_id = '2011_09_26_drive_0019_sync'  # both moving, some people at end, wonky gps
    # drive_id = '2011_09_26_drive_0020_sync'  # gps drift
    # drive_id = '2011_09_26_drive_0022_sync'  # ego mostly, then both, long
    # drive_id = '2011_09_26_drive_0023_sync'  # sample 169 (long)
    # drive_id = '2011_09_26_drive_0027_sync'  # both moving, fast, straight
    # drive_id = '2011_09_26_drive_0028_sync'  # both moving, opposite
    drive_id = '2011_09_26_drive_0029_sync'  # both moving, good gps
    # drive_id = '2011_09_26_drive_0032_sync'  # both moving, following some cars
    # drive_id = '2011_09_26_drive_0035_sync'  #
    # drive_id = '2011_09_26_drive_0036_sync'  # (long) behind red truck
    # drive_id = '2011_09_26_drive_0039_sync'  # ok, 1 moving
    # drive_id = '2011_09_26_drive_0046_sync'  # (short) only 1 moving at start
    # drive_id = '2011_09_26_drive_0048_sync'  # ok but short, no movement
    # drive_id = '2011_09_26_drive_0052_sync'  #
    # drive_id = '2011_09_26_drive_0056_sync'  #
    # drive_id = '2011_09_26_drive_0057_sync'  # (gps sinking)
    # drive_id = '2011_09_26_drive_0059_sync'  #
    # drive_id = '2011_09_26_drive_0060_sync'  #
    # drive_id = '2011_09_26_drive_0061_sync'  # ego only, ok, long, bumpy, some gps drift
    # drive_id = '2011_09_26_drive_0064_sync'  # Smart car, sample 25
    # drive_id = '2011_09_26_drive_0070_sync'  #
    # drive_id = '2011_09_26_drive_0079_sync'  #
    # drive_id = '2011_09_26_drive_0086_sync'  # (medium) uphill
    # drive_id = '2011_09_26_drive_0087_sync'  #
    # drive_id = '2011_09_26_drive_0091_sync'  #
    # drive_id = '2011_09_26_drive_0093_sync'  # Sample 50 (bad)
    # drive_id = '2011_09_26_drive_0106_sync'  # Two cyclists on right
    # drive_id = '2011_09_26_drive_0113_sync'  #
    # drive_id = '2011_09_26_drive_0117_sync'  # (long)

    # drive_id = '2011_09_28_drive_0002_sync'  # campus
    # drive_id = '2011_09_28_drive_0016_sync'  # campus
    # drive_id = '2011_09_28_drive_0021_sync'  # campus
    # drive_id = '2011_09_28_drive_0034_sync'  #
    # drive_id = '2011_09_28_drive_0037_sync'  #
    # drive_id = '2011_09_28_drive_0038_sync'  #
    # drive_id = '2011_09_28_drive_0039_sync'  # busy campus, bad gps
    # drive_id = '2011_09_28_drive_0043_sync'  #
    # drive_id = '2011_09_28_drive_0045_sync'  #
    # drive_id = '2011_09_28_drive_0179_sync'  #

    # drive_id = '2011_09_29_drive_0026_sync'  #
    # drive_id = '2011_09_29_drive_0071_sync'  #

    # drive_id = '2011_09_30_drive_0020_sync'  #
    # drive_id = '2011_09_30_drive_0027_sync'  # (long)
    # drive_id = '2011_09_30_drive_0028_sync'  # (long) bad gps
    # drive_id = '2011_09_30_drive_0033_sync'  #
    # drive_id = '2011_09_30_drive_0034_sync'  #

    # drive_id = '2011_10_03_drive_0042_sync'  #
    # drive_id = '2011_10_03_drive_0047_sync'  #

    raw_dir = os.path.expanduser('~/Kitti/raw')

    vtk_window_size = (1280, 720)

    point_cloud_source = 'lidar'

    # Load raw data
    drive_date = drive_id[0:10]
    drive_num_str = drive_id[17:21]
    raw_data = pykitti.raw(raw_dir, drive_date, drive_num_str)

    # Check that velo length matches timestamps?
    if len(raw_data.velo_files) != len(raw_data.timestamps):
        raise ValueError('velo files and timestamps have different length!')

    frame_range = (0, len(raw_data.timestamps))
    # frame_range = (0, 100)

    poses_source = 'gps'
    # poses_source = 'orbslam2'

    # camera_viewpoint = 'front'
    camera_viewpoint = 'elevated'

    ####################
    # End of Options
    ####################

    vtk_renderer = demo_utils.setup_vtk_renderer()

    vtk_render_window = demo_utils.setup_vtk_render_window(
        'Overlaid Point Cloud', vtk_window_size, vtk_renderer)

    vtk_interactor = vtk.vtkRenderWindowInteractor()
    vtk_interactor.SetRenderWindow(vtk_render_window)
    vtk_interactor.SetInteractorStyle(
        vtk_utils.ToggleActorsInteractorStyle(None, vtk_renderer))
    vtk_interactor.Initialize()

    drive_date_dir = raw_dir + '/{}'.format(drive_date)

    if point_cloud_source != 'lidar':
        raise ValueError(
            'Invalid point cloud source {}'.format(point_cloud_source))

    cam_p = raw_data.calib.P_rect_20

    if poses_source == 'gps':
        # Load poses from matlab
        poses_path = drive_date_dir + '/{}/poses.mat'.format(drive_id)
        poses_mat = scipy.io.loadmat(poses_path)
        imu_ref_poses = np.asarray(poses_mat['pose'][0])

    elif poses_source == 'orbslam2':
        # Load poses from ORBSLAM2
        imu_ref_poses = np.loadtxt(raw_data.data_path +
                                   '/poses_orbslam2.txt').reshape(-1, 3, 4)
        imu_ref_poses = np.pad(imu_ref_poses, ((0, 0), (0, 1), (0, 0)),
                               mode='constant',
                               constant_values=0)
        imu_ref_poses[:, 3, 3] = 1.0
    else:
        raise ValueError('Invalid poses_source', poses_source)

    # Read calibrations
    tf_velo_calib_imu_calib = raw_data.calib.T_velo_imu
    tf_imu_calib_velo_calib = transform_utils.invert_tf(
        tf_velo_calib_imu_calib)

    tf_cam0_calib_velo_calib = raw_data.calib.T_cam0_velo
    tf_velo_calib_cam0_calib = transform_utils.invert_tf(
        tf_cam0_calib_velo_calib)

    # Create VtkAxes
    vtk_axes = vtk.vtkAxesActor()
    vtk_axes.SetTotalLength(2, 2, 2)
    vtk_renderer.AddActor(vtk_axes)

    for frame_idx in range(*frame_range):

        # Point cloud actor wrapper
        # vtk_pc = VtkPointCloud()
        vtk_pc = VtkPointCloudGlyph()
        vtk_pc.vtk_actor.GetProperty().SetPointSize(2)

        # all_vtk_actors.append(vtk_point_cloud.vtk_actor)
        vtk_renderer.AddActor(vtk_pc.vtk_actor)

        print('{} / {}'.format(frame_idx, len(raw_data.timestamps) - 1))

        # Load next frame data
        load_start_time = time.time()
        rgb_image = np.asarray(raw_data.get_cam2(frame_idx))
        bgr_image = rgb_image[..., ::-1]

        if point_cloud_source == 'lidar':
            velo_points = get_velo_points(raw_data, frame_idx)

            # Transform point cloud to cam_0 frame
            velo_curr_points_padded = np.pad(velo_points, [[0, 0], [0, 1]],
                                             constant_values=1.0,
                                             mode='constant')

            # R_rect_00 already applied in T_cam0_velo
            # T_cam0_velo = R_rect_00 @ T_cam0_velo_unrect
            cam0_curr_pc_all_padded = raw_data.calib.T_cam0_velo @ velo_curr_points_padded.T

        else:
            raise ValueError('Invalid point cloud source')

        print('load\t\t', time.time() - load_start_time)

        # Project velodyne points
        projection_start_time = time.time()

        if point_cloud_source == 'lidar':

            points_in_img = calib_utils.project_pc_to_image(
                cam0_curr_pc_all_padded[0:3], cam_p)
            points_in_img_int = np.round(points_in_img).astype(np.int32)

            image_filter = obj_utils.points_in_img_filter(
                points_in_img_int, bgr_image.shape)

            cam0_curr_pc_padded = cam0_curr_pc_all_padded[:, image_filter]

            points_in_img_int_valid = points_in_img_int[:, image_filter]
            point_colours = bgr_image[points_in_img_int_valid[1],
                                      points_in_img_int_valid[0]]

        print('projection\t', time.time() - projection_start_time)

        # Get calibration transformations
        tf_velo_calib_imu_calib = transform_utils.invert_tf(
            tf_imu_calib_velo_calib)
        tf_cam0_calib_imu_calib = tf_cam0_calib_velo_calib @ tf_velo_calib_imu_calib

        tf_imu_calib_cam0_calib = transform_utils.invert_tf(
            tf_cam0_calib_imu_calib)

        # Get poses
        imu_ref_pose = imu_ref_poses[frame_idx]
        tf_imu_ref_imu_curr = imu_ref_pose

        # Calculate point cloud in imu_ref frame
        velo_curr_pc_padded = tf_velo_calib_cam0_calib @ cam0_curr_pc_padded
        imu_curr_pc_padded = tf_imu_calib_velo_calib @ velo_curr_pc_padded
        imu_ref_pc_padded = tf_imu_ref_imu_curr @ imu_curr_pc_padded

        # VtkPointCloud
        vtk_pc_start_time = time.time()
        vtk_pc.set_points(imu_ref_pc_padded[0:3].T, point_colours)
        print('vtk_pc\t\t', time.time() - vtk_pc_start_time)

        vtk_pc_pose = VtkPointCloudGlyph()
        vtk_pc_pose.vtk_actor.GetProperty().SetPointSize(5)
        vtk_pc_pose.set_points(np.reshape(imu_ref_pose[0:3, 3], [-1, 3]))
        vtk_renderer.AddActor(vtk_pc_pose.vtk_actor)

        # Move camera
        if camera_viewpoint == 'front':
            imu_curr_cam0_position = tf_imu_calib_cam0_calib @ [
                0.0, 0.0, 0.0, 1.0
            ]
        elif camera_viewpoint == 'elevated':
            imu_curr_cam0_position = tf_imu_calib_cam0_calib.dot(
                [0.0, -5.0, -10.0, 1.0])
        else:
            raise ValueError('Invalid camera_pos', camera_viewpoint)

        imu_ref_cam0_position = tf_imu_ref_imu_curr.dot(imu_curr_cam0_position)
        imu_curr_focal_point = tf_imu_calib_cam0_calib.dot(
            [0.0, 0.0, 20.0, 1.0])
        imu_ref_focal_point = tf_imu_ref_imu_curr.dot(imu_curr_focal_point)

        current_cam = vtk_renderer.GetActiveCamera()
        vtk_renderer.ResetCamera()
        current_cam.SetViewUp(0, 0, 1)

        current_cam.SetPosition(imu_ref_cam0_position[0:3])
        current_cam.SetFocalPoint(*imu_ref_focal_point[0:3])

        current_cam.Zoom(0.5)

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

        # Render
        render_start_time = time.time()
        vtk_render_window.Render()
        print('render\t\t', time.time() - render_start_time)

        print('---')

    print('Done')

    # Keep window open
    vtk_interactor.Start()
Exemple #44
0
def vtk_figure(output_filename,
               geometry,
               scalar=None,
               contours=None,
               width=400,
               height=230,
               scalar_colorbar=True):
    import vtk
    import math

    # bounding box
    bounds = geometry.GetBounds()
    cx = (bounds[0] + bounds[1]) / 2.0
    cy = (bounds[2] + bounds[3]) / 2.0
    scale = max(math.fabs(bounds[0] - cx), math.fabs(bounds[1] - cx),
                math.fabs(bounds[2] - cy), math.fabs(bounds[3] - cy))

    # renderer
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(1, 1, 1)

    # scalar
    if (scalar != None):
        renderer.AddActor(scalar)

    # contours
    if (contours != None):
        renderer.AddActor(contours)

    # geometry
    renderer.AddActor(geometry)

    # camera
    camera = renderer.GetActiveCamera()
    camera.ParallelProjectionOn()
    camera.SetParallelScale(scale)
    camera.SetPosition(cx, cy, 1)
    camera.SetFocalPoint(cx, cy, 0)

    # render window
    render_window = vtk.vtkRenderWindow()
    render_window.SetOffScreenRendering(1)
    render_window.SetSize(width, height)
    render_window.AddRenderer(renderer)
    render_window.Render()

    # scalar colorbar
    if (scalar != None):
        if (scalar_colorbar):
            interactor = vtk.vtkRenderWindowInteractor()
            interactor.SetRenderWindow(render_window)

            scalar_bar = vtk.vtkScalarBarActor()
            scalar_bar.SetOrientationToHorizontal()
            scalar_bar.SetNumberOfLabels(8)
            scalar_bar.SetLabelFormat("%+#6.2e")
            scalar_bar.SetLookupTable(scalar.GetMapper().GetLookupTable())
            scalar_bar.GetLabelTextProperty().SetFontFamilyToCourier()
            scalar_bar.GetLabelTextProperty().SetJustificationToRight()
            scalar_bar.GetLabelTextProperty(
            ).SetVerticalJustificationToCentered()
            scalar_bar.GetLabelTextProperty().BoldOff()
            scalar_bar.GetLabelTextProperty().ItalicOff()
            scalar_bar.GetLabelTextProperty().ShadowOff()
            scalar_bar.GetLabelTextProperty().SetColor(0, 0, 0)

            # create the scalar bar widget
            scalar_bar_widget = vtk.vtkScalarBarWidget()
            scalar_bar_widget.SetInteractor(interactor)
            scalar_bar_widget.SetScalarBarActor(scalar_bar)
            scalar_bar_widget.On()

    window_to_image_filter = vtk.vtkWindowToImageFilter()
    window_to_image_filter.SetInput(render_window)
    window_to_image_filter.Update()

    writer = vtk.vtkPNGWriter()
    writer.SetFileName(output_filename)
    writer.SetInputConnection(window_to_image_filter.GetOutputPort())
    writer.Write()
Exemple #45
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
Exemple #46
0
def main():
    colors = vtk.vtkNamedColors()

    filename, wireframe, factor = get_program_parameters()

    # Read all the data from the file
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(filename)
    reader.Update()

    inputPolyData = reader.GetOutput()

    #Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()

    if factor is not None:
        triangles = vtk.vtkTriangleFilter()
        triangles.SetInputConnection(reader.GetOutputPort())
        triangles.Update()
        inputPolyData = triangles.GetOutput()
        reduction = factor
        decPro = vtk.vtkDecimatePro()
        decPro.SetInputData(inputPolyData)
        decPro.SetTargetReduction(reduction)
        decPro.PreserveTopologyOn()
        decPro.Update()
        mapper.SetInputData(decPro.GetOutput())
    else:
        mapper.SetInputConnection(reader.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if (wireframe):
        actor.GetProperty().SetLineWidth(3)
        actor.GetProperty().SetRepresentationToWireframe()

        actor.GetProperty().SetEdgeVisibility(1)
        actor.GetProperty().SetEdgeColor(0.9, 0.9, 0.4)
        actor.GetProperty().SetLineWidth(6)
        actor.GetProperty().SetPointSize(12)
        actor.GetProperty().SetRenderLinesAsTubes(1)
        actor.GetProperty().SetRenderPointsAsSpheres(1)
        actor.GetProperty().SetVertexVisibility(1)
        actor.GetProperty().SetVertexColor(0.5, 1.0, 0.8)

    prop = actor.GetProperty()
    prop.SetColor(colors.GetColor3d("Red"))

    # Setup a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Test")
    renderWindow.SetSize(600, 600)

    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
    renderer.ResetCamera()

    #Render and interact
    renderWindow.Render()

    renderWindowInteractor.Start()
Exemple #47
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
    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()
Exemple #49
0
def main():
    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(0, 0, 100.0)
    extrude.Update()

    lineMapper = vtk.vtkPolyDataMapper()
    lineMapper.SetInputData(polyData)

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

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

    back = vtk.vtkProperty()
    back.SetColor(colors.GetColor3d("Tomato"))

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    actor.SetBackfaceProperty(back)

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

    renWin = vtk.vtkRenderWindow()
    renWin.SetWindowName("EllipticalCylinder")
    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()
def main():
    angle, step, radius, uncapped, show_line = get_program_parameters()
    angle = math.radians(abs(angle))
    step = math.radians(abs(step))
    radius = abs(radius)
    # With default settings set this to 45 and you get a bowl with a flat bottom.
    start = math.radians(90)

    pts = get_line(angle, step, radius, uncapped, start)

    # Setup points and lines
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    for pt in pts:
        pt_id = points.InsertNextPoint(pt)
        if pt_id < len(pts) - 1:
            line = vtk.vtkLine()
            line.GetPointIds().SetId(0, pt_id)
            line.GetPointIds().SetId(1, pt_id + 1)
            lines.InsertNextCell(line)

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

    # Extrude the profile to make the capped sphere
    extrude = vtk.vtkRotationalExtrusionFilter()
    extrude.SetInputData(polydata)
    extrude.SetResolution(60)

    #  Visualize
    colors = vtk.vtkNamedColors()

    # To see the line
    lineMapper = vtk.vtkPolyDataMapper()
    lineMapper.SetInputData(polydata)

    lineActor = vtk.vtkActor()
    lineActor.SetMapper(lineMapper)
    lineActor.GetProperty().SetLineWidth(4)
    lineActor.GetProperty().SetColor(colors.GetColor3d('Red'))

    # To see the surface
    surfaceMapper = vtk.vtkPolyDataMapper()
    surfaceMapper.SetInputConnection(extrude.GetOutputPort())

    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(surfaceMapper)
    surfaceActor.GetProperty().SetColor(colors.GetColor3d('Khaki'))

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

    ren.AddActor(surfaceActor)
    if show_line:
        ren.AddActor(lineActor)
    ren.SetBackground(colors.GetColor3d('LightSlateGray'))

    ren.ResetCamera()
    ren.GetActiveCamera().Azimuth(0)
    ren.GetActiveCamera().Elevation(60)
    ren.ResetCameraClippingRange()

    renWin.SetSize(600, 600)
    renWin.Render()
    renWin.SetWindowName('CappedSphere')
    iren.Start()
Exemple #51
0
# Create the rest of the cow in wireframe
restMapper = vtk.vtkPolyDataMapper()
restMapper.SetInputData(clipper.GetClippedOutput())
restMapper.ScalarVisibilityOff()

restActor = vtk.vtkActor()
restActor.SetMapper(restMapper)
restActor.GetProperty().SetRepresentationToWireframe()

# Create graphics stuff
#
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(clipActor)
ren1.AddActor(cutActor)
ren1.AddActor(restActor)
ren1.SetBackground(1, 1, 1)
ren1.ResetCamera()
ren1.GetActiveCamera().Azimuth(30)
ren1.GetActiveCamera().Elevation(30)
ren1.GetActiveCamera().Dolly(1.5)
ren1.ResetCameraClippingRange()

renWin.SetSize(300, 300)
Exemple #52
0
def main():
    """
        To match the illustrations in VTKTextbook.pdf, use BkgColor as the background and
          Wheat as the cow colour.
        Also comment out the lines:
          modelActor->GetProperty()->SetSpecular(.6);
          modelActor->GetProperty()->SetSpecularPower(30);
        and use cow.g as the inout data.

    """
    file_name, figure = get_program_parameters()
    # Create renderer stuff
    #
    colors = vtk.vtkNamedColors()
    # Set the background color.
    colors.SetColor("BkgColor", [60, 93, 144, 255])

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

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

    # create pipeline
    #
    polyData = ReadPolyData(file_name)

    modelMapper = vtk.vtkPolyDataMapper()
    modelMapper.SetInputData(polyData)

    modelActor = vtk.vtkActor()
    modelActor.SetMapper(modelMapper)
    # modelActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Wheat"))
    modelActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Crimson"))
    modelActor.GetProperty().SetSpecular(.6)
    modelActor.GetProperty().SetSpecularPower(30)

    modelAxesSource = vtk.vtkAxes()
    modelAxesSource.SetScaleFactor(10)
    modelAxesSource.SetOrigin(0, 0, 0)

    modelAxesMapper = vtk.vtkPolyDataMapper()
    modelAxesMapper.SetInputConnection(modelAxesSource.GetOutputPort())

    modelAxes = vtk.vtkActor()
    modelAxes.SetMapper(modelAxesMapper)

    ren1.AddActor(modelAxes)
    modelAxes.VisibilityOff()

    # Add the actors to the renderer, set the background and size
    #
    ren1.AddActor(modelActor)
    # ren1.SetBackground(colors.GetColor3d("BkgColor"))
    ren1.SetBackground(colors.GetColor3d("Silver"))
    renWin.SetSize(640, 480)
    ren1.ResetCamera()
    ren1.GetActiveCamera().Azimuth(0)
    ren1.GetActiveCamera().SetClippingRange(.1, 1000.0)

    modelAxes.VisibilityOn()

    renWin.Render()
    renWin.Render()

    if figure == 1:
        RotateX(renWin, modelActor)
    elif figure == 2:
        RotateY(renWin, modelActor)
    elif figure == 3:
        RotateZ(renWin, modelActor)
    else:
        RotateXY(renWin, modelActor)

    renWin.EraseOff()
    iren.Start()
def dualSurfaceRendering(image1, image2):

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.PolygonSmoothingOn()
    renWin.SetSize(400, 400)

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

    # skinMesh = createMesh(image1,(int)(image1.GetScalarRange()[0]),(int)(image1.GetScalarRange()[1]-1))
    skinMesh = createMesh(image1, 0, 255)
    boneMesh = createThresholdMesh(image2, 0, 255)
    ##########################################################
    # # polydata=vtk.vtkPolyData()
    # # polydata.SetPoints(boneMesh.GetPoints())
    # splatter=vtk.vtkGaussianSplatter()
    # splatter.SetInputData(boneMesh)
    # splatter.SetRadius(0.02)
    # surface=vtk.vtkContourFilter()
    # surface.SetInputConnection(splatter.GetOutputPort())
    # surface.SetValue(0,0.01)
    # # # Convert the image to a polydata
    # # imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter()
    # # imageDataGeometryFilter.SetInputData(image2)
    # # imageDataGeometryFilter.Update()
    # mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(surface.GetOutputPort())
    # actor = vtk.vtkActor()
    # actor.SetMapper(mapper)
    # # actor.GetProperty().SetPointSize(0.01)
    #############################################################
    # sigmoidMesh = createThresholdMesh(sigmoid_image,0,1)
    # boneMesh = createThresholdMesh(image1,(int)(image1.GetScalarRange()[1]-1), (int)(image1.GetScalarRange()[1]))
    skinMapper = vtk.vtkPolyDataMapper()
    skinMapper.SetInputData(skinMesh)
    skinMapper.ScalarVisibilityOff()

    skinActor = vtk.vtkActor()
    skinActor.SetMapper(skinMapper)
    skinActor.GetProperty().SetColor(1.0, 1.0, 1.0)
    skinActor.GetProperty().SetOpacity(1.0)
    skinActor.GetProperty().SetAmbient(0.1)
    skinActor.GetProperty().SetDiffuse(0.7)
    skinActor.GetProperty().SetSpecular(0.1)

    boneMapper = vtk.vtkPolyDataMapper()
    boneMapper.SetInputData(boneMesh)
    boneMapper.ScalarVisibilityOff()

    boneActor = vtk.vtkActor()
    boneActor.SetMapper(boneMapper)
    boneActor.GetProperty().SetColor(1.0, 0.0, 0.0)
    boneActor.GetProperty().SetAmbient(0.2)
    boneActor.GetProperty().SetDiffuse(0.7)
    boneActor.GetProperty().SetSpecular(0.2)
    boneActor.GetProperty().SetOpacity(1.0)
    # boneActor.GetProperty().SetPointSize(100)

    # sigmoidMapper = vtk.vtkPolyDataMapper()
    # sigmoidMapper.SetInputData(sigmoidMesh)
    # sigmoidMapper.ScalarVisibilityOff()
    #
    # sigmoidActor = vtk.vtkActor()
    # sigmoidActor.SetMapper(sigmoidMapper)
    # sigmoidActor.GetProperty().SetColor(0.0,1.0,0.0)
    # sigmoidActor.GetProperty().SetAmbient(0.2)
    # sigmoidActor.GetProperty().SetDiffuse(0.7)
    # sigmoidActor.GetProperty().SetSpecular(0.2)
    # sigmoidActor.GetProperty().SetOpacity(1.0)

    sphere_view = vtk.vtkSphereSource()
    # sphere_view.SetOrigin([-48.96,-48.96,-48.42])
    # sphere_view.SetSpacing(0.18,0.18,0.18)
    sphere_view.SetCenter(int(-475 * 0.15), int(19 * 0.15), int(24 * 0.15))
    # sphere_view.SetCenter(int(250*0.18),int(150*0.18),int(600*0.18))
    sphere_view.SetRadius(1.0)
    # sphere_view.SetColor(0.0,1.0,1.0)
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(sphere_view.GetOutput())
    else:
        mapper.SetInputConnection(sphere_view.GetOutputPort())

    # actor
    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(mapper)
    sphere_actor.GetProperty().SetColor(1.0, 0.0, 1.0)

    ren.AddActor(boneActor)
    ren.AddActor(skinActor)
    ren.AddActor(sphere_actor)
    # ren.AddActor(sigmoidActor)
    # ren.AddActor(actor)

    iren.Initialize()
    renWin.Render()
    iren.Start()
def main():
    ##############################
    # Options
    ##############################
    """Note: Run scripts/depth_completion/save_depth_maps_raw.py first"""

    raw_dir = os.path.expanduser('~/Kitti/raw')
    drive_id = '2011_09_26_drive_0023_sync'

    vtk_window_size = (1280, 720)
    max_fps = 30.0

    # point_cloud_source = 'lidar'
    # fill_type = None

    point_cloud_source = 'depth'
    fill_type = 'multiscale'

    # Load raw data
    drive_date = drive_id[0:10]
    drive_num_str = drive_id[17:21]
    raw_data = pykitti.raw(raw_dir, drive_date, drive_num_str)

    # Check that velo length matches timestamps?
    if len(raw_data.velo_files) != len(raw_data.timestamps):
        raise ValueError('velo files and timestamps have different length!')

    frame_range = (0, len(raw_data.timestamps))

    ##############################

    min_loop_time = 1.0 / max_fps

    vtk_renderer = demo_utils.setup_vtk_renderer()
    vtk_render_window = demo_utils.setup_vtk_render_window(
        'Overlaid Point Cloud', vtk_window_size, vtk_renderer)

    # Setup camera
    current_cam = vtk_renderer.GetActiveCamera()
    current_cam.SetViewUp(0, 0, 1)
    current_cam.SetPosition(0.0, -8.0, -15.0)
    current_cam.SetFocalPoint(0.0, 0.0, 20.0)
    current_cam.Zoom(0.7)

    # Create VtkAxes
    vtk_axes = vtk.vtkAxesActor()
    vtk_axes.SetTotalLength(2, 2, 2)

    # Setup interactor
    vtk_interactor = vtk.vtkRenderWindowInteractor()
    vtk_interactor.SetRenderWindow(vtk_render_window)
    vtk_interactor.SetInteractorStyle(
        vtk_utils.ToggleActorsInteractorStyle(None, vtk_renderer, current_cam,
                                              vtk_axes))
    vtk_interactor.Initialize()

    if point_cloud_source not in ['lidar', 'depth']:
        raise ValueError(
            'Invalid point cloud source {}'.format(point_cloud_source))

    cam_p = raw_data.calib.P_rect_20

    # Point cloud
    vtk_pc = VtkPointCloudGlyph()

    # Add actors
    vtk_renderer.AddActor(vtk_axes)
    vtk_renderer.AddActor(vtk_pc.vtk_actor)

    for frame_idx in range(*frame_range):

        loop_start_time = time.time()

        print('{} / {}'.format(frame_idx, len(raw_data.timestamps) - 1))

        # Load next frame data
        load_start_time = time.time()

        rgb_image = np.asarray(raw_data.get_cam2(frame_idx))
        bgr_image = rgb_image[..., ::-1]

        if point_cloud_source == 'lidar':
            velo_points = get_velo_points(raw_data, frame_idx)

            # Transform point cloud to cam_0 frame
            velo_curr_points_padded = np.pad(velo_points, [[0, 0], [0, 1]],
                                             constant_values=1.0,
                                             mode='constant')

            cam0_curr_pc_all_padded = raw_data.calib.T_cam0_velo @ velo_curr_points_padded.T

            # Project velodyne points
            projection_start_time = time.time()
            points_in_img = calib_utils.project_pc_to_image(
                cam0_curr_pc_all_padded[0:3], cam_p)
            points_in_img_int = np.round(points_in_img).astype(np.int32)
            print('projection\t', time.time() - projection_start_time)

            image_filter = obj_utils.points_in_img_filter(
                points_in_img_int, bgr_image.shape)

            cam0_curr_pc = cam0_curr_pc_all_padded[0:3, image_filter]

            points_in_img_int_valid = points_in_img_int[:, image_filter]
            point_colours = bgr_image[points_in_img_int_valid[1],
                                      points_in_img_int_valid[0]]

        elif point_cloud_source == 'depth':
            depth_maps_dir = core.data_dir() + \
                '/depth_completion/raw/{}/depth_02_{}'.format(drive_id, fill_type)
            depth_map_path = depth_maps_dir + '/{:010d}.png'.format(frame_idx)
            depth_map = depth_map_utils.read_depth_map(depth_map_path)
            cam0_curr_pc = depth_map_utils.get_depth_point_cloud(
                depth_map, cam_p)

            point_colours = bgr_image.reshape(-1, 3)

            # Mask to valid points
            valid_mask = (cam0_curr_pc[2] != 0)
            cam0_curr_pc = cam0_curr_pc[:, valid_mask]
            point_colours = point_colours[valid_mask]
        else:
            raise ValueError('Invalid point cloud source')

        print('load\t\t', time.time() - load_start_time)

        # VtkPointCloud
        vtk_pc_start_time = time.time()
        vtk_pc.set_points(cam0_curr_pc.T, point_colours)
        print('vtk_pc\t\t', time.time() - vtk_pc_start_time)

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

        # Render
        render_start_time = time.time()
        vtk_render_window.Render()
        print('render\t\t', time.time() - render_start_time)

        # Pause to keep frame rate under max
        loop_run_time = time.time() - loop_start_time
        print('loop\t\t', loop_run_time)
        if loop_run_time < min_loop_time:
            time.sleep(min_loop_time - loop_run_time)

        print('---')

    print('Done')

    # Keep window open
    vtk_interactor.Start()
Exemple #55
0
    def ParametricObjects(self):

        parametricObjects = list()
        parametricObjects.append(vtk.vtkParametricBoy())
        parametricObjects.append(vtk.vtkParametricConicSpiral())
        parametricObjects.append(vtk.vtkParametricCrossCap())
        parametricObjects.append(vtk.vtkParametricDini())

        parametricObjects.append(vtk.vtkParametricEllipsoid())
        parametricObjects[-1].SetXRadius(0.5)
        parametricObjects[-1].SetYRadius(2.0)
        parametricObjects.append(vtk.vtkParametricEnneper())
        parametricObjects.append(vtk.vtkParametricFigure8Klein())
        parametricObjects.append(vtk.vtkParametricKlein())

        parametricObjects.append(vtk.vtkParametricMobius())
        parametricObjects[-1].SetRadius(2)
        parametricObjects[-1].SetMinimumV(-0.5)
        parametricObjects[-1].SetMaximumV(0.5)
        parametricObjects.append(vtk.vtkParametricRandomHills())
        parametricObjects[-1].AllowRandomGenerationOff()
        parametricObjects.append(vtk.vtkParametricRoman())
        parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
        parametricObjects[-1].SetN1(0.5)
        parametricObjects[-1].SetN2(0.1)

        parametricObjects.append(vtk.vtkParametricSuperToroid())
        parametricObjects[-1].SetN1(0.2)
        parametricObjects[-1].SetN2(3.0)
        parametricObjects.append(vtk.vtkParametricTorus())
        parametricObjects.append(vtk.vtkParametricSpline())
        # Add some points to the parametric spline.
        inputPoints = vtk.vtkPoints()
        vtk.vtkMath.RandomSeed(8775070)
        for i in range(10):
            x = vtk.vtkMath.Random(0.0, 1.0)
            y = vtk.vtkMath.Random(0.0, 1.0)
            z = vtk.vtkMath.Random(0.0, 1.0)
            inputPoints.InsertNextPoint(x, y, z)
        parametricObjects[-1].SetPoints(inputPoints)

        # There are only 15 objects.
        parametricFunctionSources = list()
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

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

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(parametricObjects):
            parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
            parametricFunctionSources[idx].SetParametricFunction(item)
            parametricFunctionSources[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(
                parametricFunctionSources[idx].GetOutputPort())

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

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

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

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 4

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

        rendererSize = 200

        # 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(parametricObjects) - 1):
                    continue

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

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.2, 0.3, 0.4)
                renderers[idx].ResetCamera()
                renderers[idx].GetActiveCamera().Azimuth(30)
                renderers[idx].GetActiveCamera().Elevation(-30)
                renderers[idx].GetActiveCamera().Zoom(0.9)
                renderers[idx].ResetCameraClippingRange()

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

        renderWindow.Render()

        interactor.Start()
Exemple #56
0
    def visualize(self,
                  out_path='out/',
                  outer_box=True,
                  axes=True,
                  clip_neg=False,
                  azimuth=0,
                  elevation=0,
                  n_frames=1,
                  mag=1,
                  video=False,
                  viz_type='ODF',
                  mask=None,
                  mask_roi=None,
                  skip_n=1,
                  skip_n_roi=1,
                  scale=1,
                  roi_scale=1,
                  zoom_start=1.0,
                  zoom_end=1.0,
                  top_zoom=1,
                  interact=False,
                  save_parallels=False,
                  my_cam=None,
                  compress=True,
                  roi=None,
                  corner_text='',
                  scalemap=None,
                  titles_on=True,
                  scalebar_on=True,
                  invert=False,
                  flat=False,
                  colormap='bwr',
                  global_cm=True,
                  camtilt=False,
                  axes_on=False,
                  colors=None,
                  arrows=None,
                  arrow_color=np.array([0, 0, 0]),
                  linewidth=0.1,
                  mark_slices=None,
                  z_shift=0,
                  profiles=[],
                  markers=[],
                  marker_colors=[],
                  marker_scale=1,
                  normalize_glyphs=True,
                  gamma=1,
                  density_max=1):
        log.info('Preparing to render ' + out_path)

        # Handle scalemap
        if scalemap is None:
            scalemap = util.ScaleMap(min=np.min(self.f[..., 0]),
                                     max=np.max(self.f[..., 0]))

        # Prepare output
        util.mkdir(out_path)

        # Setup vtk renderers
        renWin = vtk.vtkRenderWindow()

        if not interact:
            renWin.SetOffScreenRendering(1)
        if isinstance(viz_type, str):
            viz_type = [viz_type]

        # Rows and columns
        cols = len(viz_type)
        if roi is None:
            rows = 1
        else:
            rows = 2

        renWin.SetSize(np.int(500 * mag * cols), np.int(500 * mag * rows))

        # Select background color
        if save_parallels:
            bg_color = [1, 1, 1]
            line_color = np.array([0, 0, 0])
            line_bcolor = np.array([1, 1, 1])
        else:
            if not invert:
                bg_color = [0, 0, 0]
                line_color = np.array([1, 1, 1])
                line_bcolor = np.array([0, 0, 0])
            else:
                bg_color = [1, 1, 1]
                line_color = np.array([0, 0, 0])
                line_bcolor = np.array([1, 1, 1])

        # For each viz_type
        rens = []
        zoom_start = []
        zoom_end = []
        for row in range(rows):
            for col in range(cols):
                # Render
                ren = window.Scene()
                rens.append(ren)
                if viz_type[col] is 'Density':
                    ren.background([0, 0, 0])
                    line_color = np.array([1, 1, 1])
                else:
                    ren.background(bg_color)
                ren.SetViewport(col / cols, (rows - row - 1) / rows,
                                (col + 1) / cols, (rows - row) / rows)
                renWin.AddRenderer(ren)
                iren = vtk.vtkRenderWindowInteractor()
                iren.SetRenderWindow(renWin)

                # Mask
                if mask is None:
                    mask = np.ones((self.X, self.Y, self.Z), dtype=np.bool)
                if mask_roi is None:
                    mask_roi = mask

                # Main vs roi
                if row == 0:
                    data = self.f
                    skip_mask = np.zeros(mask.shape, dtype=np.bool)
                    skip_mask[::skip_n, ::skip_n, ::skip_n] = 1
                    my_mask = np.logical_and(mask, skip_mask)
                    scale = scale
                    scalemap = scalemap
                    if np.sum(my_mask) == 0:
                        my_mask[0, 0, 0] = True
                else:
                    data = self.f[roi[0][0]:roi[1][0], roi[0][1]:roi[1][1],
                                  roi[0][2]:roi[1][2], :]
                    roi_mask = mask_roi[roi[0][0]:roi[1][0],
                                        roi[0][1]:roi[1][1],
                                        roi[0][2]:roi[1][2]]
                    skip_mask = np.zeros(roi_mask.shape, dtype=np.bool)
                    skip_mask[::skip_n_roi, ::skip_n_roi, ::skip_n_roi] = 1
                    my_mask = np.logical_and(roi_mask, skip_mask)
                    scale = roi_scale
                    scalemap = scalemap

                # Add visuals to renderer
                if viz_type[col] == "ODF":
                    renWin.SetMultiSamples(4)
                    log.info('Rendering ' + str(np.sum(my_mask)) + ' ODFs')
                    fodf_spheres = viz.odf_sparse(data,
                                                  self.Binv,
                                                  sphere=self.sphere,
                                                  scale=skip_n * scale * 0.5,
                                                  norm=False,
                                                  colormap=colormap,
                                                  mask=my_mask,
                                                  global_cm=global_cm,
                                                  scalemap=scalemap,
                                                  odf_sphere=False,
                                                  flat=flat,
                                                  normalize=normalize_glyphs)

                    ren.add(fodf_spheres)
                elif viz_type[col] == "ODF Sphere":
                    renWin.SetMultiSamples(4)
                    log.info('Rendering ' + str(np.sum(my_mask)) + ' ODFs')
                    fodf_spheres = viz.odf_sparse(data,
                                                  self.Binv,
                                                  sphere=self.sphere,
                                                  scale=skip_n * scale * 0.5,
                                                  norm=False,
                                                  colormap=colormap,
                                                  mask=my_mask,
                                                  global_cm=global_cm,
                                                  scalemap=scalemap,
                                                  odf_sphere=True,
                                                  flat=flat)
                    ren.add(fodf_spheres)
                elif viz_type[col] == "Ellipsoid":
                    renWin.SetMultiSamples(4)
                    log.info(
                        'Warning: scaling is not implemented for ellipsoids')
                    log.info('Rendering ' + str(np.sum(my_mask)) +
                             ' ellipsoids')
                    fodf_peaks = viz.tensor_slicer_sparse(data,
                                                          sphere=self.sphere,
                                                          scale=skip_n *
                                                          scale * 0.5,
                                                          mask=my_mask)
                    ren.add(fodf_peaks)
                elif viz_type[col] == "Peak":
                    renWin.SetMultiSamples(4)
                    log.info('Rendering ' + str(np.sum(my_mask)) + ' peaks')
                    fodf_peaks = viz.peak_slicer_sparse(
                        data,
                        self.Binv,
                        self.sphere.vertices,
                        linewidth=linewidth,
                        scale=skip_n * scale * 0.5,
                        colors=colors,
                        mask=my_mask,
                        scalemap=scalemap,
                        normalize=normalize_glyphs)
                    fodf_peaks.GetProperty().LightingOn()
                    fodf_peaks.GetProperty().SetDiffuse(
                        0.4)  # Doesn't work (VTK bug I think)
                    fodf_peaks.GetProperty().SetAmbient(0.15)
                    fodf_peaks.GetProperty().SetSpecular(0)
                    fodf_peaks.GetProperty().SetSpecularPower(0)

                    ren.add(fodf_peaks)
                elif viz_type[col] == "Principal":
                    log.info(
                        'Warning: scaling is not implemented for principals')
                    log.info('Rendering ' + str(np.sum(my_mask)) +
                             ' principals')
                    fodf_peaks = viz.principal_slicer_sparse(
                        data,
                        self.Binv,
                        self.sphere.vertices,
                        scale=skip_n * scale * 0.5,
                        mask=my_mask)
                    ren.add(fodf_peaks)
                elif viz_type[col] == "Density":
                    renWin.SetMultiSamples(0)  # Must be zero for smooth
                    # renWin.SetAAFrames(4) # Slow antialiasing for volume renders
                    log.info('Rendering density')
                    gamma_corr = np.where(data[..., 0] > 0,
                                          data[..., 0]**gamma, data[..., 0])
                    scalemap.max = density_max * scalemap.max**gamma
                    volume = viz.density_slicer(gamma_corr, scalemap)
                    ren.add(volume)

                X = np.float(data.shape[0])
                Y = np.float(data.shape[1])
                Z = np.float(data.shape[2]) - z_shift

                # Titles
                if row == 0 and titles_on:
                    viz.add_text(ren, viz_type[col], 0.5, 0.96, mag)

                # Scale bar
                if col == cols - 1 and not save_parallels and scalebar_on:
                    yscale = 1e-3 * self.vox_dim[1] * data.shape[1]
                    yscale_label = '{:.2g}'.format(yscale) + ' um'
                    viz.add_text(ren, yscale_label, 0.5, 0.03, mag)
                    viz.draw_scale_bar(ren, X, Y, Z, [1, 1, 1])

                # Corner text
                if row == rows - 1 and col == 0 and titles_on:
                    viz.add_text(ren, corner_text, 0.03, 0.03, mag, ha='left')

                # Draw boxes
                Nmax = np.max([X, Y, Z])
                if outer_box:
                    if row == 0:
                        viz.draw_outer_box(
                            ren,
                            np.array([[0, 0, 0], [X, Y, Z]]) - 0.5, line_color)
                    if row == 1:
                        viz.draw_outer_box(
                            ren,
                            np.array([[0, 0, 0], [X, Y, Z]]) - 0.5, [0, 1, 1])

                # Add colored axes
                if axes:
                    viz.draw_axes(ren, np.array([[0, 0, 0], [X, Y, Z]]) - 0.5)

                # Add custom arrows
                if arrows is not None:
                    for i in range(arrows.shape[0]):
                        viz.draw_single_arrow(ren,
                                              arrows[i, 0, :],
                                              arrows[i, 1, :],
                                              color=arrow_color)
                        viz.draw_unlit_line(ren, [
                            np.array([arrows[i, 0, :], [X / 2, Y / 2, Z / 2]])
                        ], [arrow_color],
                                            lw=0.3,
                                            scale=1.0)

                # Draw roi box
                if row == 0 and roi is not None:
                    maxROI = np.max([
                        roi[1][0] - roi[0][0], roi[1][1] - roi[0][1],
                        roi[1][2] - roi[0][2]
                    ])
                    maxXYZ = np.max([self.X, self.Y, self.Z])
                    viz.draw_outer_box(ren,
                                       roi, [0, 1, 1],
                                       lw=0.3 * maxXYZ / maxROI)
                    viz.draw_axes(ren, roi, lw=0.3 * maxXYZ / maxROI)

                # Draw marked slices
                if mark_slices is not None:
                    for slicen in mark_slices:
                        md = np.max((X, Z))
                        frac = slicen / data.shape[1]
                        rr = 0.83 * md
                        t1 = 0
                        t2 = np.pi / 2
                        t3 = np.pi
                        t4 = 3 * np.pi / 2
                        points = [
                            np.array([[
                                X / 2 + rr * np.cos(t1), frac * Y,
                                Z / 2 + rr * np.sin(t1)
                            ],
                                      [
                                          X / 2 + rr * np.cos(t2), frac * Y,
                                          Z / 2 + rr * np.sin(t2)
                                      ],
                                      [
                                          X / 2 + rr * np.cos(t3), frac * Y,
                                          Z / 2 + rr * np.sin(t3)
                                      ],
                                      [
                                          X / 2 + rr * np.cos(t4), frac * Y,
                                          Z / 2 + rr * np.sin(t4)
                                      ],
                                      [
                                          X / 2 + rr * np.cos(t1), frac * Y,
                                          Z / 2 + rr * np.sin(t1)
                                      ],
                                      [
                                          X / 2 + rr * np.cos(t2), frac * Y,
                                          Z / 2 + rr * np.sin(t2)
                                      ]])
                        ]
                        viz.draw_unlit_line(ren,
                                            points,
                                            6 * [line_color + 0.6],
                                            lw=0.3,
                                            scale=1.0)

                # Draw markers
                for i, marker in enumerate(markers):
                    # Draw sphere
                    source = vtk.vtkSphereSource()
                    source.SetCenter(marker)
                    source.SetRadius(marker_scale)
                    source.SetThetaResolution(30)
                    source.SetPhiResolution(30)

                    # mapper
                    mapper = vtk.vtkPolyDataMapper()
                    mapper.SetInputConnection(source.GetOutputPort())

                    # actor
                    actor = vtk.vtkActor()
                    actor.SetMapper(mapper)
                    actor.GetProperty().SetColor(marker_colors[i, :])
                    actor.GetProperty().SetLighting(0)
                    ren.AddActor(actor)

                # Draw profile lines
                colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

                for i, profile in enumerate(profiles):
                    import pdb
                    pdb.set_trace()
                    n_seg = profile.shape[0]
                    viz.draw_unlit_line(ren, [profile],
                                        n_seg * [colors[i, :]],
                                        lw=0.5,
                                        scale=1.0)

                    # Draw sphere
                    source = vtk.vtkSphereSource()
                    source.SetCenter(profile[0])
                    source.SetRadius(1)
                    source.SetThetaResolution(30)
                    source.SetPhiResolution(30)

                    # mapper
                    mapper = vtk.vtkPolyDataMapper()
                    mapper.SetInputConnection(source.GetOutputPort())

                    # actor
                    actor = vtk.vtkActor()
                    actor.SetMapper(mapper)
                    # actor.GetProperty().SetColor(colors[i,:])
                    actor.GetProperty().SetLighting(0)

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

                # Setup cameras
                Rmax = np.linalg.norm([Z / 2, X / 2, Y / 2])
                Rcam_rad = Rmax / np.tan(np.pi / 12)
                Ntmax = np.max([X, Y])
                ZZ = Z
                if ZZ > Ntmax:
                    Rcam_edge = np.max([X / 2, Y / 2])
                else:
                    Rcam_edge = np.min([X / 2, Y / 2])
                Rcam = Rcam_edge + Rcam_rad
                if my_cam is None:
                    cam = ren.GetActiveCamera()
                    if camtilt:
                        cam.SetPosition(
                            ((X - 1) / 2, (Y - 1) / 2, (Z - 1) / 2 + Rcam))
                        cam.SetViewUp((-1, 0, 1))
                        if axes_on:
                            max_dim = np.max((X, Z))
                            viz.draw_unlit_line(ren, [
                                np.array([[(X - max_dim) / 2, Y / 2, Z / 2],
                                          [X / 2, Y / 2, +Z / 2],
                                          [X / 2, Y / 2, (Z + max_dim) / 2]])
                            ],
                                                3 * [line_color],
                                                lw=max_dim / 250,
                                                scale=1.0)
                    else:
                        cam.SetPosition(
                            ((X - 1) / 2 + Rcam, (Y - 1) / 2, (Z - 1) / 2))
                        cam.SetViewUp((0, 0, 1))
                    cam.SetFocalPoint(((X - 1) / 2, (Y - 1) / 2, (Z - 1) / 2))
                    #ren.reset_camera()
                else:
                    ren.set_camera(*my_cam)
                ren.azimuth(azimuth)
                ren.elevation(elevation)

                # Set zooming
                if save_parallels:
                    zoom_start.append(1.7)
                    zoom_end.append(1.7)
                else:
                    if row == 0:
                        zoom_start.append(1.3 * top_zoom)
                        zoom_end.append(1.3 * top_zoom)
                    else:
                        zoom_start.append(1.3)
                        zoom_end.append(1.3)

        # Setup writer
        writer = vtk.vtkTIFFWriter()
        if not compress:
            writer.SetCompressionToNoCompression()

        # Execute renders
        az = 90
        naz = np.ceil(360 / n_frames)
        log.info('Rendering ' + out_path)
        if save_parallels:
            # Parallel rendering for summaries
            filenames = ['yz', 'xy', 'xz']
            zooms = [zoom_start[0], 1.0, 1.0]
            azs = [90, -90, 0]
            els = [0, 0, 90]
            ren.projection(proj_type='parallel')
            ren.reset_camera()
            for i in tqdm(range(3)):
                ren.zoom(zooms[i])
                ren.azimuth(azs[i])
                ren.elevation(els[i])
                ren.reset_clipping_range()
                renderLarge = vtk.vtkRenderLargeImage()
                renderLarge.SetMagnification(1)
                renderLarge.SetInput(ren)
                renderLarge.Update()
                writer.SetInputConnection(renderLarge.GetOutputPort())
                writer.SetFileName(out_path + filenames[i] + '.tif')
                writer.Write()
        else:
            # Rendering for movies
            for j, ren in enumerate(rens):
                ren.zoom(zoom_start[j])
            for i in tqdm(range(n_frames)):
                for j, ren in enumerate(rens):
                    ren.zoom(1 + ((zoom_end[j] - zoom_start[j]) / n_frames))
                    ren.azimuth(az)
                    ren.reset_clipping_range()

                renderLarge = vtk.vtkRenderLargeImage()
                renderLarge.SetMagnification(1)
                renderLarge.SetInput(ren)
                renderLarge.Update()
                writer.SetInputConnection(renderLarge.GetOutputPort())
                if n_frames != 1:
                    writer.SetFileName(out_path + str(i).zfill(3) + '.tif')
                else:
                    writer.SetFileName(out_path + '.tif')
                writer.Write()
                az = naz

        # Interactive
        if interact:
            window.show(ren)

        # Generate video (requires ffmpeg)
        if video:
            log.info('Generating video from frames')
            fps = np.ceil(n_frames / 12)
            subprocess.call([
                'ffmpeg', '-nostdin', '-y', '-framerate',
                str(fps), '-loglevel', 'panic', '-i',
                out_path + '%03d' + '.png', '-pix_fmt', 'yuvj420p', '-vcodec',
                'mjpeg', out_path[:-1] + '.avi'
            ])
            # subprocess.call(['rm', '-r', out_path])

        return my_cam
def main():
    colors = vtk.vtkNamedColors()

    file_name = get_program_parameters()

    colors.SetColor('BkgColor', [51, 77, 102, 255])

    # Create the renderer, the render window, and the interactor. The renderer
    # draws into the render window, the interactor enables mouse- and
    # keyboard-based interaction with the scene.
    ren = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    # The following reader is used to read a series of 2D slices (images)
    # that compose the volume. The slice dimensions are set, and the
    # pixel spacing. The data Endianness must also be specified. The reader
    # uses the FilePrefix in combination with the slice number to construct
    # filenames using the format FilePrefix.%d. (In this case the FilePrefix
    # is the root name of the file: quarter.)
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(file_name)

    # The volume will be displayed by ray-cast alpha compositing.
    # A ray-cast mapper is needed to do the ray-casting.
    volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volume_mapper.SetInputConnection(reader.GetOutputPort())

    # The color transfer function maps voxel intensities to colors.
    # It is modality-specific, and often anatomy-specific as well.
    # The goal is to one color for flesh (between 500 and 1000)
    # and another color for bone (1150 and over).
    volume_color = vtk.vtkColorTransferFunction()
    volume_color.AddRGBPoint(0, 0.0, 0.0, 0.0)
    volume_color.AddRGBPoint(500, 240.0 / 255.0, 184.0 / 255.0, 160.0 / 255.0)
    volume_color.AddRGBPoint(1000, 240.0 / 255.0, 184.0 / 255.0, 160.0 / 255.0)
    volume_color.AddRGBPoint(1150, 1.0, 1.0, 240.0 / 255.0)  # Ivory

    # The opacity transfer function is used to control the opacity
    # of different tissue types.
    volume_scalar_opacity = vtk.vtkPiecewiseFunction()
    volume_scalar_opacity.AddPoint(0, 0.00)
    volume_scalar_opacity.AddPoint(500, 0.15)
    volume_scalar_opacity.AddPoint(1000, 0.15)
    volume_scalar_opacity.AddPoint(1150, 0.85)

    # The gradient opacity function is used to decrease the opacity
    # in the 'flat' regions of the volume while maintaining the opacity
    # at the boundaries between tissue types.  The gradient is measured
    # as the amount by which the intensity changes over unit distance.
    # For most medical data, the unit distance is 1mm.
    volume_gradient_opacity = vtk.vtkPiecewiseFunction()
    volume_gradient_opacity.AddPoint(0, 0.0)
    volume_gradient_opacity.AddPoint(90, 0.5)
    volume_gradient_opacity.AddPoint(100, 1.0)

    # The VolumeProperty attaches the color and opacity functions to the
    # volume, and sets other volume properties.  The interpolation should
    # be set to linear to do a high-quality rendering.  The ShadeOn option
    # turns on directional lighting, which will usually enhance the
    # appearance of the volume and make it look more '3D'.  However,
    # the quality of the shading depends on how accurately the gradient
    # of the volume can be calculated, and for noisy data the gradient
    # estimation will be very poor.  The impact of the shading can be
    # decreased by increasing the Ambient coefficient while decreasing
    # the Diffuse and Specular coefficient.  To increase the impact
    # of shading, decrease the Ambient and increase the Diffuse and Specular.
    volume_property = vtk.vtkVolumeProperty()
    volume_property.SetColor(volume_color)
    volume_property.SetScalarOpacity(volume_scalar_opacity)
    volume_property.SetGradientOpacity(volume_gradient_opacity)
    volume_property.SetInterpolationTypeToLinear()
    volume_property.ShadeOn()
    volume_property.SetAmbient(0.4)
    volume_property.SetDiffuse(0.6)
    volume_property.SetSpecular(0.2)

    # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
    # and orientation of the volume in world coordinates.
    volume = vtk.vtkVolume()
    volume.SetMapper(volume_mapper)
    volume.SetProperty(volume_property)

    # Finally, add the volume to the renderer
    ren.AddViewProp(volume)

    # Set up an initial view of the volume.  The focal point will be the
    # center of the volume, and the camera position will be 400mm to the
    # patient's left (which is our right).
    camera = ren.GetActiveCamera()
    c = volume.GetCenter()
    camera.SetViewUp(0, 0, -1)
    camera.SetPosition(c[0], c[1] - 400, c[2])
    camera.SetFocalPoint(c[0], c[1], c[2])
    camera.Azimuth(30.0)
    camera.Elevation(30.0)

    # Set a background color for the renderer
    ren.SetBackground(colors.GetColor3d('BkgColor'))

    # Increase the size of the render window
    ren_win.SetSize(640, 480)
    ren_win.SetWindowName('MedicalDemo4')

    # Interact with the data.
    iren.Start()
def main():
    colors = vtk.vtkNamedColors()

    # Generate an image data set with multiple attribute arrays to probe and view
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-3, 3, -3, 3, -3, 3)
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())
    brown = vtk.vtkBrownianPoints()
    brown.SetMinimumSpeed(0.5)
    brown.SetMaximumSpeed(1.0)
    brown.SetInputConnection(grad.GetOutputPort())
    elev = vtk.vtkElevationFilter()
    elev.SetLowPoint(-3, -3, -3)
    elev.SetHighPoint(3, 3, 3)
    elev.SetInputConnection(brown.GetOutputPort())

    # Updating here because I will need to probe scalar ranges before
    # the render window updates the pipeline
    elev.Update()

    # Set up parallel coordinates representation to be used in View
    rep = vtk.vtkParallelCoordinatesRepresentation()
    rep.SetInputConnection(elev.GetOutputPort())
    rep.SetInputArrayToProcess(0, 0, 0, 0, 'RTDataGradient')
    rep.SetInputArrayToProcess(1, 0, 0, 0, 'RTData')
    rep.SetInputArrayToProcess(2, 0, 0, 0, 'Elevation')
    rep.SetInputArrayToProcess(3, 0, 0, 0, 'BrownianVectors')
    rep.SetUseCurves(0)  # set to 1 to use smooth curves
    rep.SetLineOpacity(0.5)
    rep.SetAxisColor(colors.GetColor3d('Gold'))
    rep.SetLineColor(colors.GetColor3d('MistyRose'))

    # Set up the Parallel Coordinates View and hook in representation
    view = vtk.vtkParallelCoordinatesView()
    view.SetRepresentation(rep)
    view.SetInspectMode(view.VTK_INSPECT_SELECT_DATA)
    view.SetBrushOperatorToReplace()
    view.SetBrushModeToLasso()

    # Create a annotation link to access selection in parallel coordinates view
    annotationLink = vtk.vtkAnnotationLink()
    # If you don't set the FieldType explicitly it ends up as UNKNOWN
    # (as of 21 Feb 2010)
    # See vtkSelectionNode doc for field and content type enum values
    annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)  # Point
    annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)  # Indices
    # Update before passing annotationLink to vtkExtractSelection
    annotationLink.Update()
    # Connect the annotation link to the parallel coordinates representation
    rep.SetAnnotationLink(annotationLink)

    # Extract portion of data corresponding to parallel coordinates selection
    extract = vtk.vtkExtractSelection()
    extract.SetInputConnection(0, elev.GetOutputPort())
    extract.SetInputConnection(1, annotationLink.GetOutputPort(2))

    def update_render_windows(obj, event):
        '''
        Handle updating of RenderWindow since it's not a 'View'
        and so not covered by vtkViewUpdater

        :param obj:
        :param event:
        :return:
        '''
        # ren.ResetCamera()
        renWin.Render()

    # Set up callback to update 3d render window when selections are changed in
    # parallel coordinates view
    annotationLink.AddObserver('AnnotationChangedEvent', update_render_windows)

    def toggle_inspectors(obj, event):

        if view.GetInspectMode() == 0:
            view.SetInspectMode(1)
        else:
            view.SetInspectMode(0)

    # Set up callback to toggle between inspect modes (manip axes & select data)
    view.GetInteractor().AddObserver('UserEvent', toggle_inspectors)

    # 3D outline of image data bounds
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(elev.GetOutputPort())
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)

    # Build the lookup table for the 3d data scalar colors (brown to white)
    lut = vtk.vtkLookupTable()
    lut.SetTableRange(0, 256)
    lut.SetHueRange(0.1, 0.1)
    lut.SetSaturationRange(1.0, 0.1)
    lut.SetValueRange(0.4, 1.0)
    lut.Build()

    # Set up the 3d rendering parameters
    # of the image data which is selected in parallel coordinates
    coloring_by = 'Elevation'
    dataMapper = vtk.vtkDataSetMapper()
    dataMapper.SetInputConnection(extract.GetOutputPort())
    dataMapper.SetScalarModeToUsePointFieldData()
    dataMapper.SetColorModeToMapScalars()
    data = elev.GetOutputDataObject(0).GetPointData()
    dataMapper.ScalarVisibilityOn()
    dataMapper.SetScalarRange(data.GetArray(coloring_by).GetRange())
    dataMapper.SetLookupTable(lut)
    dataMapper.SelectColorArray(coloring_by)
    dataActor = vtk.vtkActor()
    dataActor.SetMapper(dataMapper)
    dataActor.GetProperty().SetRepresentationToPoints()
    dataActor.GetProperty().SetPointSize(10)

    # Set up the 3d render window and add both actors
    ren = vtk.vtkRenderer()
    ren.AddActor(outlineActor)
    ren.AddActor(dataActor)

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetWindowName('ParallelCoordinatesExtraction')

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()

    # Finalize parallel coordinates view and start interaction event loop
    view.GetRenderWindow().SetSize(600, 300)
    view.GetRenderWindow().SetWindowName('ParallelCoordinatesExtraction')
    view.GetRenderer().GradientBackgroundOn()
    view.GetRenderer().SetBackground2(colors.GetColor3d('DarkBlue'))
    view.GetRenderer().SetBackground(colors.GetColor3d('MidnightBlue'))

    view.ResetCamera()
    view.Render()
    view.GetInteractor().Start()
Exemple #59
0
def main():
    colors = vtk.vtkNamedColors()

    # Initially, set up the points to be an equilateral triangle. Note that the
    # first point is the same as the last point to make this a closed curve when
    # I create the vtkPolyLine.
    points = vtk.vtkPoints()
    for i in range(4):
        points.InsertNextPoint(cos(2.0 * pi * i / 3), sin(2 * pi * i / 3.0),
                               0.0)

    outline_pd = as_polyline(points, LEVEL)
    # You have already gone through the trouble of putting the points in the
    # right places - so "all" you need to do now is to create polygons from the
    # points that are in the vtkPoints.

    # The points that are passed in, have an overlap of the beginning and the
    # end. For this next trick, I will need a list of the indices in the
    # vtkPoints. They're consecutive, so thats pretty straightforward.

    indices = [
        i for i in range(outline_pd.GetPoints().GetNumberOfPoints() + 1)
    ]
    triangles = vtk.vtkCellArray()

    # Set this up for each of the initial sides, then call the recursive function.
    stride = (len(indices) - 1) // 3

    # The cell data will allow us to color the triangles based on the level of
    # the iteration of the Koch snowflake.
    data = vtk.vtkIntArray()
    data.SetNumberOfComponents(0)
    data.SetName("Iteration Level")

    # This is the starting triangle.
    t = vtk.vtkTriangle()
    t.GetPointIds().SetId(0, 0)
    t.GetPointIds().SetId(1, stride)
    t.GetPointIds().SetId(2, 2 * stride)
    triangles.InsertNextCell(t)
    data.InsertNextValue(0)

    as_triangles(indices[0:stride + 1], triangles, 1, data)
    as_triangles(indices[stride:2 * stride + 1], triangles, 1, data)
    as_triangles(indices[2 * stride:-1], triangles, 1, data)

    triangle_pd = vtk.vtkPolyData()
    triangle_pd.SetPoints(outline_pd.GetPoints())
    triangle_pd.SetPolys(triangles)
    triangle_pd.GetCellData().SetScalars(data)

    # ---------------- #
    # rendering stuff  #
    # ---------------- #
    outline_mapper = vtk.vtkPolyDataMapper()
    outline_mapper.SetInputData(outline_pd)

    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(256)
    lut.SetHueRange(0.6, 0.6)
    lut.SetSaturationRange(0.0, 1.0)
    lut.Build()

    triangle_mapper = vtk.vtkPolyDataMapper()
    triangle_mapper.SetInputData(triangle_pd)
    triangle_mapper.SetScalarRange(0.0, LEVEL)
    triangle_mapper.SetLookupTable(lut)

    outline_actor = vtk.vtkActor()
    outline_actor.SetMapper(outline_mapper)

    triangle_actor = vtk.vtkActor()
    triangle_actor.SetMapper(triangle_mapper)

    outline_ren = vtk.vtkRenderer()
    outline_ren.AddActor(outline_actor)
    outline_ren.SetViewport(0.0, 0.0, 0.5, 1.0)

    triangle_ren = vtk.vtkRenderer()
    triangle_ren.AddActor(triangle_actor)
    triangle_ren.SetViewport(0.5, 0.0, 1.0, 1.0)
    triangle_ren.SetActiveCamera(outline_ren.GetActiveCamera())

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(outline_ren)
    renw.AddRenderer(triangle_ren)
    renw.SetSize(800, 400)

    outline_ren.SetBackground(colors.GetColor3d("Maroon"))
    triangle_ren.SetBackground(colors.GetColor3d("Maroon"))

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

    outline_ren.ResetCamera()
    renw.Render()
    iren.Start()
def dual_volumeRendering(image, image2, lowerThreshold, upperThreshold,
                         sigmoid_image):

    color = vtk.vtkColorTransferFunction()
    color.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color.AddRGBPoint(upperThreshold, 1.0, 1.0, 1.0)

    opacity = vtk.vtkPiecewiseFunction()
    opacity.AddPoint(0, 0.0)
    opacity.AddPoint(lowerThreshold, 0.0)
    opacity.AddPoint(upperThreshold, 1)

    gradient = vtk.vtkPiecewiseFunction()
    gradient.AddPoint(0, 0.0)
    # gradient.AddPoint(90, 0.5)
    gradient.AddPoint(255, 1.0)

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(color)
    volumeProperty.SetScalarOpacity(opacity)
    volumeProperty.SetGradientOpacity(gradient)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()
    volumeProperty.SetAmbient(0.1)
    volumeProperty.SetDiffuse(0.7)
    volumeProperty.SetSpecular(0.1)

    color2 = vtk.vtkColorTransferFunction()
    color2.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color2.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color2.AddRGBPoint(upperThreshold, 1.0, 0.0, 0.0)

    opacity2 = vtk.vtkPiecewiseFunction()
    opacity2.AddPoint(0, 0.0)
    opacity2.AddPoint(lowerThreshold, 0.0)
    opacity2.AddPoint(upperThreshold, 1.0)

    gradient2 = vtk.vtkPiecewiseFunction()
    gradient2.AddPoint(0, 0.0)
    # gradient2.AddPoint(90, 0.5)
    # gradient2.AddPoint(100,1.0)
    gradient2.AddPoint(255, 1.0)

    volumeProperty2 = vtk.vtkVolumeProperty()
    volumeProperty2.SetColor(color2)
    volumeProperty2.SetScalarOpacity(opacity2)
    volumeProperty2.SetGradientOpacity(gradient2)
    volumeProperty2.SetInterpolationTypeToLinear()
    volumeProperty2.ShadeOn()
    volumeProperty2.SetAmbient(0.1)
    volumeProperty2.SetDiffuse(1.0)
    volumeProperty2.SetSpecular(0.1)

    #######################################
    color3 = vtk.vtkColorTransferFunction()
    color3.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color3.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color3.AddRGBPoint(upperThreshold, 0.0, 1.0, 0.0)

    opacity3 = vtk.vtkPiecewiseFunction()
    opacity3.AddPoint(0, 0.0)
    opacity3.AddPoint(lowerThreshold, 0.0)
    opacity3.AddPoint(upperThreshold, 1)

    gradient3 = vtk.vtkPiecewiseFunction()
    gradient3.AddPoint(0, 0.0)
    # gradient.AddPoint(90, 0.5)
    gradient3.AddPoint(255, 1.0)

    volumeProperty3 = vtk.vtkVolumeProperty()
    volumeProperty3.SetColor(color3)
    volumeProperty3.SetScalarOpacity(opacity)
    volumeProperty3.SetGradientOpacity(gradient)
    volumeProperty3.SetInterpolationTypeToLinear()
    volumeProperty3.ShadeOn()
    volumeProperty3.SetAmbient(0.1)
    volumeProperty3.SetDiffuse(0.7)
    volumeProperty3.SetSpecular(0.1)
    ###########################################

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputData(image)

    volumeMapper2 = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper2.SetInputData(image2)

    volumeMapper3 = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper3.SetInputData(sigmoid_image)

    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)
    volume.Update()

    volume2 = vtk.vtkVolume()
    volume2.SetMapper(volumeMapper2)
    volume2.SetProperty(volumeProperty2)
    volume2.Update()

    volume3 = vtk.vtkVolume()
    volume3.SetMapper(volumeMapper3)
    volume3.SetProperty(volumeProperty3)
    volume3.Update()

    sphere_view = vtk.vtkSphereSource()
    sphere_view.SetCenter(30, 0, 550)
    sphere_view.SetRadius(5.0)
    # sphere_view.SetColor(0.0,1.0,1.0)
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(sphere_view.GetOutput())
    else:
        mapper.SetInputConnection(sphere_view.GetOutputPort())

    # actor
    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(mapper)
    sphere_actor.GetProperty().SetColor(1.0, 0.0, 1.0)

    ren = vtk.vtkRenderer()
    ren.AddActor(sphere_actor)
    # ren.AddActor(vol2_actor)
    ren.AddViewProp(volume)
    ren.AddViewProp(volume2)
    ren.AddViewProp(volume3)
    ren.SetBackground(0, 0, 0)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(400, 400)

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

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