def vtkRenderWindowInteractorConeExample():
    """Like it says, just a simple example
    """
    # create root window
    root = Tkinter.Tk()

    # create vtkTkRenderWidget
    pane = vtkTkRenderWindowInteractor(root, width=300, height=300)
    pane.Initialize()

    def quit(obj=root):
        obj.quit()

    pane.AddObserver("ExitEvent", lambda o,e,q=quit: q())

    ren = vtk.vtkRenderer()
    pane.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
    
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # pack the pane into the tk root
    pane.pack(fill='both', expand=1)
    pane.Start()

    # start the tk mainloop
    root.mainloop()
def make_sphere():
    global renderer
    # ---------------------------------------------------------------
    # The following code is identical to render_demo.py...
    # ---------------------------------------------------------------
    # create a sphere
    sphere_src = vtk.vtkSphereSource()
    sphere_src.SetRadius(1.0)
    sphere_src.SetCenter(0.0, 0.0, 0.0)
    sphere_src.SetThetaResolution(20)
    sphere_src.SetPhiResolution(20)
    # extract the edges
    edge_extractor = vtk.vtkExtractEdges()
    edge_extractor.SetInputConnection(sphere_src.GetOutputPort())
    # map sphere and edges separately
    sphere_mapper = vtk.vtkPolyDataMapper()
    sphere_mapper.SetInputConnection(sphere_src.GetOutputPort())
    edge_mapper = vtk.vtkPolyDataMapper()
    edge_mapper.SetInputConnection(edge_extractor.GetOutputPort())
    # define different rendering styles for sphere and edges
    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(sphere_mapper)
    sphere_actor.GetProperty().SetColor(1, 0.5, 0)
    edge_actor = vtk.vtkActor()
    edge_actor.SetMapper(edge_mapper)
    edge_actor.GetProperty().SetColor(0, 0.5, 0)
    edge_actor.GetProperty().SetLineWidth(3)
    # add resulting primitives to renderer
    renderer.AddActor(sphere_actor)
    renderer.AddActor(edge_actor)
Exemplo n.º 3
0
def test(points, springs1, springs2):
    app = QApplication(sys.argv)
    window = Viewer3D.SimpleView()

    polydata1 = GeneratePolydata.generateLinePolydata(points, springs1)
    polydata2 = GeneratePolydata.generateLinePolydata(points, springs2)

    mapper1 = vtk.vtkPolyDataMapper()
    mapper1.SetInputData(polydata1)
    actor1 = vtk.vtkActor()
    actor1.SetMapper(mapper1)

    mapper2 = vtk.vtkPolyDataMapper()
    mapper2.SetInputData(polydata2)
    actor2 = vtk.vtkActor()
    actor2.SetMapper(mapper2)

    actor1.GetProperty().SetColor(1,0,0)
    actor2.GetProperty().SetColor(0,1,0.5)

    window.ren.AddActor(actor1)
    window.ren.AddActor(actor2)

    window.start(app)
    return
Exemplo n.º 4
0
    def __init__(self):
        self.files = []
        self.timestep = -1

        self.geometry = vtk.vtkUnstructuredGridReader()
        self.geometry_mapper = vtk.vtkDataSetMapper()
        self.geometry_actor = vtk.vtkActor()

        self.positions = vtk.vtkUnstructuredGridReader()
        self.positions_mapper = vtk.vtkDataSetMapper()
        self.positions_actor = vtk.vtkActor()

        self.geometry_mapper.SetInput(self.geometry.GetOutput())
        self.positions_mapper.SetInput(self.positions.GetOutput())
        self.positions_mapper.ScalarVisibilityOff()

        self.geometry_actor.SetMapper(self.geometry_mapper)
        self.geometry_actor.GetProperty().SetOpacity(0.2)

        self.positions_actor.SetMapper(self.positions_mapper)
        self.positions_actor.GetProperty().SetColor(light_grey)

        self.ren = vtk.vtkRenderer()
        self.ren_win = GtkGLExtVTKRenderWindow()
        self.ren_win.GetRenderWindow().AddRenderer(self.ren)

        self.ren.AddActor(self.geometry_actor)
        self.ren.AddActor(self.positions_actor)
        self.ren.SetBackground(0.1, 0.2, 0.4)
Exemplo n.º 5
0
    def __init__(self, reader):
        self.reader = reader
        sg = self.src_glyph = vtk.vtkSphereSource()
        sg.SetRadius(0.5)
        sg.SetCenter(0.5, 0.0, 0.0)
        g = self.glyph = vtk.vtkTensorGlyph()        
        g.SetInputConnection(self.reader.GetOutputPort())
        g.SetSource(self.src_glyph.GetOutput())
        g.SetScaleFactor(0.25)
        
        # The normals are needed to generate the right colors and if
        # not used some of the glyphs are black.        
        self.normals = vtk.vtkPolyDataNormals()
        self.normals.SetInputConnection(g.GetOutputPort())
        self.map = vtk.vtkPolyDataMapper()
        self.map.SetInputConnection(self.normals.GetOutputPort())        
        self.act = vtk.vtkActor()
        self.act.SetMapper(self.map)

        # An outline.
        self.of = vtk.vtkOutlineFilter()
        self.of.SetInputConnection(self.reader.GetOutputPort())
        self.out_map = vtk.vtkPolyDataMapper()
        self.out_map.SetInputConnection(self.of.GetOutputPort())
        self.out_act = vtk.vtkActor()
        self.out_act.SetMapper(self.out_map)        
Exemplo n.º 6
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()
def render_image(pointset):
    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetTolerance(0.001)
    delaunay.SetAlpha(18)
    delaunay.SetInput(pointset);
    delaunay.Update();
 
    meshMapper = vtk.vtkPolyDataMapper()
    meshMapper.SetInput(delaunay.GetOutput())
    meshMapper.SetScalarRange(0,255)
 
    meshActor = vtk.vtkActor()
    meshActor.SetMapper(meshMapper)
 
    boundaryMapper = vtk.vtkPolyDataMapper()
    boundaryMapper.SetInput(delaunay.GetOutput())
 
    boundaryActor = vtk.vtkActor()
    boundaryActor.SetMapper(boundaryMapper);
    boundaryActor.GetProperty().SetColor(0,0.55,0);
 
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(meshActor)
    renderer.AddActor(boundaryActor)
    renderer.SetBackground(.5, .5, .5)

    renderWindow.SetSize(600, 600) 
    renderWindow.Render()
    renderWindowInteractor.Start()
Exemplo n.º 8
0
 def plotContinents(self,x1,x2,y1,y2,projection,wrap,tmpl):
     contData = vcs2vtk.prepContinents(self.canvas._continents)
     contMapper = vtk.vtkPolyDataMapper()
     contMapper.SetInputData(contData)
     contActor = vtk.vtkActor()
     contActor.SetMapper(contMapper)
     contActor.GetProperty().SetColor(0.,0.,0.)
     contActor = vcs2vtk.doWrap(contActor,[x1,x2,y1,y2],wrap)
     if projection.type!="linear":
         contData=contActor.GetMapper().GetInput()
         cpts = contData.GetPoints()
         geo, gcpts = vcs2vtk.project(cpts,projection,[x1,x2,y1,y2])
         contData.SetPoints(gcpts)
         contMapper = vtk.vtkPolyDataMapper()
         contMapper.SetInputData(contData)
         contActor = vtk.vtkActor()
         contActor.SetMapper(contMapper)
         contActor.GetProperty().SetColor(0.,0.,0.)
     else:
         geo=None
     ren = vtk.vtkRenderer()
     self.renWin.AddRenderer(ren)
     self.setLayer(ren,tmpl.data.priority)
     vcs2vtk.fitToViewport(contActor,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo)
     if tmpl.data.priority!=0:
       ren.AddActor(contActor)
Exemplo n.º 9
0
    def __init__(self):
        # Central dot
        self.dot = vtk.vtkSphereSource()
        self.dot.SetThetaResolution(20)
        self.dot.SetRadius(.5)
        self.dotMapper = vtk.vtkPolyDataMapper()
        self.dotMapper.SetInputConnection(self.dot.GetOutputPort())
        self.dotActor = vtk.vtkActor()
        self.dotActor.SetMapper(self.dotMapper)
        
        # Circular halo around dot
        self.halo = vtk.vtkSphereSource()
        self.halo.SetThetaResolution(20)
        self.halo.SetRadius(2)
        self.haloMapper = vtk.vtkPolyDataMapper()
        self.haloMapper.SetInputConnection(self.halo.GetOutputPort())
        self.haloActor = vtk.vtkActor()
        self.haloActor.SetMapper(self.haloMapper)
        
        self.dotActor.GetProperty().SetColor(red)
        self.haloActor.GetProperty().SetColor(white)
        self.haloActor.GetProperty().SetOpacity(0.1)
        self.haloActor.GetProperty().SetSpecular(0.6)

        self.actor = vtk.vtkAssembly()
        self.actor.AddPart(self.dotActor)
        self.actor.AddPart(self.haloActor)
Exemplo n.º 10
0
 def initPicker(self):
     coneSource = vtk.vtkConeSource()
     coneSource.CappingOn()
     coneSource.SetHeight(2)
     coneSource.SetRadius(1)
     coneSource.SetResolution(10)
     coneSource.SetCenter(1,0,0)
     coneSource.SetDirection(-1,0,0)
     
     coneMapper = vtk.vtkDataSetMapper()
     coneMapper.SetInputConnection(coneSource.GetOutputPort())
     
     self.redCone = vtk.vtkActor()
     self.redCone.PickableOff()
     self.redCone.SetMapper(coneMapper)
     self.redCone.GetProperty().SetColor(1,0,0)
     
     self.greenCone = vtk.vtkActor()
     self.greenCone.PickableOff()
     self.greenCone.SetMapper(coneMapper)
     self.greenCone.GetProperty().SetColor(0,1,0)
     
     # Add the two cones (or just one, if you want)
     self.renderer.AddViewProp(self.redCone)
     self.renderer.AddViewProp(self.greenCone)
     
     self.picker = vtk.vtkVolumePicker()
     self.picker.SetTolerance(1e-6)
     self.picker.SetVolumeOpacityIsovalue(0.1)
Exemplo n.º 11
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError('vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInput(self.PickedSeeds)
        glyphs.SetSource(glyphSource.GetOutput())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInput(glyphs.GetOutput())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInput(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1.0)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.OutputText('Please position the mouse and press space to add source points, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        self.OutputText('Please position the mouse and press space to add target points, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._TargetSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Exemplo n.º 12
0
def visQuadFunc():
    """ vtk sample scene with iso contours """

    # VTK supports implicit functions of the form f(x,y,z)=constant. These
    # functions can represent things spheres, cones, etc. Here we use a
    # general form for a quadric to create an elliptical data field.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    # vtkSampleFunction samples an implicit function over the x-y-z range
    # specified (here it defaults to -1,1 in the x,y,z directions).
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(30, 30, 30)
    sample.SetImplicitFunction(quadric)

    # Create five surfaces F(x,y,z) = constant between range specified. The
    # GenerateValues() method creates n isocontour values between the range
    # specified.
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(8, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contours.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)

    contActor = vtk.vtkActor()
    contActor.SetMapper(contMapper)

    # We'll put a simple outline around the data.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 0.5, 0)

    # extract data from the volume
    extract = vtk.vtkExtractVOI()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetVOI(0, 29, 0, 29, 15, 15)
    extract.SetSampleRate(1, 2, 3)

    contours2 = vtk.vtkContourFilter()
    contours2.SetInputConnection(extract.GetOutputPort())
    contours2.GenerateValues(8, 0.0, 1.2)

    contMapper2 = vtk.vtkPolyDataMapper()
    contMapper2.SetInputConnection(contours2.GetOutputPort())
    contMapper2.SetScalarRange(0.0, 1.2)

    contActor2 = vtk.vtkActor()
    contActor2.SetMapper(contMapper2)

    return contActor, contActor2, outlineActor, contours, contours2
Exemplo n.º 13
0
def BuildBackdrop (minX, maxX, minY, maxY, minZ, maxZ, thickness):
    global basePlane
    global baseMapper
    global base
    global backPlane
    global backMapper
    global back
    global left
    global leftPlane
    global leftMapper
    
    if not basePlane:
        basePlane = vtk.vtkCubeSource()
    basePlane.SetCenter( (maxX + minX)/2.0, minY, (maxZ + minZ)/2.0)
    basePlane.SetXLength(maxX-minX)
    basePlane.SetYLength(thickness)
    basePlane.SetZLength(maxZ - minZ)

    if not baseMapper:
        baseMapper = vtk.vtkPolyDataMapper()
    baseMapper.SetInput(basePlane.GetOutput())

    if not base:
        base = vtk.vtkActor()
    base.SetMapper(baseMapper)

    if not backPlane:
        backPlane = vtk.vtkCubeSource()
    backPlane.SetCenter( (maxX + minX)/2.0, (maxY + minY)/2.0, minZ)
    backPlane.SetXLength(maxX-minX)
    backPlane.SetYLength(maxY - minY)
    backPlane.SetZLength(thickness)

    if not backMapper:
        backMapper = vtk.vtkPolyDataMapper()
    backMapper.SetInput(backPlane.GetOutput())

    if not back:
        back = vtk.vtkActor()
    back.SetMapper(backMapper)

    if not leftPlane:
        leftPlane = vtk.vtkCubeSource()
    leftPlane.SetCenter( minX, (maxY+minY)/2.0, (maxZ+minZ)/2.0)
    leftPlane.SetXLength(thickness)
    leftPlane.SetYLength(maxY-minY)
    leftPlane.SetZLength(maxZ-minZ)

    if not leftMapper:
        leftMapper = vtk.vtkPolyDataMapper()
    leftMapper.SetInput(leftPlane.GetOutput())

    if not left:
        left = vtk.vtkActor()
    left.SetMapper(leftMapper)

    return [base, back, left] 
Exemplo n.º 14
0
Arquivo: sym.py Projeto: ggoret/VEDA
	def build_constelation(self,mol):
		if mol.acteur == None :
			MB.showwarning('Info','Select a molecule in the list')
			return
		if mol.symobs !=None:
			mol.acteur.RemoveObserver(mol.symobs)
		if mol.lsm!=[]:
			for sm in mol.lsm:
				self.gfx.renderer.RemoveActor(sm)
			mol.lsm=[]
		(xmin, xmax, ymin, ymax, zmin, zmax)= self.bounds
		sym=open(self.symlistfile,'r')
		for l in sym:
			ms = l.split()
			nbl = int(ms[6][1:])
			if nbl not in mol.lnbsm:
				continue
			ang = [float(ms[0]),float(ms[1]),float(ms[2])]
			tra = array([float(ms[3]),float(ms[4]),float(ms[5])])
			sm=symmate() #on cree un symmate vide
			sm.SetPosition(mol.acteur.GetPosition()) #on assigne la partie translationelle des pv
			sm.SetOrientation(mol.acteur.GetOrientation()) #on assigne la partie rotationelle des pv
			self.RotaEuler(sm.ut,ang[0],ang[1],ang[2]) #on defini la partie rotationelle de la transformation
			sm.ut.Translate(tra[0],tra[1],tra[2]) #on defini la partie translationelle de la transformation
			sm.SetUserTransform(sm.ut) #on assigne la transformation a notre symmate
			pip = [sm.GetMatrix().GetElement(0,3),sm.GetMatrix().GetElement(1,3),sm.GetMatrix().GetElement(2,3)]#on recupere la partie translationelle de la combinaison de pv et de la transformation (ut)
			if (xmin + self.mdbe < pip[0]) and (pip[0] < xmax - self.mdbe) and (ymin + self.mdbe < pip[1]) and (pip[1] < ymax - self.mdbe) and (zmin + self.mdbe < pip[2]) and (pip[2] < zmax - self.mdbe):# on test si pip est dans la boite
				sm.nbsym=nbl
				if mol.acteur.GetClassName()=='vtkAssembly':# dans le cas ou la molecule independante est un assembly
					for i in range(mol.acteur.GetNumberOfPaths()):
						tmp=vtk.vtkActor()
						tmp.SetMapper(mol.acteur.GetParts().GetItemAsObject(i).GetMapper())
						p=vtk.vtkProperty()
						#p.SetColor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor())
						p.SetColor(Map.invcolor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor()))
						tmp.SetProperty(p)
						if mol.mod.type=='mol':
							tmp.GetProperty().SetLineWidth(4)
						tmp.DragableOff()
						tmp.PickableOff()
						sm.AddPart(tmp)
				else:#cas simple ou la mol ind est composer d un seul objet
					tmp=vtk.vtkActor()
					tmp.SetMapper(mol.acteur.GetMapper())
					p=vtk.vtkProperty()
					#p.SetColor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor())
					p.SetColor(Map.invcolor(mol.acteur.GetProperty().GetColor()))
					tmp.SetProperty(p)
					if mol.mod.type=='mol':
							tmp.GetProperty().SetLineWidth(4)
					tmp.DragableOff()
					tmp.PickableOff()
					sm.AddPart(tmp)
				mol.lsm+=[sm]# on ajoute le symmate a la liste des symmate
		sym.close()
		self.move_sym(mol)
Exemplo n.º 15
0
    def Execute(self):

        self._SourceSeedIds.Initialize()

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Add points.',self.PickCallback)
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        # create a text actor
        txt = vtk.vtkTextActor()
        info = "Position mouse and press space. "
        info += "Select seeds in this order: RSpv, RIpv, LIpv, LSpv. "
        info += "Fifth seed requires --use_laa_seed command."
        txt.SetInput(info)
        txtprop=txt.GetTextProperty()
        txtprop.SetFontFamilyToArial()
        txtprop.SetFontSize(13)
        txtprop.SetColor(1, 1, 1)
        txt.SetDisplayPosition(0, 10)
        self.vmtkRenderer.Renderer.AddActor(txt)

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Exemplo n.º 16
0
 def SetInputActor(self):
     self.inputActor1 = vtk.vtkActor()
     self.inputActor1.SetMapper(self.inputMapper1)
     self.inputActor1.GetProperty().SetInterpolationToFlat()
     self.inputActor2 = vtk.vtkActor()
     self.inputActor2.SetMapper(self.inputMapper2)
     self.inputActor3 = vtk.vtkActor()
     self.inputActor3.SetMapper(self.inputMapper3)
     self.inputActor4 = vtk.vtkActor()
     self.inputActor4.SetMapper(self.inputMapper4)
Exemplo n.º 17
0
def PlotEdges(mesh, angle):
    featureEdges = vtk.vtkFeatureEdges()
    if vtk.vtkVersion().GetVTKMajorVersion() >5:
        featureEdges.SetInputData(mesh)
    else:
        featureEdges.SetInput(mesh)
    featureEdges.FeatureEdgesOn()
    featureEdges.BoundaryEdgesOff()
    featureEdges.NonManifoldEdgesOff()
    featureEdges.ManifoldEdgesOff()
    featureEdges.SetFeatureAngle(angle)
    
    
    edgeMapper = vtk.vtkPolyDataMapper();
    edgeMapper.SetInputConnection(featureEdges.GetOutputPort());
    
    edgeActor = vtk.vtkActor();
    edgeActor.GetProperty().SetLineWidth(5);
    edgeActor.SetMapper(edgeMapper)
    
    
    mapper = vtk.vtkDataSetMapper()
    if vtk.vtkVersion().GetVTKMajorVersion() >5:
        mapper.SetInputData(mesh)
    else:
        mapper.SetInput(mesh)

    
    # Actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().LightingOff()    
        
    ###############################
    # Display
    ###############################
    
    # Render
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    # Allow user to interact
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    
    ren.AddActor(actor)
    ren.AddActor(edgeActor)
    
        
    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 18
0
def visualise_color(surface,ref,case):
    """Visualise surface in solid color and 'ref' in trasparent."""
    # create a text actor
    txt = vtk.vtkTextActor()
    txt.SetInput(case)
    txtprop=txt.GetTextProperty()
    txtprop.SetFontFamilyToArial()
    txtprop.SetFontSize(18)
    txtprop.SetColor(0, 0, 0)
    txt.SetDisplayPosition(20, 30)

    # create a rendering window, renderer, and renderwindowinteractor
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)
    iren.SetRenderWindow(renWin)

    # surface mapper and actor
    surfacemapper = vtk.vtkPolyDataMapper()
    surfacemapper.SetInputData(surface)
    surfacemapper.SetScalarModeToUsePointFieldData()
    surfaceactor = vtk.vtkActor()
    surfaceactor.GetProperty().SetColor(288/255, 26/255, 28/255)
    surfaceactor.SetMapper(surfacemapper)

    # refsurface mapper and actor
    refmapper = vtk.vtkPolyDataMapper()
    refmapper.SetInputData(ref)
    refmapper.SetScalarModeToUsePointFieldData()

    refactor = vtk.vtkActor()
    refactor.GetProperty().SetOpacity(0.5)
    refactor.GetProperty().SetColor(1, 1, 1)
    refactor.SetMapper(refmapper)


    # assign actors to the renderer
    ren.AddActor(surfaceactor)
    ren.AddActor(refactor)
    ren.AddActor(txt)

    # set the background and size; zoom in; and render
    ren.SetBackground(1, 1, 1)
    renWin.SetSize(800 , 800)
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(1)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 19
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        #Create a cube
        cube=vtk.vtkCubeSource()
        cube.SetXLength(40)
        cube.SetYLength(30)
        cube.SetZLength(20)
        cubeMapper=vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())
         
        #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
        plane=vtk.vtkPlane()
        plane.SetOrigin(10,0,0)
        plane.SetNormal(1,0,0)
         
        #create cutter
        cutter=vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(cube.GetOutputPort())
        cutter.Update()
        cutterMapper=vtk.vtkPolyDataMapper()
        cutterMapper.SetInputConnection( cutter.GetOutputPort())
         
        #create plane actor
        planeActor=vtk.vtkActor()
        planeActor.GetProperty().SetColor(1.0,1,0)
        planeActor.GetProperty().SetLineWidth(2)
        planeActor.SetMapper(cutterMapper)
         
        #create cube actor
        cubeActor=vtk.vtkActor()
        cubeActor.GetProperty().SetColor(0.5,1,0.5)
        cubeActor.GetProperty().SetOpacity(0.5)
        cubeActor.SetMapper(cubeMapper)
         
        #create renderers and add actors of plane and cube
        self.ren.AddActor(planeActor)
        self.ren.AddActor(cubeActor) 

        self.ren.ResetCamera()
        self._initialized = False
Exemplo n.º 20
0
 def __init__(self):
     self.source = None
     self.target = None
     self.transformed = None
     self.iteration =200
     self.icp= vtk.vtkIterativeClosestPointTransform()
     self.icptf = vtk.vtkTransformPolyDataFilter()
     self.mappers =vtk.vtkPolyDataMapper()
     self.mappert =vtk.vtkPolyDataMapper()
     self.mappertf =vtk.vtkPolyDataMapper()
     self.actors = vtk.vtkActor()
     self.actort = vtk.vtkActor()
     self.actortf = vtk.vtkActor()
     self.centroidon= False
Exemplo n.º 21
0
def initializeView():
    mapOutline = vtk.vtkPolyDataMapper()
    mapOutline.SetInputConnection(outlineData.GetOutputPort())
    outline = vtk.vtkActor()
    outline.SetMapper(mapOutline)
    outline.GetProperty().SetColor(0, 0, 0)

    skinMapper = vtk.vtkPolyDataMapper()
    skinMapper.SetInputConnection(skinNormals.GetOutputPort())
    skinMapper.ScalarVisibilityOff()
    skin = vtk.vtkActor()
    skin.SetMapper(skinMapper)
    attachProp(outline, vtkNode)
    attachProp(skin, vtkNode)
Exemplo n.º 22
0
def vtkpoints(points, color=None, radius=None):
    # Create a polydata with the points we just created.
    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    # Perform a 2D Delaunay triangulation on them.
    delny = vtk.vtkDelaunay2D()
    delny.SetInput(profile)
    delny.SetTolerance(0.001)
    mapMesh = vtk.vtkPolyDataMapper()
    mapMesh.SetInputConnection(delny.GetOutputPort())
    meshActor = vtk.vtkActor()
    meshActor.SetMapper(mapMesh)
    meshActor.GetProperty().SetColor(0.1, 0.2, 0.1)

    # We will now create a nice looking mesh by wrapping the edges in tubes,
    # and putting fat spheres at the points.
    extract = vtk.vtkExtractEdges()
    extract.SetInputConnection(delny.GetOutputPort())

    ball = vtk.vtkSphereSource()

    if radius == None:
        rad = 0.002
    else:
        rad = radius
    print rad
    ball.SetRadius(rad)
    ball.SetThetaResolution(50)
    ball.SetPhiResolution(5)
    balls = vtk.vtkGlyph3D()
    balls.SetInputConnection(delny.GetOutputPort())
    balls.SetSourceConnection(ball.GetOutputPort())
    mapBalls = vtk.vtkPolyDataMapper()
    mapBalls.SetInputConnection(balls.GetOutputPort())
    ballActor = vtk.vtkActor()
    ballActor.SetMapper(mapBalls)
    if color == None:
        ballcolor = red
    else:
        ballcolor = color
    print "setting ball color to...", ballcolor
    ballActor.GetProperty().SetColor(ballcolor)
    ballActor.GetProperty().SetSpecularColor(0, 0, 0)
    ballActor.GetProperty().SetSpecular(0.3)
    ballActor.GetProperty().SetSpecularPower(500)
    ballActor.GetProperty().SetAmbient(0.2)
    ballActor.GetProperty().SetDiffuse(0.8)
    return ballActor, profile
Exemplo n.º 23
0
    def testContourQuadraticTetra(self):
	# Create a reader to load the data (quadratic tetrahedra)
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/quadTetEdgeTest.vtk")

        tetContours = vtk.vtkContourFilter()
        tetContours.SetInputConnection(reader.GetOutputPort())
        tetContours.SetValue(0, 0.5)
        aTetContourMapper = vtk.vtkDataSetMapper()
        aTetContourMapper.SetInputConnection(tetContours.GetOutputPort())
        aTetContourMapper.ScalarVisibilityOff()
        aTetMapper = vtk.vtkDataSetMapper()
        aTetMapper.SetInputConnection(reader.GetOutputPort())
        aTetMapper.ScalarVisibilityOff()
        aTetActor = vtk.vtkActor()
        aTetActor.SetMapper(aTetMapper)
        aTetActor.GetProperty().SetRepresentationToWireframe()
        aTetActor.GetProperty().SetAmbient(1.0)
        aTetContourActor = vtk.vtkActor()
        aTetContourActor.SetMapper(aTetContourMapper)
        aTetContourActor.GetProperty().SetAmbient(1.0)

        # Create the rendering related stuff.
        # Since some of our actors are a single vertex, we need to remove all
        # cullers so the single vertex actors will render
        ren1 = vtk.vtkRenderer()
        ren1.GetCullers().RemoveAllItems()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren1)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        ren1.SetBackground(.1, .2, .3)

        renWin.SetSize(400, 250)

        # specify properties
        ren1.AddActor(aTetActor)
        ren1.AddActor(aTetContourActor)

        ren1.ResetCamera()
        ren1.GetActiveCamera().Dolly(1.5)
        ren1.ResetCameraClippingRange()

        renWin.Render()

        img_file = "contourQuadraticTetra.png"
        vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 24
0
def trace(obj):
  
  s = vtk.vtkProgrammableSource()
  def execute():
    global offset
    positions = [trajectory(obj,i) for i in range(offset)]
                  
    #construct a VTK polydata object: a single poly-line 'cell'
    dataset = s.GetPolyDataOutput()
    points = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(len(positions))
    for p in positions:
      id = points.InsertNextPoint(*p)
      cells.InsertCellPoint(id)
    dataset.SetPoints(points)
    dataset.SetLines(cells)
    return dataset
  s.SetExecuteMethod(execute)

  m=vtk.vtkPolyDataMapper()
  m.SetInput(s.GetOutput())
  a=vtk.vtkActor()
  a.SetMapper(m)
  def update():
    s.Modified()
  return (update,a)
Exemplo n.º 25
0
def QVTKRenderWidgetConeExample():
    """A simple example that uses the QVTKRenderWindowInteractor
    class.  """

    # every QT app needs an app
    app = qt.QApplication(['QVTKRenderWindowInteractor'])

    # create the widget
    widget = QVTKRenderWindowInteractor()
    widget.Initialize()
    widget.Start()
    # if you dont want the 'q' key to exit comment this.
    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # close the application when window is closed
    app.setMainWidget(widget)
    # start event processing
    app.exec_loop()
Exemplo n.º 26
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)
Exemplo n.º 27
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.CubeSource = vtk.vtkCubeSource()
        self.CubeActor = vtk.vtkActor()
        
        self.BoxActive = 0
        self.BoxBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        self.CroppedImage = vtk.vtkImageData()

        self.vmtkRenderer = None
        self.OwnRenderer = 0

        self.PlaneWidgetX = None
        self.PlaneWidgetY = None
        self.PlaneWidgetZ = None
        self.BoxWidget = None

        self.Image = None

        self.Interactive = 1

        self.SetScriptName('vmtkimagevoiselector')
        self.SetScriptDoc('select a cubical volume of interest and get rid of the rest of the image')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Interactive','interactive','bool',1,'','toggle interactivity'],
            ['BoxBounds','boxbounds','float',6,'','bounds of the cubical region of interest'],
            ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer']
            ])
        self.SetOutputMembers([
            ['Image','o','vtkImageData',1,'','the output image','vmtkimagewriter']
            ])
    def __init__( self, pcIndex=0, nPartitions=1 ):
        self.nPartitions = nPartitions
        self.polydata = None
        self.vardata = None
        self.vrange = None
        self.np_index_seq = None
        self.np_cell_data = None
        self.points = None
        self.pcIndex = pcIndex
        self.earth_radius = 100.0
        self.spherical_scaling = 0.4
        self.vtk_planar_points = None
        self.vtk_spherical_points = None
        self.np_points_data = None
        self.topo = PlotType.Planar
        self.grid = None
#        self.threshold_target = "vardata"
        self.current_scalar_range = None
        self.nlevels  = None
        self.current_subset_specs = None
        self.updated_subset_specs = None
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetScalarModeToUsePointData()
        self.mapper.SetColorModeToMapScalars()
        self.actor = vtk.vtkActor()
        self.actor.SetMapper( self.mapper )
Exemplo n.º 29
0
def make_sphereActor (x, r, rgb, opacity):
    points = vtk.vtkPoints()
    points.InsertNextPoint(x[0], x[1], x[2])

    diameter = vtk.vtkDoubleArray()
    diameter.SetNumberOfComponents(1)
    diameter.InsertNextTuple1(2.0*r)

    pData = vtk.vtkPolyData()
    pData.SetPoints(points)
    pData.GetPointData().SetScalars(diameter)

    pSource = vtk.vtkSphereSource()
    pSource.SetPhiResolution(16)
    pSource.SetThetaResolution(16)

    pGlyph = vtk.vtkGlyph3D()
    pGlyph.SetSource(pSource.GetOutput())
    pGlyph.SetInput(pData)
    pGlyph.ScalingOn()
    pGlyph.SetScaleModeToScaleByScalar()

    pMapper = vtk.vtkPolyDataMapper()
    pMapper.ScalarVisibilityOff()
    pMapper.SetInput(pGlyph.GetOutput())

    pActor = vtk.vtkActor()
    pActor.SetMapper(pMapper)
    pActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2])
    pActor.GetProperty().SetOpacity(opacity)

    return pActor
Exemplo n.º 30
0
def main():
    '''One render window, multiple viewports'''
    iren_list = []
    rw = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(rw)
    # Define viewport ranges
    xmins=[0,.5,0,.5]
    xmaxs=[0.5,1,0.5,1]
    ymins=[0,0,.5,.5]
    ymaxs=[0.5,0.5,1,1]
    for i in range(4):
        ren = vtk.vtkRenderer()
        rw.AddRenderer(ren)
        ren.SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i])
        
        #Create a sphere
        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetCenter(0.0, 0.0, 0.0)
        sphereSource.SetRadius(5)
        
        #Create a mapper and actor
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphereSource.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        ren.AddActor(actor)
        ren.ResetCamera()
    
    rw.Render()
    rw.SetWindowName('RW: Multiple ViewPorts')
    iren.Start()
Exemplo n.º 31
0
def drawOffsets2(myscreen, ofs):
    # draw loops
    nloop = 0
    lineColor = ovdvtk.lgreen
    arcColor = ovdvtk.green  #grass
    ofs_points = []
    for lop in ofs:
        points = []
        n = 0
        N = len(lop)
        first_point = []
        previous = []
        for p in lop:
            # p[0] is the Point
            # p[1] is -1 for lines, and r for arcs
            if n == 0:  # don't draw anything on the first iteration
                previous = p[0]
                #first_point = p[0]
            else:
                cw = p[3]
                cen = p[2]
                r = p[1]
                p = p[0]
                if r == -1:  # r=-1 means line-segment
                    points.extend(
                        [previous,
                         p])  #drawLine(myscreen, previous, p, lineColor)
                else:  # otherwise we have an arc
                    points.extend(arc_pts(previous, p, r, cen, cw))

                previous = p
            n = n + 1
        ofs_points.append(points)
        #print "rendered loop ",nloop, " with ", len(lop), " points"
        nloop = nloop + 1

    # now draw each loop with polydata
    oPoints = vtk.vtkPoints()
    lineCells = vtk.vtkCellArray()
    #self.colorLUT = vtk.vtkLookupTable()
    print len(ofs_points), " loops to render:"
    idx = 0
    last_idx = 0

    for of in ofs_points:
        epts = of
        segs = []
        first = 1
        print " loop with ", len(epts), " points"
        for p in epts:
            oPoints.InsertNextPoint(p.x, p.y, 0)
            if first == 0:
                seg = [last_idx, idx]
                segs.append(seg)
            first = 0
            last_idx = idx
            idx = idx + 1

        # create line and cells
        for seg in segs:
            line = vtk.vtkLine()
            line.GetPointIds().SetId(0, seg[0])
            line.GetPointIds().SetId(1, seg[1])
            #print " indexes: ", seg[0]," to ",seg[1]
            lineCells.InsertNextCell(line)

    linePolyData = vtk.vtkPolyData()
    linePolyData.SetPoints(oPoints)
    linePolyData.SetLines(lineCells)
    linePolyData.Modified()
    linePolyData.Update()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(linePolyData)
    edge_actor = vtk.vtkActor()
    edge_actor.SetMapper(mapper)
    edge_actor.GetProperty().SetColor(ovdvtk.lgreen)
    myscreen.addActor(edge_actor)
def main():
    # setup the dataset filepath
    all_filename = np.genfromtxt('stats/filenames.csv', dtype=None)
    time_index = [];
    for i in range(60, 120):
        if(i%5==0):
            time_index.append(i);
    print(time_index);
    overview_filename = all_filename[time_index];
    certain_filename = all_filename[69:88];            
    
    # iso_value_1 = average mean + 3*std
    # we calculate it in other file "finalproject_T2"
    iso_value_1 = 0.3547;
    for i in range(0, len(overview_filename)):
    #for i in range(0, 1):
        filename = "yC31/"+overview_filename[i];
        print(filename);
        #filename = "yC31/pv_insitu_300x300x300_29072.vti"
        # the name of data array which is used in this example
        daryName = "tev";
        #'v03' 'prs' 'tev'
        # for accessomg build-in color access
        colors = vtk.vtkNamedColors();

        # 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 data within the render windows.


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

        # Set a background color for the renderer
        # and set the size of the render window.
        aRenderer.SetBackground(colors.GetColor3d("Silver"));
        renWin.SetSize(600, 600);
        # data reader
        reader = vtk.vtkXMLImageDataReader();
        reader.SetFileName(filename);
        reader.Update();

        # specify the data array in the file to process
        reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0);


        # convert the data array to numpy array and get the min and maximum value
        dary = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars(daryName));
        dary = dary[dary!= 0]
        dMax = np.amax(dary);
        dMin = np.amin(dary);
        dRange = dMax - dMin;
        dMean = np.mean(dary);
        dMedian = np.median(dary);
        dstd = np.std(dary);
        '''
        print("Data array max: ", dMax);
        print("Data array min: ", dMin);
        print("Data array range: ", dRange);
        print("Data array mean: ", dMean);
        print("Data array median: ", dMedian);
        print("Data array std: ", dstd);
        '''
        ############ setup color map #########
        # Now create a loopup table that consists of the full hue circle
        # (from HSV).
        hueLut = vtk.vtkLookupTable();
        hueLut.SetTableRange(dMin, dMax);
        hueLut.Build();

        # An outline provides context around the data.
        outlineData = vtk.vtkOutlineFilter();
        outlineData.SetInputConnection(reader.GetOutputPort());
        outlineData.Update()

        mapOutline = vtk.vtkPolyDataMapper();
        mapOutline.SetInputConnection(outlineData.GetOutputPort());

        outline = vtk.vtkActor();
        outline.SetMapper(mapOutline);
        outline.GetProperty().SetColor(colors.GetColor3d("Black"));



    
        #################### create isosurface tev = mean + 3*std ######################################
        # isosurface 
        iso = vtk.vtkContourFilter();
        iso.SetInputConnection(reader.GetOutputPort());
        iso.Update();
        iso.SetValue(0, iso_value_1);

        normals = vtk.vtkPolyDataNormals();
        normals.SetInputConnection(iso.GetOutputPort());
        normals.SetFeatureAngle(45);

        isoMapper = vtk.vtkPolyDataMapper();
        isoMapper.SetInputConnection(normals.GetOutputPort());
        isoMapper.ScalarVisibilityOff();

        isoActor = vtk.vtkActor();
        isoActor.SetMapper(isoMapper);
        isoActor.GetProperty().SetColor(colors.GetColor3d("bisque"));
        isoActor.GetProperty().SetOpacity(0.3);
        #################################################################################################
        aCamera = vtk.vtkCamera();
        aCamera.SetViewUp(0, 0, 1);
        aCamera.SetPosition(1, 1, 2);
        aCamera.SetFocalPoint(0, 0, 0);
        aCamera.ComputeViewPlaneNormal();
        aCamera.Azimuth(45.0);
        aCamera.Elevation(45.0);
    
        ######################## create a text #####################
        # create a text actor
    
        txt = vtk.vtkTextActor()
        txt_str = "isosurface value (mean+3*std)(bisque) = "+ str(iso_value_1)[:5]
        txt.SetInput(txt_str)
        txtprop=txt.GetTextProperty()
        txtprop.SetFontFamilyToArial()
        txtprop.SetFontSize(24)
        txtprop.SetColor(colors.GetColor3d("bisque"))
        txt.SetDisplayPosition(50,550)
        ##########################################################
    
        txt3 = vtk.vtkTextActor()
        txt_str3 = "timestep = "+filename[27:32]
        txt3.SetInput(txt_str3)
        txtprop3=txt3.GetTextProperty()
        txtprop3.SetFontFamilyToArial()
        txtprop3.SetFontSize(24)
        txtprop3.SetColor(0,0,0)
        txt3.SetDisplayPosition(50,500)
    
    

        # Actors are added to the renderer.
        aRenderer.AddActor(outline);
        aRenderer.AddActor(isoActor);
        aRenderer.AddActor(txt);
        aRenderer.AddActor(txt3);
        # An initial camera view is created. The Dolly() method moves
        # the camera towards the FocalPoint, thereby enlarging the image.
        aRenderer.SetActiveCamera(aCamera);

        # Calling Render() directly on a vtkRenderer is strictly forbidden.
        # Only calling Render() on the vtkRenderWindow is a valid call.
        renWin.Render();
        aRenderer.ResetCamera();
        aCamera.Dolly(-2.0);
    
        ####################################################################
        # screenshot code:
        w2if = vtk.vtkWindowToImageFilter()
        w2if.SetInput(renWin)
        w2if.Update()

        writer = vtk.vtkPNGWriter()
        saveName = "plots/ios/tev/mean/"+daryName+"_t_"+filename[27:32]+".png";
        writer.SetFileName(saveName)
        writer.SetInputData(w2if.GetOutput())
        writer.Write()
    
        #####################################################################

        # Note that when camera movement occurs (as it does in the Dolly() method),
        # the clipping planes often need adjusting.
        # Clipping planes consist of two planes:
        # near and far along the view direction.
        # The near plane clips out objects in front of the plane;
        # the far plane clips out objects behind the plane.
        # This way only what is drawn between the planes is actually rendered.

        aRenderer.ResetCameraClippingRange();

        # Interact with the data.
        renWin.Render();
Exemplo n.º 33
0
normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(fohe.GetOutputPort())

foheMapper = vtk.vtkPolyDataMapper()
foheMapper.SetInputConnection(normals.GetOutputPort())

foheActor = vtk.vtkLODActor()
foheActor.SetMapper(foheMapper)

outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(normals.GetOutputPort())

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

outlineActor = vtk.vtkActor()
outlineActor.SetMapper(mapOutline)
outlineActor.GetProperty().SetColor(0, 0, 0)

# Create the RenderWindow, Renderer, and setup viewports
camera = vtk.vtkCamera()
camera.SetClippingRange(1.60187, 20.0842)
camera.SetFocalPoint(0.21406, 1.5, 0)
camera.SetPosition(11.63, 6.32, 5.77)
camera.SetViewUp(0.180325, 0.549245, -0.815974)

light = vtk.vtkLight()
light.SetFocalPoint(0.21406, 1.5, 0)
light.SetPosition(8.3761, 4.94858, 4.12505)

ren1 = vtk.vtkRenderer()
Exemplo n.º 34
0
sample = vtk.vtkSampleFunction()
sample.SetSampleDimensions(30, 30, 30)
sample.SetImplicitFunction(quadric)

# Create five surfaces F(x,y,z) = constant between range specified. The
# GenerateValues() method creates n isocontour values between the range
# specified.
contours = vtk.vtkContourFilter()
contours.SetInputConnection(sample.GetOutputPort())
contours.GenerateValues(5, 0.0, 1.2)

contMapper = vtk.vtkPolyDataMapper()
contMapper.SetInputConnection(contours.GetOutputPort())
contMapper.SetScalarRange(0.0, 1.2)

contActor = vtk.vtkActor()
contActor.SetMapper(contMapper)

# We'll put a simple outline around the data.
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(sample.GetOutputPort())

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

outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.GetProperty().SetColor(0,0,0)

# The usual rendering stuff.
ren = vtk.vtkRenderer()
Exemplo n.º 35
0
                             "/Data/sampleGenGrid3.nc")
# Set the arrays we want to load.
reader_cartesian.UpdateMetaData()
reader_cartesian.SetVariableArrayStatus("sample", 1)
reader_cartesian.SphericalCoordinatesOff()
# Assign the field to scalars.
aa_cartesian = vtk.vtkAssignAttribute()
aa_cartesian.SetInputConnection(reader_cartesian.GetOutputPort())
aa_cartesian.Assign("sample", "SCALARS", "CELL_DATA")
# Extract a surface that we can render.
surface_cartesian = vtk.vtkDataSetSurfaceFilter()
surface_cartesian.SetInputConnection(aa_cartesian.GetOutputPort())
mapper_cartesian = vtk.vtkPolyDataMapper()
mapper_cartesian.SetInputConnection(surface_cartesian.GetOutputPort())
mapper_cartesian.SetScalarRange(100, 2500)
actor_cartesian = vtk.vtkActor()
actor_cartesian.SetMapper(mapper_cartesian)
ren_cartesian = vtk.vtkRenderer()
ren_cartesian.AddActor(actor_cartesian)
ren_cartesian.SetViewport(0.0, 0.0, 0.5, 1.0)
renWin.AddRenderer(ren_cartesian)
#############################################################################
# Case 2: Spherical coordinates on.
# Open the file.
reader_spherical = vtk.vtkNetCDFCFReader()
reader_spherical.SetFileName("" + str(VTK_DATA_ROOT) +
                             "/Data/sampleGenGrid3.nc")
# Set the arrays we want to load.
reader_spherical.UpdateMetaData()
reader_spherical.SetVariableArrayStatus("sample", 1)
reader_spherical.SphericalCoordinatesOn()
Exemplo n.º 36
0
    def testContour3DAll(self):

        # On older Macs, 10 is too low. Due to what looks like a driver bug
        # spectral lighting behaves sort of weird and produces small differences
        threshold = 30

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

        # create pipeline
        #
        slc = vtk.vtkStructuredPointsReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk")

        actorColors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"]

        types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"]

        i = 1
        c = 0

        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        colors = self.Colors()

        for idx, vtkType in enumerate(types):
            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5)

            i += 5

            cast.append(vtk.vtkImageCast())
            eval("cast[idx].SetOutputScalarTypeTo" + vtkType)
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkContourFilter())
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)
            iso[idx].ComputeScalarsOff()
            iso[idx].ComputeGradientsOff()

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            eval('actor[idx].GetProperty().SetDiffuseColor(colors.GetRGBColor("' + actorColors[idx] + '"))')
            actor[idx].GetProperty().SetSpecularPower(30)
            actor[idx].GetProperty().SetDiffuse(.7)
            actor[idx].GetProperty().SetSpecular(.5)

            c += 3

            ren.AddActor(actor[idx])


        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.SetBackground(0.9, .9, .9)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        renWin.SetSize(400, 400)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()


        img_file = "contour3DAll.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 37
0
def main():
    grid = vtk.vtkUnstructuredGrid()
    grid_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_VERSION >= 6:
        grid_mapper.SetInputData(grid)
    else:
        grid_mapper.SetInput(grid)
    #if vtk.VTK_VERSION[0] <= 5:
    #    grid_mapper.SetInputConnection(grid.GetProducerPort())
    #else:
    #    grid_mapper.SetInputData(grid)

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

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

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

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

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

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

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

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

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

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

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

    rend.SetBackground(0.7, 0.8, 1.0)
    renWin.SetSize(800, 800)
    renWin.Render()
    iren.Start()
Exemplo n.º 38
0
    xy = iren.GetEventPosition()
    the_ren = iren.FindPokedRenderer(xy[0], xy[1])
    print(the_ren.GetBackground())
    camera = the_ren.GetActiveCamera()
    # camera.Azimuth(120.)
    # camera.SetPosition(.5, 1.0, 1.0)
    print(camera.GetOrientation())
    print("Clicked")


# pointCloud = VtkPointCloud()
cube = vtk.vtkCubeSource()
cube.SetBounds(-1, 1, -1, 1, -1, 1)
cubeMapper = vtk.vtkPolyDataMapper()
cubeMapper.SetInputConnection(cube.GetOutputPort())
cubeActor = vtk.vtkActor()
cubeActor.SetMapper(cubeMapper)
cubeActor.GetProperty().SetOpacity(.5)

# Renderer
ren = vtk.vtkRenderer()
# pointCloud.vtkActor.SetMapper(cubeMapper)

ren.AddActor(cubeActor)
# ren.AddActor(pointCloud.vtkActor)
ren.SetBackground(.2, .3, .4)
ren.ResetCamera()

# Render Window
rw = vtk.vtkRenderWindow()
rw.AddRenderer(ren)
Exemplo n.º 39
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
sphere = vtk.vtkSphereSource()
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereActor = vtk.vtkActor()
sphereActor.SetMapper(sphereMapper)
coneGlyph = vtk.vtkConeSource()
coneGlyph.SetResolution(6)
sphereGlyph = vtk.vtkSphereSource()
sphereGlyph.SetThetaResolution(12)
sphereGlyph.SetPhiResolution(6)
caption = vtk.vtkCaptionActor2D()
caption.SetCaption("This is the\nsouth pole")
caption.SetAttachmentPoint(0, 0, -0.5)
caption.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
caption.GetPositionCoordinate().SetReferenceCoordinate(None)
caption.GetPositionCoordinate().SetValue(0.05, 0.05)
caption.SetWidth(0.25)
caption.SetHeight(0.15)
caption.ThreeDimensionalLeaderOn()
Exemplo n.º 40
0
	line_i = vtk.vtkLine()
	line_i.GetPointIds().SetId( 0, i ) 
	line_i.GetPointIds().SetId( 1, i + 1 ) 
	
	geoReg_lines.InsertNextCell( line_i )

geoReg_data.SetPoints( geoReg_pts )
geoReg_data.SetLines( geoReg_lines )

geoReg_data.Modified()

geoRegMapper = vtk.vtkPolyDataMapper()
geoRegMapper.SetInputData( geoReg_data )
geoRegMapper.Update()

geoRegActor = vtk.vtkActor()
geoRegActor.SetMapper( geoRegMapper )
geoRegActor.GetProperty().SetLineWidth( 15 )
geoRegActor.GetProperty().SetColor( [ 0, 0, 1 ] )
geoRegActor.GetProperty().SetOpacity( 0.8 )
geoRegActor.GetProperty().SetRenderLinesAsTubes( 1 )


# 2) Hierarchical Multi-Geodesic Regression
#####################################################
# 	Linearized Geodesic Regression for all Data		#
#####################################################
step_size = 0.01
max_iter = 500
step_tol = 1e-8
Exemplo n.º 41
0
def keypress(obj, ev):
    interactor = obj
    renderer = interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()
    actorCollection = renderer.GetActors()
    actorCollection.InitTraversal()
    
    key = obj.GetKeySym()

    if key in 'h':
      print('Press the \'u\' key to output actor transform matrix')
      print('Press the \'p\' key to pick a point')
      print('Press the \'d\' key to delete a point')
      print('Press the \'o\' key to output points')
      print('Press the \'a\' key for actor control mode')
      print('Press the \'c\' key for camera control mode')
      print('Press the \'q\' key to quit')

    if key in 'u':
      for index in range(actorCollection.GetNumberOfItems()):
        nextActor = actorCollection.GetNextActor()
        if (nextActor.GetPickable()==1):
          printMatrix4x4(nextActor.GetMatrix())
          message('File written: transform.txt')
          writeTransform('transform.txt',nextActor.GetMatrix(),False)
          
    if key in 'p':
      x, y = obj.GetEventPosition()

      cellPicker = vtk.vtkCellPicker()
      cellPicker.SetTolerance(0.0001)
      cellPicker.Pick(x, y, 0, renderer)

      points = cellPicker.GetPickedPositions()
      numPoints = points.GetNumberOfPoints()
      if numPoints < 1:
        return()
      i, j, k = points.GetPoint(0)
      

      # Get the size of the actor by measuring its diagonal
      b = actorCollection.GetNextActor().GetBounds()
      sphere_size = diagonal(b[1]-b[0],b[3]-b[2],b[5]-b[4]) * 0.005
      
      sphere = vtk.vtkSphereSource()
      sphere.SetRadius(sphere_size)
      sphere.SetThetaResolution(20)
      sphere.SetPhiResolution(20)
      sphere.SetCenter(i, j, k)
      
      mapper = vtk.vtkPolyDataMapper()
      mapper.SetInputConnection(sphere.GetOutputPort())
      
      marker = vtk.vtkActor()
      marker.SetMapper(mapper)
      renderer.AddActor(marker)
      marker.GetProperty().SetColor(1, 0, 0)
      interactor.Render()
      
      # updates the dictionaries where the point coordinates are stored
      if len(pointsDict.keys()) > 0:
          pointNum = max(pointsDict.keys())
      else:
          pointNum = 0
      
      pointsDict.update({pointNum + 1:[i, j, k]})
      actorDict.update({pointNum + 1:marker})
      
      print_points_to_screen(pointsDict.values(),',',4)
      
      
    if key in 'd':
      x, y = interactor.GetEventPosition()
      
      cellPicker = vtk.vtkCellPicker()
      cellPicker.SetTolerance(0.00001)
      cellPicker.Pick(x, y, 0, renderer)
      
      points = cellPicker.GetPickedPositions()
      numPoints = points.GetNumberOfPoints()
      if numPoints < 1:
        return()
      i, j, k = points.GetPoint(0)
      
      min_distance_to_point = 1e12
      for point, posn in pointsDict.items():
        distance_to_point = diagonal(posn[0]-i,posn[1]-j,posn[2]-k)
        if (distance_to_point < min_distance_to_point):
          min_distance_to_point = distance_to_point
          keyPoint = point
      
      try:    
         renderer.RemoveActor(actorDict[keyPoint])
         interactor.Render()
         
         del pointsDict[keyPoint]
         del actorDict[keyPoint]
         
         print("Deleted point #: ", keyPoint)
         print("Number of points remaining: ", str(len(pointsDict.keys())) )
         
      except KeyError:
         print("No point found at these coordinates")
         
      print_points_to_screen(pointsDict.values(),',',4)
      
      
    if key in 'o':
      #result = input('Output filename \"{}\" as .txt filetype. \n'.format(output_dir))
      #output_filename = str(output_dir) + str(result) + '.txt'
      output_file = "points.txt"
      
      precision = 4
      delimiter=','
      formatter = '{{:8.{}f}}'.format(precision)
      
      with open(output_file, 'w') as fp:
          for point in pointsDict.values():
              entry = delimiter.join([formatter.format(float(x)) for x in point])
              entry += os.linesep
              fp.write(entry)
      
      message('Wrote output file ',output_file)
Exemplo n.º 42
0
def main():
    fileName, center = get_program_parameters()

    # These are the centers for the streamline seed.
    seedCenters = [[0.0, 2.1, 0.5], [0.1, 2.1, 0.5], [0.1, 2.7, 0.5],
                   [0.08, 2.7, 0.5]]
    center = abs(center)
    if center >= len(seedCenters):
        center = len(seedCenters) - 1

    colors = vtk.vtkNamedColors()
    # Set the furniture colors, matching those in the VTKTextBook.
    tableTopColor = [0.59, 0.427, 0.392]
    filingCabinetColor = [0.8, 0.8, 0.6]
    bookShelfColor = [0.8, 0.8, 0.6]
    windowColor = [0.3, 0.3, 0.5]
    colors.SetColor("TableTop", *tableTopColor)
    colors.SetColor("FilingCabinet", *filingCabinetColor)
    colors.SetColor("BookShelf", *bookShelfColor)
    colors.SetColor("WindowColor", *windowColor)

    # We read a data file that represents a CFD analysis of airflow in an office
    # (with ventilation and a burning cigarette).
    reader = vtk.vtkDataSetReader()
    reader.SetFileName(fileName)

    # Create the scene.
    # We generate a whole bunch of planes which correspond to
    # the geometry in the analysis; tables, bookshelves and so on.
    table1 = vtk.vtkStructuredGridGeometryFilter()
    table1.SetInputData(reader.GetStructuredGridOutput())
    table1.SetExtent(11, 15, 7, 9, 8, 8)
    mapTable1 = vtk.vtkPolyDataMapper()
    mapTable1.SetInputConnection(table1.GetOutputPort())
    mapTable1.ScalarVisibilityOff()
    table1Actor = vtk.vtkActor()
    table1Actor.SetMapper(mapTable1)
    table1Actor.GetProperty().SetColor(colors.GetColor3d("TableTop"))

    table2 = vtk.vtkStructuredGridGeometryFilter()
    table2.SetInputData(reader.GetStructuredGridOutput())
    table2.SetExtent(11, 15, 10, 12, 8, 8)
    mapTable2 = vtk.vtkPolyDataMapper()
    mapTable2.SetInputConnection(table2.GetOutputPort())
    mapTable2.ScalarVisibilityOff()
    table2Actor = vtk.vtkActor()
    table2Actor.SetMapper(mapTable2)
    table2Actor.GetProperty().SetColor(colors.GetColor3d("TableTop"))

    FilingCabinet1 = vtk.vtkStructuredGridGeometryFilter()
    FilingCabinet1.SetInputData(reader.GetStructuredGridOutput())
    FilingCabinet1.SetExtent(15, 15, 7, 9, 0, 8)
    mapFilingCabinet1 = vtk.vtkPolyDataMapper()
    mapFilingCabinet1.SetInputConnection(FilingCabinet1.GetOutputPort())
    mapFilingCabinet1.ScalarVisibilityOff()
    FilingCabinet1Actor = vtk.vtkActor()
    FilingCabinet1Actor.SetMapper(mapFilingCabinet1)
    FilingCabinet1Actor.GetProperty().SetColor(
        colors.GetColor3d("FilingCabinet"))

    FilingCabinet2 = vtk.vtkStructuredGridGeometryFilter()
    FilingCabinet2.SetInputData(reader.GetStructuredGridOutput())
    FilingCabinet2.SetExtent(15, 15, 10, 12, 0, 8)
    mapFilingCabinet2 = vtk.vtkPolyDataMapper()
    mapFilingCabinet2.SetInputConnection(FilingCabinet2.GetOutputPort())
    mapFilingCabinet2.ScalarVisibilityOff()
    FilingCabinet2Actor = vtk.vtkActor()
    FilingCabinet2Actor.SetMapper(mapFilingCabinet2)
    FilingCabinet2Actor.GetProperty().SetColor(
        colors.GetColor3d("FilingCabinet"))

    bookshelf1Top = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Top.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Top.SetExtent(13, 13, 0, 4, 0, 11)
    mapBookshelf1Top = vtk.vtkPolyDataMapper()
    mapBookshelf1Top.SetInputConnection(bookshelf1Top.GetOutputPort())
    mapBookshelf1Top.ScalarVisibilityOff()
    bookshelf1TopActor = vtk.vtkActor()
    bookshelf1TopActor.SetMapper(mapBookshelf1Top)
    bookshelf1TopActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf1Bottom = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Bottom.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Bottom.SetExtent(20, 20, 0, 4, 0, 11)
    mapBookshelf1Bottom = vtk.vtkPolyDataMapper()
    mapBookshelf1Bottom.SetInputConnection(bookshelf1Bottom.GetOutputPort())
    mapBookshelf1Bottom.ScalarVisibilityOff()
    bookshelf1BottomActor = vtk.vtkActor()
    bookshelf1BottomActor.SetMapper(mapBookshelf1Bottom)
    bookshelf1BottomActor.GetProperty().SetColor(
        colors.GetColor3d("BookShelf"))

    bookshelf1Front = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Front.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Front.SetExtent(13, 20, 0, 0, 0, 11)
    mapBookshelf1Front = vtk.vtkPolyDataMapper()
    mapBookshelf1Front.SetInputConnection(bookshelf1Front.GetOutputPort())
    mapBookshelf1Front.ScalarVisibilityOff()
    bookshelf1FrontActor = vtk.vtkActor()
    bookshelf1FrontActor.SetMapper(mapBookshelf1Front)
    bookshelf1FrontActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf1Back = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Back.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Back.SetExtent(13, 20, 4, 4, 0, 11)
    mapBookshelf1Back = vtk.vtkPolyDataMapper()
    mapBookshelf1Back.SetInputConnection(bookshelf1Back.GetOutputPort())
    mapBookshelf1Back.ScalarVisibilityOff()
    bookshelf1BackActor = vtk.vtkActor()
    bookshelf1BackActor.SetMapper(mapBookshelf1Back)
    bookshelf1BackActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf1LHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1LHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1LHS.SetExtent(13, 20, 0, 4, 0, 0)
    mapBookshelf1LHS = vtk.vtkPolyDataMapper()
    mapBookshelf1LHS.SetInputConnection(bookshelf1LHS.GetOutputPort())
    mapBookshelf1LHS.ScalarVisibilityOff()
    bookshelf1LHSActor = vtk.vtkActor()
    bookshelf1LHSActor.SetMapper(mapBookshelf1LHS)
    bookshelf1LHSActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf1RHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1RHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1RHS.SetExtent(13, 20, 0, 4, 11, 11)
    mapBookshelf1RHS = vtk.vtkPolyDataMapper()
    mapBookshelf1RHS.SetInputConnection(bookshelf1RHS.GetOutputPort())
    mapBookshelf1RHS.ScalarVisibilityOff()
    bookshelf1RHSActor = vtk.vtkActor()
    bookshelf1RHSActor.SetMapper(mapBookshelf1RHS)
    bookshelf1RHSActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf2Top = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Top.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Top.SetExtent(13, 13, 15, 19, 0, 11)
    mapBookshelf2Top = vtk.vtkPolyDataMapper()
    mapBookshelf2Top.SetInputConnection(bookshelf2Top.GetOutputPort())
    mapBookshelf2Top.ScalarVisibilityOff()
    bookshelf2TopActor = vtk.vtkActor()
    bookshelf2TopActor.SetMapper(mapBookshelf2Top)
    bookshelf2TopActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf2Bottom = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Bottom.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Bottom.SetExtent(20, 20, 15, 19, 0, 11)
    mapBookshelf2Bottom = vtk.vtkPolyDataMapper()
    mapBookshelf2Bottom.SetInputConnection(bookshelf2Bottom.GetOutputPort())
    mapBookshelf2Bottom.ScalarVisibilityOff()
    bookshelf2BottomActor = vtk.vtkActor()
    bookshelf2BottomActor.SetMapper(mapBookshelf2Bottom)
    bookshelf2BottomActor.GetProperty().SetColor(
        colors.GetColor3d("BookShelf"))

    bookshelf2Front = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Front.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Front.SetExtent(13, 20, 15, 15, 0, 11)
    mapBookshelf2Front = vtk.vtkPolyDataMapper()
    mapBookshelf2Front.SetInputConnection(bookshelf2Front.GetOutputPort())
    mapBookshelf2Front.ScalarVisibilityOff()
    bookshelf2FrontActor = vtk.vtkActor()
    bookshelf2FrontActor.SetMapper(mapBookshelf2Front)
    bookshelf2FrontActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf2Back = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Back.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Back.SetExtent(13, 20, 19, 19, 0, 11)
    mapBookshelf2Back = vtk.vtkPolyDataMapper()
    mapBookshelf2Back.SetInputConnection(bookshelf2Back.GetOutputPort())
    mapBookshelf2Back.ScalarVisibilityOff()
    bookshelf2BackActor = vtk.vtkActor()
    bookshelf2BackActor.SetMapper(mapBookshelf2Back)
    bookshelf2BackActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf2LHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2LHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2LHS.SetExtent(13, 20, 15, 19, 0, 0)
    mapBookshelf2LHS = vtk.vtkPolyDataMapper()
    mapBookshelf2LHS.SetInputConnection(bookshelf2LHS.GetOutputPort())
    mapBookshelf2LHS.ScalarVisibilityOff()
    bookshelf2LHSActor = vtk.vtkActor()
    bookshelf2LHSActor.SetMapper(mapBookshelf2LHS)
    bookshelf2LHSActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    bookshelf2RHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2RHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2RHS.SetExtent(13, 20, 15, 19, 11, 11)
    mapBookshelf2RHS = vtk.vtkPolyDataMapper()
    mapBookshelf2RHS.SetInputConnection(bookshelf2RHS.GetOutputPort())
    mapBookshelf2RHS.ScalarVisibilityOff()
    bookshelf2RHSActor = vtk.vtkActor()
    bookshelf2RHSActor.SetMapper(mapBookshelf2RHS)
    bookshelf2RHSActor.GetProperty().SetColor(colors.GetColor3d("BookShelf"))

    window = vtk.vtkStructuredGridGeometryFilter()
    window.SetInputData(reader.GetStructuredGridOutput())
    window.SetExtent(20, 20, 6, 13, 10, 13)
    mapWindow = vtk.vtkPolyDataMapper()
    mapWindow.SetInputConnection(window.GetOutputPort())
    mapWindow.ScalarVisibilityOff()
    windowActor = vtk.vtkActor()
    windowActor.SetMapper(mapWindow)
    windowActor.GetProperty().SetColor(colors.GetColor3d("WindowColor"))

    outlet = vtk.vtkStructuredGridGeometryFilter()
    outlet.SetInputData(reader.GetStructuredGridOutput())
    outlet.SetExtent(0, 0, 9, 10, 14, 16)
    mapOutlet = vtk.vtkPolyDataMapper()
    mapOutlet.SetInputConnection(outlet.GetOutputPort())
    mapOutlet.ScalarVisibilityOff()
    outletActor = vtk.vtkActor()
    outletActor.SetMapper(mapOutlet)
    outletActor.GetProperty().SetColor(colors.GetColor3d("lamp_black"))

    inlet = vtk.vtkStructuredGridGeometryFilter()
    inlet.SetInputData(reader.GetStructuredGridOutput())
    inlet.SetExtent(0, 0, 9, 10, 0, 6)
    mapInlet = vtk.vtkPolyDataMapper()
    mapInlet.SetInputConnection(inlet.GetOutputPort())
    mapInlet.ScalarVisibilityOff()
    inletActor = vtk.vtkActor()
    inletActor.SetMapper(mapInlet)
    inletActor.GetProperty().SetColor(colors.GetColor3d("lamp_black"))

    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(reader.GetStructuredGridOutput())
    mapOutline = vtk.vtkPolyDataMapper()
    mapOutline.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(mapOutline)
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Black"))

    # Create the source for the streamtubes.
    seeds = vtk.vtkPointSource()
    seeds.SetRadius(0.075)
    seeds.SetCenter(seedCenters[center])
    seeds.SetNumberOfPoints(25)
    streamers = vtk.vtkStreamTracer()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(seeds.GetOutputPort())
    streamers.SetMaximumPropagation(500)
    streamers.SetMinimumIntegrationStep(0.1)
    streamers.SetMaximumIntegrationStep(1.0)
    streamers.SetInitialIntegrationStep(0.2)
    streamers.Update()
    mapStreamers = vtk.vtkPolyDataMapper()
    mapStreamers.SetInputConnection(streamers.GetOutputPort())
    mapStreamers.SetScalarRange(
        reader.GetOutput().GetPointData().GetScalars().GetRange())
    streamersActor = vtk.vtkActor()
    streamersActor.SetMapper(mapStreamers)

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the remaining actors to the renderer, set the background and size.
    ren.AddActor(table1Actor)
    ren.AddActor(table2Actor)
    ren.AddActor(FilingCabinet1Actor)
    ren.AddActor(FilingCabinet2Actor)
    ren.AddActor(bookshelf1TopActor)
    ren.AddActor(bookshelf1BottomActor)
    ren.AddActor(bookshelf1FrontActor)
    ren.AddActor(bookshelf1BackActor)
    ren.AddActor(bookshelf1LHSActor)
    ren.AddActor(bookshelf1RHSActor)
    ren.AddActor(bookshelf2TopActor)
    ren.AddActor(bookshelf2BottomActor)
    ren.AddActor(bookshelf2FrontActor)
    ren.AddActor(bookshelf2BackActor)
    ren.AddActor(bookshelf2LHSActor)
    ren.AddActor(bookshelf2RHSActor)
    ren.AddActor(windowActor)
    ren.AddActor(outletActor)
    ren.AddActor(inletActor)
    ren.AddActor(outlineActor)
    ren.AddActor(streamersActor)

    ren.SetBackground(colors.GetColor3d("SlateGray"))

    aCamera = vtk.vtkCamera()
    aCamera.SetClippingRange(0.726079, 36.3039)
    aCamera.SetFocalPoint(2.43584, 2.15046, 1.11104)
    aCamera.SetPosition(-4.76183, -10.4426, 3.17203)
    aCamera.ComputeViewPlaneNormal()
    aCamera.SetViewUp(0.0511273, 0.132773, 0.989827)
    aCamera.SetViewAngle(18.604)
    aCamera.Zoom(1.2)

    ren.SetActiveCamera(aCamera)

    renWin.SetSize(640, 400)
    iren.Initialize()
    iren.Start()
Exemplo n.º 43
0
def main():
    # vtkFlyingEdges3D was introduced in VTK >= 8.2
    use_flying_edges = vtk_version_ok(8, 2, 0)

    colors = vtk.vtkNamedColors()

    file_name = get_program_parameters()

    colors.SetColor('SkinColor', [240, 184, 160, 255])
    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 data within the
    # render window.
    #
    a_renderer = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(a_renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    # Set a background color for the renderer and set the size of the
    # render window (expressed in pixels).
    a_renderer.SetBackground(colors.GetColor3d('BkgColor'))
    ren_win.SetSize(640, 480)

    # 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)
    reader.Update()

    # An isosurface, or contour value of 500 is known to correspond to
    # the skin of the patient.
    # The triangle stripper is used to create triangle
    # strips from the isosurface these render much faster on may
    # systems.
    if use_flying_edges:
        try:
            skin_extractor = vtk.vtkFlyingEdges3D()
        except AttributeError:
            skin_extractor = vtk.vtkMarchingCubes()
    else:
        skin_extractor = vtk.vtkMarchingCubes()
    skin_extractor.SetInputConnection(reader.GetOutputPort())
    skin_extractor.SetValue(0, 500)
    skin_extractor.Update()

    skin_stripper = vtk.vtkStripper()
    skin_stripper.SetInputConnection(skin_extractor.GetOutputPort())
    skin_stripper.Update()

    skin_mapper = vtk.vtkPolyDataMapper()
    skin_mapper.SetInputConnection(skin_stripper.GetOutputPort())
    skin_mapper.ScalarVisibilityOff()

    skin = vtk.vtkActor()
    skin.SetMapper(skin_mapper)
    skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor'))
    skin.GetProperty().SetSpecular(0.3)
    skin.GetProperty().SetSpecularPower(20)

    # An isosurface, or contour value of 1150 is known to correspond to
    # the bone of the patient.
    # The triangle stripper is used to create triangle
    # strips from the isosurface these render much faster on may
    # systems.
    if use_flying_edges:
        try:
            bone_extractor = vtk.vtkFlyingEdges3D()
        except AttributeError:
            bone_extractor = vtk.vtkMarchingCubes()
    else:
        bone_extractor = vtk.vtkMarchingCubes()
    bone_extractor.SetInputConnection(reader.GetOutputPort())
    bone_extractor.SetValue(0, 1150)

    bone_stripper = vtk.vtkStripper()
    bone_stripper.SetInputConnection(bone_extractor.GetOutputPort())

    bone_mapper = vtk.vtkPolyDataMapper()
    bone_mapper.SetInputConnection(bone_stripper.GetOutputPort())
    bone_mapper.ScalarVisibilityOff()

    bone = vtk.vtkActor()
    bone.SetMapper(bone_mapper)
    bone.GetProperty().SetDiffuseColor(colors.GetColor3d('Ivory'))

    # An outline provides context around the data.
    #
    outline_data = vtk.vtkOutlineFilter()
    outline_data.SetInputConnection(reader.GetOutputPort())
    outline_data.Update()

    map_outline = vtk.vtkPolyDataMapper()
    map_outline.SetInputConnection(outline_data.GetOutputPort())

    outline = vtk.vtkActor()
    outline.SetMapper(map_outline)
    outline.GetProperty().SetColor(colors.GetColor3d('Black'))

    # Now we are creating three orthogonal planes passing through the
    # volume. Each plane uses a different texture map and therefore has
    # different coloration.

    # Start by creating a black/white lookup table.
    bw_lut = vtk.vtkLookupTable()
    bw_lut.SetTableRange(0, 2000)
    bw_lut.SetSaturationRange(0, 0)
    bw_lut.SetHueRange(0, 0)
    bw_lut.SetValueRange(0, 1)
    bw_lut.Build()  # effective built

    # Now create a lookup table that consists of the full hue circle
    # (from HSV).
    hue_lut = vtk.vtkLookupTable()
    hue_lut.SetTableRange(0, 2000)
    hue_lut.SetHueRange(0, 1)
    hue_lut.SetSaturationRange(1, 1)
    hue_lut.SetValueRange(1, 1)
    hue_lut.Build()  # effective built

    # Finally, create a lookup table with a single hue but having a range
    # in the saturation of the hue.
    sat_lut = vtk.vtkLookupTable()
    sat_lut.SetTableRange(0, 2000)
    sat_lut.SetHueRange(0.6, 0.6)
    sat_lut.SetSaturationRange(0, 1)
    sat_lut.SetValueRange(1, 1)
    sat_lut.Build()  # effective built

    # Create the first of the three planes. The filter vtkImageMapToColors
    # maps the data through the corresponding lookup table created above.  The
    # vtkImageActor is a type of vtkProp and conveniently displays an image on
    # a single quadrilateral plane. It does this using texture mapping and as
    # a result is quite fast. (Note: the input image has to be unsigned char
    # values, which the vtkImageMapToColors produces.) Note also that by
    # specifying the DisplayExtent, the pipeline requests data of this extent
    # and the vtkImageMapToColors only processes a slice of data.
    sagittal_colors = vtk.vtkImageMapToColors()
    sagittal_colors.SetInputConnection(reader.GetOutputPort())
    sagittal_colors.SetLookupTable(bw_lut)
    sagittal_colors.Update()

    sagittal = vtk.vtkImageActor()
    sagittal.GetMapper().SetInputConnection(sagittal_colors.GetOutputPort())
    sagittal.SetDisplayExtent(128, 128, 0, 255, 0, 92)
    sagittal.ForceOpaqueOn()

    # Create the second (axial) plane of the three planes. We use the
    # same approach as before except that the extent differs.
    axial_colors = vtk.vtkImageMapToColors()
    axial_colors.SetInputConnection(reader.GetOutputPort())
    axial_colors.SetLookupTable(hue_lut)
    axial_colors.Update()

    axial = vtk.vtkImageActor()
    axial.GetMapper().SetInputConnection(axial_colors.GetOutputPort())
    axial.SetDisplayExtent(0, 255, 0, 255, 46, 46)
    axial.ForceOpaqueOn()

    # Create the third (coronal) plane of the three planes. We use
    # the same approach as before except that the extent differs.
    coronal_colors = vtk.vtkImageMapToColors()
    coronal_colors.SetInputConnection(reader.GetOutputPort())
    coronal_colors.SetLookupTable(sat_lut)
    coronal_colors.Update()

    coronal = vtk.vtkImageActor()
    coronal.GetMapper().SetInputConnection(coronal_colors.GetOutputPort())
    coronal.SetDisplayExtent(0, 255, 128, 128, 0, 92)
    coronal.ForceOpaqueOn()

    # It is convenient to create an initial view of the data. The
    # FocalPoint and Position form a vector direction. Later on
    # (ResetCamera() method) this vector is used to position the camera
    # to look at the data in this direction.
    a_camera = vtk.vtkCamera()
    a_camera.SetViewUp(0, 0, -1)
    a_camera.SetPosition(0, -1, 0)
    a_camera.SetFocalPoint(0, 0, 0)
    a_camera.ComputeViewPlaneNormal()
    a_camera.Azimuth(30.0)
    a_camera.Elevation(30.0)

    # Actors are added to the renderer.
    a_renderer.AddActor(outline)
    a_renderer.AddActor(sagittal)
    a_renderer.AddActor(axial)
    a_renderer.AddActor(coronal)
    a_renderer.AddActor(skin)
    a_renderer.AddActor(bone)

    # Turn off bone for this example.
    bone.VisibilityOff()

    # Set skin to semi-transparent.
    skin.GetProperty().SetOpacity(0.5)

    # An initial camera view is created.  The Dolly() method moves
    # the camera towards the FocalPoint, thereby enlarging the image.
    a_renderer.SetActiveCamera(a_camera)

    # Calling Render() directly on a vtkRenderer is strictly forbidden.
    # Only calling Render() on the vtkRenderWindow is a valid call.
    ren_win.SetWindowName('MedicalDemo3')
    ren_win.Render()

    a_renderer.ResetCamera()
    a_camera.Dolly(1.5)

    # Note that when camera movement occurs (as it does in the Dolly()
    # method), the clipping planes often need adjusting. Clipping planes
    # consist of two planes: near and far along the view direction. The
    # near plane clips out objects in front of the plane; the far plane
    # clips out objects behind the plane. This way only what is drawn
    # between the planes is actually rendered.
    a_renderer.ResetCameraClippingRange()

    # Interact with the data.
    ren_win.Render()
    iren.Initialize()
    iren.Start()
Exemplo n.º 44
0
boneStripper = vtk.vtkStripper()
boneStripper.SetInputConnection(boneNormals.GetOutputPort())

boneLocator = vtk.vtkCellLocator()
boneLocator.SetDataSet(boneExtractor.GetOutput())
boneLocator.LazyEvaluationOn()

boneMapper = vtk.vtkPolyDataMapper()
boneMapper.SetInputConnection(boneStripper.GetOutputPort())
boneMapper.ScalarVisibilityOff()

boneProperty = vtk.vtkProperty()
boneProperty.SetColor(1.0, 1.0, 0.9)

bone = vtk.vtkActor()
bone.SetMapper(boneMapper)
bone.SetProperty(boneProperty)

#---------------------------------------------------------
# Create an image actor
table = vtk.vtkLookupTable()
table.SetRange(0, 2000)
table.SetRampToLinear()
table.SetValueRange(0, 1)
table.SetHueRange(0, 0)
table.SetSaturationRange(0, 0)

mapToColors = vtk.vtkImageMapToColors()
mapToColors.SetInputConnection(reader.GetOutputPort())
mapToColors.SetLookupTable(table)
Exemplo n.º 45
0
    def __init__(self, iren):
        """
        initialization of the interactor and fixed objects
        """
        # state indicators
        self.dim = 3
        self.contour_state = False

        # interactor
        self.iren = iren

        # empty defaults
        self.data = data.Data()
        self.current_timestep = 0
        self.line_points = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]

        # camera
        self.camera = vtk.vtkCamera()
        self.camera.Elevation(-70)
        self.camera.SetViewUp(0, 0, 1)
        self.camera.Azimuth(-60)

        # lookup table
        self.lut = vtk.vtkLookupTable()
        # self.lut.SetHueRange(0.66667, 0.0)
        for i in range(0, 255):
            x = i / 255.
            self.lut.SetTableValue(i, min(2. * x, 1.), 1.0 - abs(1.0 - 2 * x),
                                   min(2.0 - 2. * x, 1.0), 1.0)
        self.lut.SetScaleToLog10()
        self.lut.Build()

        # 3d mapper
        self.mapper3d = vtk.vtkDataSetMapper()
        self.mapper3d.SetLookupTable(self.lut)
        self.mapper3d.InterpolateScalarsBeforeMappingOn()

        # contour
        self.contour = vtk.vtkContourFilter()
        self.contour.SetNumberOfContours(1)

        # actors
        self.main_actor = vtk.vtkLODActor()
        self.main_actor.SetMapper(self.mapper3d)
        self.outline_actor = vtk.vtkActor()

        # render window
        self.ren_win = self.iren.GetRenderWindow()
        # self.ren_win.SetSize(800, 800)
        # self.ren_win.SetNumberOfLayers(2)

        # main renderer
        self.ren = vtk.vtkRenderer()
        # self.ren.SetLayer(0)
        self.ren.SetBackground(82. / 255, 87. / 255, 110. / 255)
        self.ren.SetActiveCamera(self.camera)
        self.ren_win.AddRenderer(self.ren)

        # set interaction style to paraview style
        self.iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        # keyboard bindings
        self.iren.AddObserver(vtk.vtkCommand.KeyPressEvent, self.on_keypress)

        self.add_widgets()
Exemplo n.º 46
0
reader5 = vtk.vtkSTLReader()
reader5.SetFileName("cframe.stl")

#Create a mapper and actor
mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInputConnection(reader1.GetOutputPort())
mapper2 = vtk.vtkPolyDataMapper()
mapper2.SetInputConnection(reader2.GetOutputPort())
mapper3 = vtk.vtkPolyDataMapper()
mapper3.SetInputConnection(reader3.GetOutputPort())
mapper4 = vtk.vtkPolyDataMapper()
mapper4.SetInputConnection(reader4.GetOutputPort())
mapper5 = vtk.vtkPolyDataMapper()
mapper5.SetInputConnection(reader5.GetOutputPort())

actor1 = vtk.vtkActor()
actor1.SetMapper(mapper1)
actor2 = vtk.vtkActor()
actor2.SetMapper(mapper2)
actor3 = vtk.vtkActor()
actor3.SetMapper(mapper3)
actor4 = vtk.vtkActor()
actor4.SetMapper(mapper4)
actor5 = vtk.vtkActor()
actor5.SetMapper(mapper5)

# Setup a renderer, render window, and interactor
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
Exemplo n.º 47
0
    def getActor(self):
        vtkActor = kwvtk.vtkActor()
        vtkActor.SetMapper(self.getVtkMapper())

        return vtkActor
Exemplo n.º 48
0
sample.Update()

# The cut plane
plane = vtk.vtkPlane()
plane.SetOrigin(0, 0, 0)
plane.SetNormal(1, 1, 1)

cut = vtk.vtkFlyingEdgesPlaneCutter()
cut.SetInputConnection(sample.GetOutputPort())
cut.SetPlane(plane)
cut.ComputeNormalsOff()

cutMapper = vtk.vtkPolyDataMapper()
cutMapper.SetInputConnection(cut.GetOutputPort())

cutActor = vtk.vtkActor()
cutActor.SetMapper(cutMapper)
cutActor.GetProperty().SetColor(1, 1, 1)
cutActor.GetProperty().SetOpacity(1)

# Create the RenderWindow, Renderer and both Actors
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren)
iRen = vtk.vtkRenderWindowInteractor()
iRen.SetRenderWindow(renWin)


# Create the widget, its representation, and callback
def main():
    colors = vtk.vtkNamedColors()

    # create a sphere
    sphere = vtk.vtkSphere()
    sphere.SetRadius(1)
    sphere.SetCenter(1, 0, 0)

    # create a box
    box = vtk.vtkBox()
    box.SetBounds(-1, 1, -1, 1, -1, 1)

    # combine the two implicit functions
    boolean = vtk.vtkImplicitBoolean()
    boolean.SetOperationTypeToDifference()
    # boolean.SetOperationTypeToUnion()
    # boolean.SetOperationTypeToIntersection()
    boolean.AddFunction(box)
    boolean.AddFunction(sphere)

    # The sample function generates a distance function from the implicit
    # function. This is then contoured to get a polygonal surface.
    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(boolean)
    sample.SetModelBounds(-1, 2, -1, 1, -1, 1)
    sample.SetSampleDimensions(40, 40, 40)
    sample.ComputeNormalsOff()

    # contour
    surface = vtk.vtkContourFilter()
    surface.SetInputConnection(sample.GetOutputPort())
    surface.SetValue(0, 0.0)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(surface.GetOutputPort())
    mapper.ScalarVisibilityOff()
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetColor(colors.GetColor3d('AliceBlue'))
    actor.GetProperty().SetEdgeColor(colors.GetColor3d('SteelBlue'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Silver'))

    # add the actor
    renderer.AddActor(actor)

    # render window
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    renwin.SetWindowName('BooleanOperationImplicitFunctions')

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Start
    interactor.Initialize()
    renwin.Render()
    # renderer.GetActiveCamera().AddObserver('ModifiedEvent', CameraModifiedCallback)
    renderer.GetActiveCamera().SetPosition(5.0, -4.0, 1.6)
    renderer.GetActiveCamera().SetViewUp(0.1, 0.5, 0.9)
    renderer.GetActiveCamera().SetDistance(6.7)
    renwin.Render()
    interactor.Start()
Exemplo n.º 50
0
outlineClip1.SetClippingPlanes(clippingPlanes)
outlineClip1.GenerateFacesOff()
outlineClip1.GenerateOutlineOn()
outlineClip1.SetScalarModeToColors()
outlineClip1.SetClipColor(1, 1, 0)
outlineClip1.SetActivePlaneId(2)
outlineClip1.SetActivePlaneColor(0, 1, 0)

postTrans1 = vtk.vtkTransformPolyDataFilter()
postTrans1.SetInputConnection(outlineClip1.GetOutputPort())
postTrans1.SetTransform(userTrans.GetInverse())

outlineMapper1 = vtk.vtkDataSetMapper()
outlineMapper1.SetInputConnection(postTrans1.GetOutputPort())

outlineActor1 = vtk.vtkActor()
outlineActor1.SetMapper(outlineMapper1)

volume1.SetUserTransform(userTrans)

outlineActor1.SetUserTransform(userTrans)

ren1.AddViewProp(outlineActor1)
ren1.AddViewProp(volume1)

volumeMapper1.SetCroppingRegionFlagsToFence()

outline1.GenerateScalarsOn()

ren1.ResetCamera()
ren1.GetActiveCamera().Zoom(1.35)
Exemplo n.º 51
0
def main():
    colors = vtk.vtkNamedColors()

    # Create polydata to slice the grid with. In this case, use a cone. This could
    # be any polydata including a stl file.
    cone = vtk.vtkConeSource()
    cone.SetResolution(20)
    cone.Update()

    # implicit function that will be used to slice the mesh
    implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance()
    implicitPolyDataDistance.SetInput(cone.GetOutput())

    # create a grid
    xCoords = vtk.vtkFloatArray()
    for x, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        xCoords.InsertNextValue(i)

    yCoords = vtk.vtkFloatArray()
    for y, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        yCoords.InsertNextValue(i)

    zCoords = vtk.vtkFloatArray()
    for z, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        zCoords.InsertNextValue(i)

    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(x + 1, y + 1, z + 1)
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(zCoords)

    # Create an array to hold distance information
    signedDistances = vtk.vtkFloatArray()
    signedDistances.SetNumberOfComponents(1)
    signedDistances.SetName('SignedDistances')

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

    # add the SignedDistances to the grid
    rgrid.GetPointData().SetScalars(signedDistances)

    # use vtkClipDataSet to slice the grid with the polydata
    clipper = vtk.vtkClipDataSet()
    clipper.SetInputData(rgrid)
    clipper.InsideOutOn()
    clipper.SetValue(0.0)
    clipper.Update()

    # --- mappers, actors, render, etc. ---
    # mapper and actor to view the cone
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    # geometry filter to view the background grid
    geometryFilter = vtk.vtkRectilinearGridGeometryFilter()
    geometryFilter.SetInputData(rgrid)
    geometryFilter.SetExtent(0, x + 1, 0, y + 1, (z + 1) // 2, (z + 1) // 2)
    geometryFilter.Update()

    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(geometryFilter.GetOutputPort())

    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetRepresentationToWireframe()
    wireActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # mapper and actor to view the clipped mesh
    clipperMapper = vtk.vtkDataSetMapper()
    clipperMapper.SetInputConnection(clipper.GetOutputPort())

    clipperActor = vtk.vtkActor()
    clipperActor.SetMapper(clipperMapper)
    clipperActor.GetProperty().SetRepresentationToWireframe()
    clipperActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Snow'))

    # add the actors
    # renderer.AddActor(coneActor)
    renderer.AddActor(wireActor)
    renderer.AddActor(clipperActor)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    renwin.SetWindowName('ClipDataSetWithPolyData')

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Start
    interactor.Initialize()
    renwin.Render()
    renderer.GetActiveCamera().SetPosition(0, -1, 0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 0, 1)
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.ResetCamera()
    renwin.Render()
    interactor.Start()
Exemplo n.º 52
0
glyph.SetInputArrayToProcess(3, 0, 0, 0, 'RTData')  # colors

# Calling update because I'm going to use the scalar range to set the color map range
glyph.Update()

coloring_by = 'RTData'
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
mapper.SetScalarModeToUsePointFieldData()
mapper.SetColorModeToMapScalars()
mapper.ScalarVisibilityOn()
mapper.SetScalarRange(
    glyph.GetOutputDataObject(0).GetPointData().GetArray(
        coloring_by).GetRange())
mapper.SelectColorArray(coloring_by)
actor = vtk.vtkActor()
actor.SetMapper(mapper)

ren = vtk.vtkRenderer()
ren.AddActor(actor)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
istyle = vtk.vtkInteractorStyleTrackballCamera()
iren.SetInteractorStyle(istyle)
iren.SetRenderWindow(renWin)
ren.ResetCamera()
renWin.Render()

iren.Start()
Exemplo n.º 53
0
# vtkClipPolyData requires an implicit function to define what it is to
# clip with. Any implicit function, including complex boolean combinations
# can be used. Notice that we can specify the value of the implicit function
# with the SetValue method.
clipper = vtk.vtkClipPolyData()
clipper.SetInputConnection(cowNormals.GetOutputPort())
clipper.SetClipFunction(plane)
clipper.GenerateClipScalarsOn()
clipper.GenerateClippedOutputOn()
clipper.SetValue(0.5)
clipMapper = vtk.vtkPolyDataMapper()
clipMapper.SetInputConnection(clipper.GetOutputPort())
clipMapper.ScalarVisibilityOff()
backProp = vtk.vtkProperty()
backProp.SetDiffuseColor(tomato)
clipActor = vtk.vtkActor()
clipActor.SetMapper(clipMapper)
clipActor.GetProperty().SetColor(peacock)
clipActor.SetBackfaceProperty(backProp)

# Here we are cutting the cow. Cutting creates lines where the cut
# function intersects the model. (Clipping removes a portion of the
# model but the dimension of the data does not change.)
#
# The reason we are cutting is to generate a closed polygon at the
# boundary of the clipping process. The cutter generates line
# segments, the stripper then puts them together into polylines. We
# then pull a trick and define polygons using the closed line
# segments that the stripper created.
cutEdges = vtk.vtkCutter()
cutEdges.SetInputConnection(cowNormals.GetOutputPort())
Exemplo n.º 54
0
    def __init__(self, data_dir,reader):
        planes = vtk.vtkPlane()
        planeC = vtk.vtkPlaneCollection()
        planeC.AddItem(planes)
        # Stripper for getting smooth poly outlines,
        # gives circle and not random triangles
        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(reader.GetOutputPort())
        # Clipper for PLANE
        
        clipper = vtk.vtkClipClosedSurface()
        clipper.SetInputConnection(stripper.GetOutputPort())
        clipper.SetClippingPlanes(planeC)
        clipMapper = vtk.vtkImageFlip()
        clipMapper = vtk.vtkPolyDataMapper()
        clipMapper.SetInputConnection(clipper.GetOutputPort())
        clipActor = vtk.vtkActor()
        clipActor.SetMapper(clipMapper)
        clipActor.GetProperty().SetColor(0.5,0.5,0.5)
        clipActor.GetProperty().SetOpacity(0.5)
        clipActor.SetPosition(0.001,0.001,0.001)

        clipperOutline = vtk.vtkClipClosedSurface()
        clipperOutline.SetInputConnection(stripper.GetOutputPort())
        clipperOutline.SetClippingPlanes(planeC)
        clipperOutline.GenerateFacesOff()
        clipperOutline.GenerateOutlineOn()
        innerNorms = vtk.vtkTriangleMeshPointNormals()
        innerNorms.SetInputConnection(reader.GetOutputPort())
        innerMapper = vtk.vtkOpenGLPolyDataMapper()
        innerMapper.SetInputConnection(innerNorms.GetOutputPort())
        innerActor = vtk.vtkActor()
        innerActor.SetMapper(innerMapper)

        clipperOutlineMapper = vtk.vtkPolyDataMapper()
        clipperOutlineMapper.SetInputConnection(clipperOutline.GetOutputPort())
        clipOutlineActor = vtk.vtkActor()
        clipOutlineActor.SetMapper(clipperOutlineMapper)
        clipOutlineActor.GetProperty().SetColor(0,1,0)
        clipOutlineActor.SetPosition(0.001,0.001,0.001)


        planeWidget = vtk.vtkImagePlaneWidget()
        planeWidget.SetInputConnection(reader.GetOutputPort())
        planeWidget.RestrictPlaneToVolumeOn()
        planeWidget.GetResliceOutput()
        rsx = planeWidget.GetResliceAxes()
        #planeWidget.SetSliceIndex(52)
        #planeWidget.SetOrigin(1,-1,-1)
        planeWidget.SetResliceInterpolateToLinear()
        self.clipActor = clipActor

        self.planes = planes
        self.planeWidget = planeWidget
        self.innerActor = innerActor
        self.clipOutlineActor = clipOutlineActor
        


        px = planeWidget.GetSlicePosition()
        #Cut(px)
            
            #clipActor.VisibilityOn()
        def UpdateMesh(obj, event):
            obj.GetNormal()
            self.planes.SetNormal(obj.GetNormal())
            self.planes.SetOrigin(obj.GetOrigin())
            self.clipActor.VisibilityOn()
            
        #planeWidget.AddObserver("EndInteractionEvent", CutMesh) 
        planeWidget.AddObserver("InteractionEvent", UpdateMesh)
        self.planeWidget = planeWidget
Exemplo n.º 55
0
p1.SetPointSize(4)

# Top row has lighting on
p2 = vtk.vtkProperty()
p2.DeepCopy(p1)
p2.LightingOn()

light = vtk.vtkLight()
light.SetPosition(1, 1, 1)

for m in mappers:
    # Push back the polygons
    m.SetRelativeCoincidentTopologyPolygonOffsetParameters(10, 2)

    # Bottom renderer shows cube without lighting
    actors.append(vtk.vtkActor())
    a1 = actors[-1]
    a1.SetMapper(m)
    a1.SetProperty(p1)
    renderers.append(vtk.vtkRenderer())
    r1 = renderers[-1]
    r1.AddActor(a1)
    r1.RemoveAllLights()
    r1.AddLight(light)
    r1.SetViewport(x, 0, x + dx, 0.5)
    renWin.AddRenderer(r1)

    # Top renderer shows cube with lighting
    actors.append(vtk.vtkActor())
    a2 = actors[-1]
    a2.SetMapper(m)
Exemplo n.º 56
0
# First way or writing
w = vtk.vtkPLYWriter()
w.SetInputConnection(pd2cd.GetOutputPort())
w.SetFileName("plyWriter.ply")
w.SetFileTypeToBinary()
w.SetDataByteOrderToLittleEndian()
w.SetColorModeToUniformCellColor()
w.SetColor(255,0,0)
w.Write()
r = vtk.vtkPLYReader()
r.SetFileName("plyWriter.ply")
r.Update()
file.delete("-force", "plyWriter.ply")
plyMapper = vtk.vtkPolyDataMapper()
plyMapper.SetInputConnection(r.GetOutputPort())
plyActor = vtk.vtkActor()
plyActor.SetMapper(plyMapper)
# Second way or writing - it will map through a lookup table
lut = vtk.vtkLookupTable()
lut.Build()
w2 = vtk.vtkPLYWriter()
w2.SetInputConnection(pd2cd.GetOutputPort())
w2.SetFileName("plyWriter.ply")
w2.SetFileTypeToBinary()
w2.SetDataByteOrderToLittleEndian()
w2.SetColorModeToDefault()
w2.SetLookupTable(lut)
w2.SetArrayName("Elevation")
w2.SetComponent(0)
w2.Write()
r2 = vtk.vtkPLYReader()
Exemplo n.º 57
0
    def show_cell(
        self,
        cell_id,
        control_volume_boundaries_rgba=None,
        barycenter_rgba=None,
        circumcenter_rgba=None,
        incenter_rgba=None,
        face_circumcenter_rgba=None,
        insphere_rgba=None,
        circumsphere_rgba=None,
        line_width=1.0,
        close=False,
    ):
        import vtk

        def get_line_actor(x0, x1, line_width=1.0):
            source = vtk.vtkLineSource()
            source.SetPoint1(x0)
            source.SetPoint2(x1)
            # mapper
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(source.GetOutputPort())
            # actor
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            # color actor
            actor.GetProperty().SetColor(0, 0, 0)
            actor.GetProperty().SetLineWidth(line_width)
            return actor

        def get_sphere_actor(x0, r, rgba):
            # Generate polygon data for a sphere
            sphere = vtk.vtkSphereSource()

            sphere.SetCenter(x0)
            sphere.SetRadius(r)

            sphere.SetPhiResolution(100)
            sphere.SetThetaResolution(100)

            # Create a mapper for the sphere data
            sphere_mapper = vtk.vtkPolyDataMapper()
            # sphere_mapper.SetInput(sphere.GetOutput())
            sphere_mapper.SetInputConnection(sphere.GetOutputPort())

            # Connect the mapper to an actor
            sphere_actor = vtk.vtkActor()
            sphere_actor.SetMapper(sphere_mapper)
            sphere_actor.GetProperty().SetColor(rgba[:3])
            sphere_actor.GetProperty().SetOpacity(rgba[3])
            return sphere_actor

        # Visualize
        renderer = vtk.vtkRenderer()
        render_window = vtk.vtkRenderWindow()
        # render_window.SetOffScreenRendering(1)
        render_window.AddRenderer(renderer)
        render_window_interactor = vtk.vtkRenderWindowInteractor()
        render_window_interactor.SetRenderWindow(render_window)

        for ij in [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]:
            x0, x1 = self.node_coords[self.cells["nodes"][cell_id][ij]]
            renderer.AddActor(get_line_actor(x0, x1, line_width))
        renderer.SetBackground(1.0, 1.0, 1.0)

        r = 0.02

        if circumcenter_rgba is not None:
            renderer.AddActor(
                get_sphere_actor(self.cell_circumcenters[cell_id], r,
                                 circumcenter_rgba))

        if circumsphere_rgba is not None:
            renderer.AddActor(
                get_sphere_actor(
                    self.cell_circumcenters[cell_id],
                    self.cell_circumradius[cell_id],
                    circumsphere_rgba,
                ))

        if incenter_rgba is not None:
            renderer.AddActor(
                get_sphere_actor(self.cell_incenters[cell_id], r,
                                 incenter_rgba))

        if insphere_rgba is not None:
            renderer.AddActor(
                get_sphere_actor(
                    self.cell_incenters[cell_id],
                    self.cell_inradius[cell_id],
                    insphere_rgba,
                ))

        if barycenter_rgba is not None:
            renderer.AddActor(
                get_sphere_actor(self.cell_barycenters[cell_id], r,
                                 barycenter_rgba))

        if face_circumcenter_rgba is not None:
            x = self.node_coords[self.node_face_cells[..., [cell_id]]]
            face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei,
                                                      self.ei_dot_ej)[:, 0, :]
            for f in face_ccs:
                renderer.AddActor(
                    get_sphere_actor(f, r, face_circumcenter_rgba))

        if control_volume_boundaries_rgba:
            cell_cc = self.cell_circumcenters[cell_id]
            x = self.node_coords[self.node_face_cells[..., [cell_id]]]
            face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei,
                                                      self.ei_dot_ej)[:, 0, :]
            for face, face_cc in zip(range(4), face_ccs):
                for edge in range(3):
                    k0, k1 = self.idx_hierarchy[:, edge, face, cell_id]
                    edge_midpoint = 0.5 * (self.node_coords[k0] +
                                           self.node_coords[k1])

                    points = vtk.vtkPoints()
                    points.InsertNextPoint(*edge_midpoint)
                    points.InsertNextPoint(*cell_cc)
                    points.InsertNextPoint(*face_cc)

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

                    triangles = vtk.vtkCellArray()
                    triangles.InsertNextCell(triangle)

                    trianglePolyData = vtk.vtkPolyData()
                    trianglePolyData.SetPoints(points)
                    trianglePolyData.SetPolys(triangles)

                    # mapper
                    mapper = vtk.vtkPolyDataMapper()
                    if vtk.VTK_MAJOR_VERSION <= 5:
                        mapper.SetInput(trianglePolyData)
                    else:
                        mapper.SetInputData(trianglePolyData)

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

                    actor.GetProperty().SetColor(
                        *control_volume_boundaries_rgba[:3])
                    actor.GetProperty().SetOpacity(
                        control_volume_boundaries_rgba[3])
                    renderer.AddActor(actor)

        render_window.Render()

        if close:
            render_window.Finalize()
            del render_window, render_window_interactor
        else:
            render_window_interactor.Start()
        return
Exemplo n.º 58
0
trianglePolyData.GetPointData().SetScalars(colors)
trianglePolyData.SetPolys(triangles)

# Clean the polydata so that the edges are shared !
cleanPolyData = vtk.vtkCleanPolyData()
cleanPolyData.SetInputData(trianglePolyData)

# Use a filter to smooth the data (will add triangles and smooth)
smooth_loop = vtk.vtkLoopSubdivisionFilter()
smooth_loop.SetNumberOfSubdivisions(3)
smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())

# Create a mapper and actor for smoothed dataset
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(smooth_loop.GetOutputPort())
actor_loop = vtk.vtkActor()
actor_loop.SetMapper(mapper)
actor_loop.GetProperty().SetInterpolationToFlat()

# Update the pipeline so that vtkCellLocator finds cells !
smooth_loop.Update()

# Define a cellLocator to be able to compute intersections between lines
# and the surface
locator = vtk.vtkCellLocator()
locator.SetDataSet(smooth_loop.GetOutput())
locator.BuildLocator()

maxloop = 1000
dist = 20.0 / maxloop
tolerance = 0.001
Exemplo n.º 59
0
        xform = vtk.vtkTransformPolyDataFilter()
        xform.SetTransform(transform)
        xform.SetInputConnection(source.GetOutputPort())
        xform.Update()

        output.ShallowCopy(xform.GetOutputDataObject(0))
        return 1


source1 = MovingSphereSource()
group1 = vtk.vtkGroupTimeStepsFilter()
group1.SetInputConnection(source1.GetOutputPort())
mapper1 = vtk.vtkCompositePolyDataMapper2()
mapper1.SetInputConnection(group1.GetOutputPort())
actor1 = vtk.vtkActor()
actor1.SetMapper(mapper1)

source2 = MovingPDC()
group2 = vtk.vtkGroupTimeStepsFilter()
group2.SetInputConnection(source2.GetOutputPort())
mapper2 = vtk.vtkCompositePolyDataMapper2()
mapper2.SetInputConnection(group2.GetOutputPort())
actor2 = vtk.vtkActor()
actor2.SetMapper(mapper2)

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Exemplo n.º 60
0
plane.SetOrigin(output.GetCenter())
plane.SetNormal(-0.287, 0, 0.9579)

planeCut = vtk.vtkCutter()
planeCut.SetInputData(output)
planeCut.SetCutFunction(plane)

probe = vtk.vtkProbeFilter()
probe.SetInputConnection(planeCut.GetOutputPort())
probe.SetSourceData(output)

cutMapper = vtk.vtkDataSetMapper()
cutMapper.SetInputConnection(probe.GetOutputPort())
cutMapper.SetScalarRange(output.GetPointData().GetScalars().GetRange())

cutActor = vtk.vtkActor()
cutActor.SetMapper(cutMapper)

#extract plane
compPlane = vtk.vtkStructuredGridGeometryFilter()
compPlane.SetInputData(output)
compPlane.SetExtent(0, 100, 0, 100, 9, 9)

planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(compPlane.GetOutputPort())
planeMapper.ScalarVisibilityOff()

planeActor = vtk.vtkActor()
planeActor.SetMapper(planeMapper)
planeActor.GetProperty().SetRepresentationToWireframe()
planeActor.GetProperty().SetColor(0, 0, 0)