コード例 #1
0
ファイル: sympler_viewer.py プロジェクト: argreiner/sympler
    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)
コード例 #2
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()
コード例 #3
0
ファイル: vtkgui.py プロジェクト: capitalaslash/radcal-gui
 def add_outline(self):
     outline = vtk.vtkOutlineFilter()
     outline.SetInputData(self.data.grid[self.current_timestep])
     outline_mapper = vtk.vtkDataSetMapper()
     outline_mapper.SetInputConnection(outline.GetOutputPort())
     self.outline_actor.SetMapper(outline_mapper)
     self.ren.AddActor(self.outline_actor)
コード例 #4
0
    def unstructered_grid_reader(filename):
        # Read the source file.
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update() # Needed because of GetScalarRange
        output = reader.GetOutput()
        scalar_range = output.GetScalarRange()

        # Create the mapper that corresponds the objects of the vtk file
        # into graphics elements
        mapper =vtk.vtkDataSetMapper()
        mapper.SetInputData(output)
        mapper.SetScalarRange(scalar_range)

        # Create the Actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        # Create the Renderer
        renderer = vtk.vtkRenderer()
        renderer.AddActor(actor)
        renderer.SetBackground(1, 1, 1) # Set background to white

        # Create the RendererWindow
        renderer_window = vtk.vtkRenderWindow()
        renderer_window.AddRenderer(renderer)

        # Create the RendererWindowInteractor and display the vtk_file
        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetRenderWindow(renderer_window)
        interactor.Initialize()
        interactor.Start()
コード例 #5
0
ファイル: vtk_FE_graphic.py プロジェクト: lcpt/xc
    def VtkDefineElementsActor(self, reprType,field,color=xc.Vector([rd.random(),rd.random(),rd.random()])):
        ''' Define the actor to display elements

        :param reprType: type of representation ("points", "wireframe" or
               "surface")
        :param field: field to be repreresented
        :param color: RGB color to represent the elements (defaults to random
                      color)
        '''
        if(field):
            field.setupOnGrid(self.gridRecord.uGrid)
        self.gridMapper= vtk.vtkDataSetMapper()
        self.gridMapper.SetInputData(self.gridRecord.uGrid)
        if(field):
            field.setupOnMapper(self.gridMapper)
        elemActor= vtk.vtkActor()
        elemActor.SetMapper(self.gridMapper)
        elemActor.GetProperty().SetColor(color[0],color[1],color[2])

        if(reprType=="points"):
            elemActor.GetProperty().SetRepresentationToPoints()
        elif(reprType=="wireframe"):
            elemActor.GetProperty().SetRepresentationToWireFrame()
        elif(reprType=="surface"):
            elemActor.GetProperty().SetRepresentationToSurface()
        else:
            lmsg.error("Representation type: '"+ reprType+ "' unknown.")
        self.renderer.AddActor(elemActor)
        if(field):
            field.creaColorScaleBar()
            self.renderer.AddActor2D(field.scalarBar)
コード例 #6
0
ファイル: plotter.py プロジェクト: trianam/voropath
    def addTriangles(self, triangles, color):
        vtkPoints = vtk.vtkPoints()
        idPoint = 0
        allIdsTriangle = []

        for triangle in triangles:
            idsTriangle = []

            for point in triangle:
                vtkPoints.InsertNextPoint(point[0], point[1], point[2])
                idsTriangle.append(idPoint)
                idPoint += 1

            allIdsTriangle.append(idsTriangle)

        unstructuredGrid = vtk.vtkUnstructuredGrid()
        unstructuredGrid.SetPoints(vtkPoints)
        for idsTriangle in allIdsTriangle:
            unstructuredGrid.InsertNextCell(vtk.VTK_TRIANGLE, 3, idsTriangle)

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(unstructuredGrid)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color)

        self._rendererScene.AddActor(actor)
コード例 #7
0
ファイル: structure_vtk.py プロジェクト: jesuansito/pymatgen
    def add_polyhedron(self, neighbors, center, color):
        """
        Adds a polyhedron.

        Args:
            neighbors:
                Neighbors of the polyhedron (the vertices).
            center:
                The atom in the center of the polyhedron.
            color:
                Color for text as RGB.
        """
        points = vtk.vtkPoints()
        conv = vtk.vtkConvexPointSet()
        for i in range(len(neighbors)):
            x, y, z = neighbors[i].coords
            points.InsertPoint(i, x, y, z)
            conv.GetPointIds().InsertId(i, i)
        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(conv.GetCellType(), conv.GetPointIds())
        grid.SetPoints(points)

        dsm = vtk.vtkDataSetMapper()
        polysites = [center]
        polysites.extend(neighbors)
        self.mapper_map[dsm] = polysites
        dsm.SetInput(grid)
        ac = vtk.vtkActor()
        #ac.SetMapper(mapHull)
        ac.SetMapper(dsm)
        ac.GetProperty().SetOpacity(0.4)
        ac.GetProperty().SetColor(color)
        self.ren.AddActor(ac)
コード例 #8
0
ファイル: vtkRender.py プロジェクト: smdabdoub/ProkaryMetrics
 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)
コード例 #9
0
ファイル: ExodusActor.py プロジェクト: aeslaughter/moose
    def __init__(self, renderer, data, type, index):
        PeacockActor.__init__(self, renderer)
        self.data = data
        self.type = type
        self.index = index

        self.solid_visible = False
        self.edges_visible = False

        self.mesh = data.GetBlock(type).GetBlock(index)

        self.geom = vtk.vtkDataSetSurfaceFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.geom.SetInput(self.mesh)
        else:
            self.geom.SetInputData(self.mesh)
        self.geom.Update()

        self.mapper = vtk.vtkDataSetMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.mesh)
        else:
            self.mapper.SetInputData(self.mesh)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetPointSize(5)
        self.actor.GetProperty().SetEdgeColor(0,0,0)
        self.actor.GetProperty().SetAmbient(0.3);
コード例 #10
0
ファイル: mylib_grid.py プロジェクト: PBrockmann/VTK_Mapper
def grid_create(
		arg_grid_delta,
		arg_grid_color,
		arg_grid_width,
		arg_projection,
		arg_ratioxy):

	gridpolydata=vtk.vtkAppendPolyData()
	for i in range(0,int(90*arg_ratioxy),int(arg_grid_delta*arg_ratioxy)) :
		latpolydata=latitude_create(i,arg_projection)
		gridpolydata.AddInputData(latpolydata)
	for i in range(0,int(-90*arg_ratioxy),int(-arg_grid_delta*arg_ratioxy)) :
		latpolydata=latitude_create(i,arg_projection)
		gridpolydata.AddInputData(latpolydata)
	if arg_projection == 'linear' :
		for i in range(-180,540,arg_grid_delta) :
			lonpolydata=longitude_create(i,arg_projection,arg_ratioxy)
			gridpolydata.AddInputData(lonpolydata)
	else:
		for i in range(0,180,arg_grid_delta) :
			lonpolydata=longitude_create(i,arg_projection)
			gridpolydata.AddInputData(lonpolydata)

	gridpolygonmapper=vtk.vtkDataSetMapper()
	gridpolygonmapper.SetInputConnection(gridpolydata.GetOutputPort())

	gridpolygonactor=vtk.vtkActor()
	gridpolygonactor.SetMapper(gridpolygonmapper)
	gridpolygonactor.GetProperty().SetColor(arg_grid_color)
	gridpolygonactor.GetProperty().SetLineWidth(arg_grid_width)
	gridpolygonactor.GetProperty().SetAmbient(1)
	gridpolygonactor.GetProperty().SetDiffuse(0)
	gridpolygonactor.PickableOff()

	return(gridpolygonactor)
コード例 #11
0
ファイル: MraImageDisplayWindow.py プロジェクト: CoderXv/vas
def create_vessel_actor(ref_data):
    vessel_ref_data = ref_data
    points = vtk.vtkPoints()

    # insert each properties of points into obj.
    for i in range(vessel_ref_data.get_len_of_vassel_value()):
        x = vessel_ref_data.get_abscissa_value_at(i)
        y = vessel_ref_data.get_ordinate_value_at(i)
        z = vessel_ref_data.get_iso_value_at(i)
        points.InsertPoint(i, x, y, z)

    poly = vtk.vtkPolyVertex()
    poly.GetPointIds().SetNumberOfIds(vessel_ref_data.get_len_of_vassel_value())

    cont = 0
    while cont < vessel_ref_data.get_len_of_vassel_value():
        poly.GetPointIds().SetId(cont, cont)
        cont += 1

    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.InsertNextCell(poly.GetCellType(), poly.GetPointIds())

    mapper = vtk.vtkDataSetMapper()
    if sys.hexversion == 34015984:
        mapper.SetInputData(grid)
    elif sys.hexversion == 34015728:
        mapper.SetInput(grid)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor
コード例 #12
0
ファイル: gui_main.py プロジェクト: zwghit/ProteusCFD
    def readMesh(self, path, casename):
        #read the mesh
        self.data.loadMesh(path, casename)

        # Create actors based on grid parts
        self.vtkActorList = []
        vtkgrids = self.data.buildVTKGrids()
        itag = 0
        c = colors()
        for vtkgrid in vtkgrids:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInput(vtkgrid)
            self.vtkActorList.append(vtk.vtkActor())
            self.vtkActorList[-1].SetMapper(mapper)
            self.vtkActorList[-1].GetProperty().SetColor(c.getNext())
            # set visibility of volumes to false on startup
            if int(self.data.elemGroups[itag]) < 0:
                self.vtkActorList[-1].VisibilityOff()
            itag = itag + 1
            
        #visualize the grid
        for actor in self.vtkActorList:
            self.ren.AddActor(actor)
        self.iren.Render()
        
        #update mesh visibility options
        self.BCTab1.drawBCVizBoxes()
コード例 #13
0
ファイル: viewer.py プロジェクト: andrlikjirka/lisa
    def __init__(self, vtk_filename=None, vtk_data=None):
        """
        Initiate Viwer

        Parameters
        ----------
        vtk_filename : str
            Input VTK filename
        """

        QDialog.__init__(self)
        self.initUI()

        ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(ren)
        iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        if vtk_filename is not None:
            # VTK file
            reader = vtk.vtkUnstructuredGridReader()
            reader.SetFileName(vtk_filename)
            reader.Update()
            vtkdata = reader.GetOutput()

        if vtk_data is not None:
            vtkdata = vtk_data

        # VTK surface
        surface = vtk.vtkDataSetSurfaceFilter()
        surface.SetInput(vtkdata)
        surface.Update()

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(surface.GetOutput())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOff()
        # actor.GetProperty().SetEdgeColor(1,1,1)
        # actor.GetProperty().SetLineWidth(0.1)
        ren.AddActor(actor)

        # annot. cube
        axesActor = vtk.vtkAnnotatedCubeActor()
        axesActor.SetXPlusFaceText('R')
        axesActor.SetXMinusFaceText('L')
        axesActor.SetYMinusFaceText('H')
        axesActor.SetYPlusFaceText('F')
        axesActor.SetZMinusFaceText('A')
        axesActor.SetZPlusFaceText('P')
        axesActor.GetTextEdgesProperty().SetColor(1, 1, 0)
        axesActor.GetCubeProperty().SetColor(0, 0, 1)
        self.axes = vtk.vtkOrientationMarkerWidget()
        self.axes.SetOrientationMarker(axesActor)
        self.axes.SetInteractor(iren)
        self.axes.EnabledOn()
        self.axes.InteractiveOn()

        ren.ResetCamera()
        iren.Initialize()
コード例 #14
0
def create_vessel_actor(ref_data):
    # vessel_ref_data = ref_data

    points = vtk.vtkPoints()

    # insert each properties of points into obj.
    for i in xrange(len(ref_data)):
        x = ref_data[i][0]
        y = ref_data[i][1]
        z = ref_data[i][2]
        points.InsertPoint(i, x, y, z)

    poly = vtk.vtkPolyVertex()
    poly.GetPointIds().SetNumberOfIds(len(ref_data))

    cont = 0
    while cont < len(ref_data):
        poly.GetPointIds().SetId(cont, cont)
        cont += 1

    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.InsertNextCell(poly.GetCellType(), poly.GetPointIds())

    mapper = vtk.vtkDataSetMapper()
    if sys.hexversion == 34015984:
        mapper.SetInputData(grid)
    if sys.hexversion == 34015728:
        mapper.SetInput(grid)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor
コード例 #15
0
    def GridSurface(self):
        #----------------------------------------------------------------------
        # ELECTRODE CONTACT DELAUNAY TRIANGULATION ----------------------------
        deln = vtk.vtkDelaunay3D()
        deln.SetInput(self.electrodePolyData)
        deln.SetTolerance(0.01)
        tmapper = vtk.vtkTextureMapToSphere()
        tmapper.SetInputConnection(deln.GetOutputPort())
        #tmapper.PreventSeamOn()
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(tmapper.GetOutputPort())

        # TEST TEXTURE PART
        atext = vtk.vtkOpenGLTexture()

        self.contactScalarData = vtk.vtkDoubleArray()
        self.contactScalarData.SetNumberOfComponents(1)
        for tupleID in range(self.electrodePolyData.GetNumberOfPoints()):
            self.contactScalarData.InsertNextValue(random.uniform(0, 1))

        self.UpdateGridSurface()
        atext.SetInput(self.electrodePolyData)
        self.triangulation = vtk.vtkOpenGLActor()
        self.triangulation.SetMapper(mapper)
        self.triangulation.SetTexture(atext)
        self.triangulation.GetProperty().SetOpacity(1)
コード例 #16
0
ファイル: sse.py プロジェクト: JDonner/gabbleduck
def show_beta_sheets(renderer):
    for sheet in sheet_defs:
#    helix = helix_defs[1]
        aPolyLineGrid = vtk.vtkUnstructuredGrid()
        aPolyLineGrid.Allocate(5, 1)

        (polyLinePoints, aPolyLine) = make_polyline(sheet)

#         # Create a tube filter to represent the lines as tubes.  Set up the
#         # associated mapper and actor.
#         tuber = vtk.vtkTubeFilter()
#         tuber.SetInputConnection(appendF.GetOutputPort())
#         tuber.SetRadius(0.1)
#         lineMapper = vtk.vtkPolyDataMapper()
#         lineMapper.SetInputConnection(tuber.GetOutputPort())
#         lineActor = vtk.vtkActor()
#         lineActor.SetMapper(lineMapper)

        aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(),
                                     aPolyLine.GetPointIds())
        aPolyLineGrid.SetPoints(polyLinePoints)

        aPolyLineMapper = vtk.vtkDataSetMapper()
        aPolyLineMapper.SetInput(aPolyLineGrid)
        aPolyLineActor = vtk.vtkActor()
        aPolyLineActor.SetMapper(aPolyLineMapper)
        aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1)

        renderer.AddActor(aPolyLineActor)
コード例 #17
0
    def testUnstructured(self):
        rt = vtk.vtkRTAnalyticSource()
        rt.SetWholeExtent(-5, 5, -5, 5, -5, 5)

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

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

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

        c.Update()

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

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

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

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

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

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

        rtTester = vtk.vtkTesting()
        for arg in sys.argv[1:]:
            rtTester.AddArgument(arg)
        rtTester.AddArgument("-V")
        rtTester.AddArgument("tableBasedClip.png")
        rtTester.SetRenderWindow(rw)
        rw.Render()
        rtResult = rtTester.RegressionTest(10)
コード例 #18
0
ファイル: pcd_scanner.py プロジェクト: stetro/objScanner
def show_vtk_file(path):
	# open vtk file from arglist
	reader = vtk.vtkDataSetReader()
	reader.SetFileName(path)
	reader.Update()
	# read out data and scalarrange
	output = reader.GetOutput()
	scalarrange = output.GetScalarRange()
	# generate Mapper and set DataSource
	mapper = vtk.vtkDataSetMapper()
	mapper.SetInput(output)
	mapper.SetScalarRange(scalarrange)
	# create actor
	actor = vtk.vtkActor()
	actor.SetMapper(mapper)
	# build renderer
	renderer = vtk.vtkRenderer()
	window = vtk.vtkRenderWindow()
	window.AddRenderer(renderer)
	# create interaction
	interaction = vtk.vtkRenderWindowInteractor()
	interaction.SetRenderWindow(window)
	# add actor
	renderer.AddActor(actor)
	# show window and start inteaction and renderer
	interaction.Initialize()
	window.Render()
	interaction.Start()
コード例 #19
0
	def InitVTKMethods(self):
		"""Initializes the VTK methods to be used."""
		self.colortable=ColorTableSource()
		self._plane=vtkPlane()
		self._cutter=vtkCutter()
		self._mapper=vtkDataSetMapper()
		self.actor=vtkLODActor()
コード例 #20
0
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""     
		self.x, self.y, self.z = -1, -1, -1
		VisualizationModule.__init__(self, parent, visualizer, **kws)   
		#self.name = "Scale bar"
		self.renew = 1
		self.mapper = vtk.vtkDataSetMapper()
		
		self.actor = vtk.vtkActor()
		self.actor.SetMapper(self.mapper)
		self.width = 10
		self.widthPx = 100
		self.voxelSize = (1, 1, 1)
		
		self.renderer = self.parent.getRenderer()
		self.renderer.AddActor(self.actor)
		

		self.polyLine = vtk.vtkPolyLine()
		#self.mapper.SetInput(self.polyLine.GetOutput())
		self.actor.GetProperty().SetColor(1, 1, 1)
			   
		self.textActor = vtk.vtkTextActor()
		#self.textActor.ScaledTextOn()
		self.renderer.AddActor2D(self.textActor)
		
		iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
		style = iactor.GetInteractorStyle()
#        style.AddObserver("StartInteractionEvent",self.updateLine)
		style.AddObserver("EndInteractionEvent", self.updateRendering)
コード例 #21
0
ファイル: pan.py プロジェクト: sukhbinder/cyNastran
    def addGeometry(self):
        print("addGeometry")
        self.aQuadMapper = vtk.vtkDataSetMapper()
        self.aQuadMapper.SetInput(self.grid)

        #lut = vtk.vtkLookupTable()
        #aQuadMapper.SetLookupTable(lut)

        #aQuadMapper.SetInput(Filter.GetOutput())
        geometryActor = vtk.vtkActor()
        #geometryActor.GetOutput().ReleaseDataFlagOn()
        geometryActor.SetMapper(self.aQuadMapper)
        #geometryActor.AddPosition(2, 0, 2)
        #geometryActor.GetProperty().SetDiffuseColor(0, 0, 1) # blue
        prop = geometryActor.GetProperty()
        #prop = geometryActor.GetProperty()
        #prop.SetColor(0.9, 0.9, 0.9)
        #prop.SetColor(1., 1., 1.)
        #prop.SetAmbient(0.9)
        #prop.SetDiffuse(0.1)
        #prop.SetSpecular(0.1)

        prop.SetDiffuseColor(1, 0, 0)  # red
        #prop = geometryActor.SetBackfaceProperty(prop)

        #geometryActor.GetProperty().SetBackfaceProperty(1, 0, 0) # red
        #geometryActor.GetProperty().BackfaceCullingOn()  # hidges elements that have normals not facing camera
        #geometryActor.GetProperty().SetLineWidth(0.5)
        self.rend.AddActor(geometryActor)
コード例 #22
0
ファイル: world.py プロジェクト: cjauvin/pypetree
 def __init___(self, scene, V, opacity=1, color='gray'):
     self.scene = scene
     self.frame = scene.frame
     self.V = V
     n_voxels = len(V)
     size = V.bin_size
     pts = vtk.vtkPoints()
     pts.SetNumberOfPoints(8 * n_voxels)
     grid = vtk.vtkUnstructuredGrid()
     grid.Allocate(n_voxels, 1)
     vx = vtk.vtkVoxel()
     for i, q in enumerate(V):
         pos = q * size + V.low_range
         pts.InsertPoint(i * 8 + 0, *pos)
         pts.InsertPoint(i * 8 + 1, *(pos + (size,0,0)))
         pts.InsertPoint(i * 8 + 2, *(pos + (0,size,0)))
         pts.InsertPoint(i * 8 + 3, *(pos + (size,size,0)))
         pts.InsertPoint(i * 8 + 4, *(pos + (0,0,size)))
         pts.InsertPoint(i * 8 + 5, *(pos + (size,0,size)))
         pts.InsertPoint(i * 8 + 6, *(pos + (0,size,size)))
         pts.InsertPoint(i * 8 + 7, *(pos + (size,size,size)))
         for j in range(8):
             vx.GetPointIds().SetId(j, i * 8 + j)
         grid.InsertNextCell(vx.GetCellType(), vx.GetPointIds())
     grid.SetPoints(pts)
     mapper = vtk.vtkDataSetMapper()
     mapper.SetInput(grid)
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(mapper)
     #self.actor.GetProperty().SetDiffuseColor(*name_to_rgb_float(color))
     self.actor.GetProperty().SetColor(*name_to_rgb_float(color))
     self.actor.GetProperty().SetOpacity(opacity)
     self.frame.ren.AddActor(self.actor)
コード例 #23
0
ファイル: VTK_Plotting.py プロジェクト: akaszynski/PyACVD
def PlotGrids_wFEM(grids):
    """ Plots CFD structured grids with a single FEM """

    N = len(grids)
    HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
    
    actors = []
    for i in range(len(grids)):
        
        # Create mapper
        mapper = vtk.vtkDataSetMapper()
        if vtk.vtkVersion().GetVTKMajorVersion() >5:
            mapper.SetInput(grids[i])
        else:
            mapper.SetInputData(grids[i])
        
        # Create actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOn()
        if i != 0:
            actor.GetProperty().SetRepresentationToWireframe()
            actor.GetProperty().SetColor(RGB_tuples[i])
        actor.GetProperty().LightingOff()
        actors.append(actor)
        
    # Add FEM Actor to renderer window
    ren = vtk.vtkRenderer()
#    ren.SetBackground(0.3, 0.3, 0.3)
    ren.SetBackground(0.8, 0.8, 0.8)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    # Allow user to interact
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    

    
    # Add actor
    for actor in actors:
        ren.AddActor(actor)
    
    axes = vtk.vtkAxesActor()
    widget = vtk.vtkOrientationMarkerWidget()
#    widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 )
    widget.SetOrientationMarker( axes )
    widget.SetInteractor( iren )
    widget.SetViewport( 0.0, 0.0, 0.4, 0.4 )
    widget.SetEnabled( 1 )
    widget.InteractiveOn()
    
    # Render
    iren.Initialize()
    renWin.Render()
    iren.Start()
コード例 #24
0
ファイル: pyfrp_gui_vtk.py プロジェクト: alexblaessle/PyFRAP
	def initMapper(self):
		
		"""Sets up simulation mapper."""
		
		self.mapper = vtk.vtkDataSetMapper()
		if vtk.VTK_MAJOR_VERSION <= 5:
			self.mapper.SetInputConnection(self.grid.GetProducerPort())
		else:
			self.mapper.SetInputData(self.grid)	
コード例 #25
0
ファイル: vtkPlotter.py プロジェクト: asimurzin/hybridFlu
    def getVTKActor(self, obj):
        self.triFilter = vtk.vtkDataSetTriangleFilter()
        self.mapper = vtk.vtkDataSetMapper()
        self.actor = vtk.vtkActor()

        self.triFilter.SetInput(obj)
        self.mapper.SetInput(self.triFilter.GetOutput())
        self.actor.SetMapper(self.mapper)
        self.ren.AddActor(self.actor)
コード例 #26
0
ファイル: gui_qt_common.py プロジェクト: umvarma/pynastran
    def _create_grid_mapper(self, name):
        self.grid = vtk.vtkUnstructuredGrid()
        self.aQuadMapper = vtk.vtkDataSetMapper()
        self.aQuadMapper.SetInput(self.grid)

        geometryActor = vtk.vtkActor()
        geometryActor.SetMapper(self.aQuadMapper)
        geometryActor.GetProperty().SetDiffuseColor(1, 0, 0)  # red
        self.rend.AddActor(geometryActor)
コード例 #27
0
ファイル: vtkTools.py プロジェクト: simpeg/simpegviz
	def makeVTKActor(vtkObj):
		""" Makes a vtk mapper and Actor"""
		mapper = vtk.vtkDataSetMapper()
		mapper.SetInput(vtkObj)
		actor = vtk.vtkActor()
		actor.SetMapper(mapper)
		actor.GetProperty().SetColor(0,0,0)
		actor.GetProperty().SetRepresentationToWireframe()
		return actor
コード例 #28
0
ファイル: vmtkmeshcutter.py プロジェクト: samsmu/vmtk
 def CutMesh(self):
     cutPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(cutPlane)
     self.MeshCutFilter.SetCutFunction(cutPlane)
     self.MeshCutFilter.Update()
     self.Actor = vtk.vtkActor()
     mapper = vtk.vtkDataSetMapper()
     mapper.SetInputConnection(self.MeshCutFilter.GetOutputPort())
     self.Actor.SetMapper(mapper)
     self.vmtkRenderer.Renderer.AddActor(self.Actor)
コード例 #29
0
ファイル: demoGui.py プロジェクト: xirxa/pynastran-locr
 def addGeometry(self):
     aQuadMapper = vtk.vtkDataSetMapper()
     aQuadMapper.SetInput(self.grid)
     #aQuadMapper.SetInput(Filter.GetOutput())
     geometryActor = vtk.vtkActor()
     geometryActor.SetMapper(aQuadMapper)
     #geometryActor.AddPosition(2, 0, 2)
     #geometryActor.GetProperty().SetDiffuseColor(0, 0, 1) # blue
     geometryActor.GetProperty().SetDiffuseColor(1, 0, 0)  # red
     self.rend.AddActor(geometryActor)
コード例 #30
0
ファイル: plotting.py プロジェクト: serafim-78/VKR
    def AddMesh(
            self,
            mesh,
            color=None,
            style=None,
            scalars=None,
            rng=None,
            stitle=None,
            showedges=True,
            psize=5.0,
            opacity=1,
            linethick=None,
            flipscalars=False,
            lighting=False,
            ncolors=256,
            interpolatebeforemap=False,
            colormap=None,
            **kwargs):
        """
        Adds a vtk unstructured, structured, or polymesh to the plotting object

        Parameters
        ----------
        mesh : vtk unstructured, structured, or polymesh
            A vtk unstructured, structured, or polymesh to plot.

        color : string or 3 item list, optional, defaults to white
            Either a string, rgb list, or hex color string.  For example:
                color='white'
                color='w'
                color=[1, 1, 1]
                color='#FFFFFF'

            Color will be overridden when scalars are input.

        style : string, optional
            Visualization style of the vtk mesh.  One for the following:
                style='surface'
                style='wireframe'
                style='points'

            Defaults to 'surface'

        scalars : numpy array, optional
            Scalars used to "color" the mesh.  Accepts an array equal to the
            number of cells or the number of points in the mesh.  Array should
            be sized as a single vector.

        rng : 2 item list, optional
            Range of mapper for scalars.  Defaults to minimum and maximum of
            scalars array.  Example: [-1, 2]

        stitle : string, optional
            Scalar title.  By default there is no scalar legend bar.  Setting
            this creates the legend bar and adds a title to it.  To create a
            bar with no title, use an empty string (i.e. '').

        showedges : bool, optional
            Shows the edges of a mesh.  Does not apply to a wireframe
            representation.

        psize : float, optional
            Point size.  Applicable when style='points'.  Default 5.0

        opacity : float, optional
            Opacity of mesh.  Should be between 0 and 1.  Default 1.0

        linethick : float, optional
            Thickness of lines.  Only valid for wireframe and surface
            representations.  Default None.

        flipscalars : bool, optional
            Flip direction of colormap.

        lighting : bool, optional
            Enable or disable view direction lighting.  Default False.

        ncolors : int, optional
            Number of colors to use when displaying scalars.  Default 256.

        interpolatebeforemap : bool, default False
            Enabling makes for a smoother scalar display.  Default False

        colormap : str, optional
           Colormap string.  See available matplotlib colormaps.  Only applicable for
           when displaying scalars.  Defaults None (rainbow).  Requires matplotlib.

        Returns
        -------
        actor: vtk.vtkActor
            VTK actor of the mesh.
        """
        # set main values
        self.mesh = mesh
        self.mapper = vtk.vtkDataSetMapper()
        self.mapper.SetInputData(self.mesh)
        actor, prop = self.AddActor(self.mapper)

        # Scalar formatting ===================================================
        if scalars is not None:
            # convert to numpy array
            if not isinstance(scalars, np.ndarray):
                scalars = np.asarray(scalars)

            # ravel if not 1 dimentional
            if scalars.ndim != 1:
                scalars = scalars.ravel()

            # Scalar interpolation approach
            if scalars.size == mesh.GetNumberOfPoints():
                self.mesh.AddPointScalars(scalars, '', True)
                self.mapper.SetScalarModeToUsePointData()
                self.mapper.GetLookupTable().SetNumberOfTableValues(ncolors)
                if interpolatebeforemap:
                    self.mapper.InterpolateScalarsBeforeMappingOn()
            elif scalars.size == mesh.GetNumberOfCells():
                self.mesh.AddCellScalars(scalars, '')
                self.mapper.SetScalarModeToUseCellData()
            else:
                raise Exception('Number of scalars (%d) ' % scalars.size +
                                'must match either the number of points ' +
                                '(%d) ' % mesh.GetNumberOfPoints() +
                                'or the number of cells ' +
                                '(%d) ' % mesh.GetNumberOfCells())

            # Set scalar range
            if not rng:
                rng = [np.nanmin(scalars), np.nanmax(scalars)]
            elif isinstance(rng, float) or isinstance(rng, int):
                rng = [-rng, rng]

            if np.any(rng):
                self.mapper.SetScalarRange(rng[0], rng[1])

            # Flip if requested
            table = self.mapper.GetLookupTable()
            if colormap is not None:
                try:
                    from matplotlib.cm import get_cmap
                except ImportError:
                    raise Exception('colormap requires matplotlib')
                cmap = get_cmap(colormap)
                ctable = cmap(np.linspace(0, 1, ncolors))*255
                ctable = ctable.astype(np.uint8)
                if flipscalars:
                    ctable = np.ascontiguousarray(ctable[::-1])
                table.SetTable(VN.numpy_to_vtk(ctable))

            else:  # no colormap specified
                if flipscalars:
                    self.mapper.GetLookupTable().SetHueRange(0.0, 0.66667)
                else:
                    self.mapper.GetLookupTable().SetHueRange(0.66667, 0.0)

        else:
            self.mapper.SetScalarModeToUseFieldData()

        # select view style
        if not style:
            style = 'surface'
        style = style.lower()
        if style == 'wireframe':
            prop.SetRepresentationToWireframe()
        elif style == 'points':
            prop.SetRepresentationToPoints()
        elif style == 'surface':
            prop.SetRepresentationToSurface()
        else:
            raise Exception('Invalid style.  Must be one of the following:\n' +
                            '\t"surface"\n' +
                            '\t"wireframe"\n' +
                            '\t"points"\n')

        prop.SetPointSize(psize)

        # edge display style
        if showedges:
            prop.EdgeVisibilityOn()
        prop.SetColor(ParseColor(color))
        prop.SetOpacity(opacity)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if linethick:
            prop.SetLineWidth(linethick)

        # Add scalar bar if available
        if stitle is not None:
            self.AddScalarBar(stitle)

        return actor
コード例 #31
0
ファイル: plotting.py プロジェクト: serafim-78/VKR
    def AddPoints(self, points, color=None, psize=5, scalars=None,
                  rng=None, name='', opacity=1, stitle='', flipscalars=False,
                  colormap=None, ncolors=256):
        """ Adds a point actor or numpy points array to plotting object """

        # select color
        if color is None:
            color = [1, 1, 1]
        elif isinstance(color, str):
            color = vtkInterface.StringToRGB(color)

        # Convert to vtk points object if "points" is a numpy array
        if isinstance(points, np.ndarray):
            # check size of points
            if points.ndim != 2 or points.shape[1] != 3:
                try:
                    points = points.reshape((-1, 3))
                except:
                    raise Exception('Invalid point array shape'
                                    '%s' % str(points.shape))
            self.points = vtkInterface.MakeVTKPointsMesh(points)
        else:
            self.points = points

        # Create mapper and add lines
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(self.points)

        if np.any(scalars):
            self.points.AddPointScalars(scalars, name, True)
            mapper.SetScalarModeToUsePointData()
            mapper.GetLookupTable().SetNumberOfTableValues(ncolors)

            if not rng:
                rng = [np.min(scalars), np.max(scalars)]
            elif isinstance(rng, float):
                rng = [-rng, rng]

            if np.any(rng):
                mapper.SetScalarRange(rng[0], rng[1])

        # Flip if requested
        table = mapper.GetLookupTable()
        if colormap is not None:
            try:
                from matplotlib.cm import get_cmap
            except ImportError:
                raise Exception('colormap requires matplotlib')
            cmap = get_cmap(colormap)
            ctable = cmap(np.linspace(0, 1, ncolors))*255
            ctable = ctable.astype(np.uint8)
            if flipscalars:
                ctable = np.ascontiguousarray(ctable[::-1])
            table.SetTable(VN.numpy_to_vtk(ctable))

        else:  # no colormap specifide
            mapper.GetLookupTable().SetHueRange(0.66667, 0.0)


        # Create Actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetPointSize(psize)
        actor.GetProperty().SetColor(color)
        actor.GetProperty().LightingOff()
        actor.GetProperty().SetOpacity(opacity)

        self.renderer.AddActor(actor)

        # Add scalar bar
        if stitle:
            self.scalarBar = vtk.vtkScalarBarActor()
            self.scalarBar.SetLookupTable(mapper.GetLookupTable())

            self.scalarBar.GetTitleTextProperty().SetFontFamilyToCourier()
            self.scalarBar.GetTitleTextProperty().ItalicOff()
            self.scalarBar.GetTitleTextProperty().BoldOn()
            self.scalarBar.GetLabelTextProperty().SetFontFamilyToCourier()
            self.scalarBar.GetLabelTextProperty().ItalicOff()
            self.scalarBar.GetLabelTextProperty().BoldOn()

            self.scalarBar.SetTitle(stitle)
            self.scalarBar.SetNumberOfLabels(5)

            self.renderer.AddActor(self.scalarBar)
コード例 #32
0
ファイル: CapClip.py プロジェクト: JensMunkHansen/pystuff
def main():
    filePath = get_program_parameters()

    # Define colors
    colors = vtk.vtkNamedColors()
    backgroundColor = colors.GetColor3d("steel_blue")
    boundaryColor = colors.GetColor3d("Banana")
    clipColor = colors.GetColor3d("Tomato")
    restColor = colors.GetColor3d("Red")

    if filePath and os.path.isfile(filePath):
        polyData = ReadPolyData(filePath)
        if not polyData:
            polyData = GetSpherePD()
    else:
        polyData = GetSpherePD()

    plane = vtk.vtkPlane()
    plane.SetOrigin(polyData.GetCenter())
    plane.SetNormal(1.0, -1.0, -1.0)

    clipper = vtk.vtkClipPolyData()
    clipper.SetInputData(polyData)
    clipper.SetClipFunction(plane)
    clipper.SetValue(0)
    clipper.Update()

    polyData = clipper.GetOutput()

    clipMapper = vtk.vtkDataSetMapper()
    clipMapper.SetInputData(polyData)

    clipActor = vtk.vtkActor()
    clipActor.SetMapper(clipMapper)
    clipActor.GetProperty().SetDiffuseColor(clipColor)
    clipActor.GetProperty().SetInterpolationToFlat()
    clipActor.GetProperty().EdgeVisibilityOn()

    # Now extract feature edges
    boundaryEdges = vtk.vtkFeatureEdges()
    boundaryEdges.SetInputData(polyData)
    boundaryEdges.BoundaryEdgesOn()
    boundaryEdges.FeatureEdgesOff()
    boundaryEdges.NonManifoldEdgesOff()
    boundaryEdges.ManifoldEdgesOff()

    boundaryStrips = vtk.vtkStripper()
    boundaryStrips.SetInputConnection(boundaryEdges.GetOutputPort())
    boundaryStrips.Update()

    # Change the polylines into polygons
    boundaryPoly = vtk.vtkPolyData()
    boundaryPoly.SetPoints(boundaryStrips.GetOutput().GetPoints())
    boundaryPoly.SetPolys(boundaryStrips.GetOutput().GetLines())

    append = vtk.vtkAppendPolyData()
    append.AddInputData(boundaryPoly)
    append.AddInputData(polyData)
    cleanFilter = vtk.vtkCleanPolyData()
    cleanFilter.SetInputConnection(append.GetOutputPort())
    cleanFilter.Update()

    boundaryMapper = vtk.vtkPolyDataMapper()
    boundaryMapper.SetInputData(boundaryPoly)

    boundaryActor = vtk.vtkActor()
    boundaryActor.SetMapper(boundaryMapper)
    boundaryActor.GetProperty().SetDiffuseColor(boundaryColor)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(cleanFilter.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetDiffuseColor(restColor)
    actor.GetProperty().SetInterpolationToFlat()

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

    # set background color and size
    renderer.SetBackground(backgroundColor)
    renderWindow.SetSize(640, 480)

    # add our actor to the renderer
    #renderer.AddActor(clipActor)
    #renderer.AddActor(boundaryActor)
    renderer.AddActor(actor)

    # Generate an interesting view
    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.GetActiveCamera().Dolly(1.2)
    renderer.ResetCameraClippingRange()

    # Print number of open edges
    featureEdges = vtk.vtkFeatureEdges()
    featureEdges.FeatureEdgesOff()
    featureEdges.BoundaryEdgesOn()
    featureEdges.NonManifoldEdgesOn()

    featureEdges.Update()
    print("Number of open edges: % d" %
          (featureEdges.GetOutput().GetNumberOfCells()))

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName('./output.vtp')
    writer.SetInputConnection(cleanFilter.GetOutputPort())
    writer.Update()

    renderWindow.Render()
    renderWindow.SetWindowName('CapClip')
    renderWindow.Render()

    interactor.Start()
コード例 #33
0
    def Execute(self):

        if (self.Mesh == None):
            self.PrintError('Error: no Mesh.')

        if (self.Centerlines == None):
            self.PrintError('Error: no Centerlines')

        #Save the centerlines
        previousCenterlines = self.Centerlines

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInput(self.Centerlines)
        cleaner.Update()
        self.Centerlines = cleaner.GetOutput()

        if self.Tolerance == -1:
            self.Tolerance = 0.000001 * self.Mesh.GetLength()

        if self.RadiusArrayName != '':
            self.RadiusArray = self.Centerlines.GetPointData().GetArray(
                self.RadiusArrayName)
            if self.RadiusArray == None:
                self.PrintError('Error : could not find radius array')

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

        meshMapper = vtk.vtkDataSetMapper()
        meshMapper.SetInput(self.Mesh)
        meshMapper.ScalarVisibilityOff()
        self.MeshActor = vtk.vtkActor()
        self.MeshActor.SetMapper(meshMapper)
        self.MeshActor.GetProperty().SetOpacity(0.25)
        self.MeshActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.MeshActor)

        centerlinesMapper = vtk.vtkDataSetMapper()
        centerlinesMapper.SetInput(self.Centerlines)
        centerlinesMapper.ScalarVisibilityOff()
        self.CenterlinesActor = vtk.vtkActor()
        self.CenterlinesActor.SetMapper(centerlinesMapper)
        self.vmtkRenderer.Renderer.AddActor(self.CenterlinesActor)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1)
        glyphs.SetInput(self.Spheres)
        glyphs.SetSource(glyphSource.GetOutput())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInput(glyphs.GetOutput())
        glyphMapper.ScalarVisibilityOff()
        self.SpheresActor = vtk.vtkActor()
        self.SpheresActor.SetMapper(glyphMapper)
        self.SpheresActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        self.SpheresActor.GetProperty().SetOpacity(0.25)
        self.SpheresActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SpheresActor)

        self.InterpolatedGlyphs = vtk.vtkGlyph3D()
        interpolatedGlyphSource = vtk.vtkSphereSource()
        interpolatedGlyphSource.SetRadius(1)
        self.InterpolatedGlyphs.SetInput(self.Centerlines)
        self.InterpolatedGlyphs.SetSource(interpolatedGlyphSource.GetOutput())
        #scaling is off for now
        self.InterpolatedGlyphs.SetScaleModeToDataScalingOff()
        self.InterpolatedGlyphs.SetScaleFactor(0.)
        interpolatedGlyphMapper = vtk.vtkPolyDataMapper()
        interpolatedGlyphMapper.SetInput(self.InterpolatedGlyphs.GetOutput())
        interpolatedGlyphMapper.ScalarVisibilityOff()
        self.InterpolatedSpheresActor = vtk.vtkActor()
        self.InterpolatedSpheresActor.SetMapper(interpolatedGlyphMapper)
        self.InterpolatedSpheresActor.GetProperty().SetColor(0.0, 1.0, 0.0)
        self.InterpolatedSpheresActor.GetProperty().SetOpacity(0.25)
        self.InterpolatedSpheresActor.PickableOff()
        self.InterpolatedSpheresActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.InterpolatedSpheresActor)

        polyBallMapper = vtk.vtkPolyDataMapper()
        polyBallMapper.ScalarVisibilityOff()
        self.PolyBallActor = vtk.vtkActor()
        self.PolyBallActor.SetMapper(polyBallMapper)
        self.PolyBallActor.GetProperty().SetColor(0.0, 1.0, 0.0)
        self.PolyBallActor.GetProperty().SetOpacity(0.25)
        self.PolyBallActor.PickableOff()
        self.PolyBallActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.PolyBallActor)

        self.SphereWidget = vtk.vtkSphereWidget()
        self.SphereWidget.TranslationOff()
        self.SphereWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback)

        self.Clipper = vtk.vtkClipDataSet()
        self.Clipper.SetInput(self.Mesh)
        self.Clipper.SetInsideOut(self.InsideOut)
        self.Clipper.GenerateClippedOutputOn()

        #self.LineClipper = vtkvmtk.vtkvmtkClipDataSetLine()
        #self.LineClipper.SetInput(self.Mesh)
        #self.LineClipper.SetInsideOut(self.InsideOut)
        #self.LineClipper.GenerateClippedOutputOn()

        self.InitializeSpheres()

        self.PreviewMesh = self.Mesh

        self.Display()

        self.PolyBallActor.VisibilityOff()
        self.ClipMesh()

        if self.ClippedMesh == None:
            #return an empty mesh
            self.ClippedMesh = vtk.vtkUnstructuredGrid()
        elif self.IncludeSurfaceCells:
            #Create the surface cells
            self.PreviewMesh = self.CreateSurfaceCells(self.PreviewMesh)
            self.ClippedMesh = self.CreateSurfaceCells(self.ClippedMesh)

        self.Mesh = self.PreviewMesh

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()

        if self.Mesh.GetSource():
            self.Mesh.GetSource().UnRegisterAllOutputs()

        #Restore the centerlines
        self.Centerlines = previousCenterlines
コード例 #34
0
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Manually create a label map. Place a bunch of
# overlapping circles and then extract the
# resulting regions.
VTK_SHORT = 4
res = 500
image = vtk.vtkImageData()
image.SetDimensions(res,res,1)
image.AllocateScalars(VTK_SHORT,1)

imMapper = vtk.vtkDataSetMapper()
imMapper.SetInputData(image)
imMapper.ScalarVisibilityOn()
imMapper.SetScalarRange(0,5)

imActor = vtk.vtkActor()
imActor.SetMapper(imMapper)

# Fill the scalars with 0 and then set particular values.
# Here we'll create several regions / labels.
def GenIndex(i,j):
    return i + j*res

scalars = image.GetPointData().GetScalars()
scalars.Fill(0)

# Generate a circle of labels
コード例 #35
0
ファイル: sig_yy.py プロジェクト: e-b-py/2DFEP
import vtk

# Reader
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName("../out/sigyy.vtk")
reader.Update()
# Mapper
element_mapper = vtk.vtkDataSetMapper()
element_mapper.SetInput(reader.GetOutput())
# Find minimum and maximum stresses to get a proper lookup table
scalar_data = reader.GetOutput()
min_value = scalar_data.GetScalarRange()[0]
max_value = scalar_data.GetScalarRange()[1]
lookup_table = vtk.vtkLookupTable()
lookup_table.Build()
lookup_table.SetRange(scalar_data.GetScalarRange())
element_mapper.SetScalarRange(scalar_data.GetScalarRange())
element_mapper.SetLookupTable(lookup_table)
print element_mapper.GetLookupTable().GetRange()
# Actor
actor = vtk.vtkActor()
actor.SetMapper(element_mapper)
scalar_bar = vtk.vtkScalarBarActor()
scalar_bar.SetLookupTable(lookup_table)
scalar_bar.SetHeight(0.5)
scalar_bar.SetPosition(0.02, 0.25)
scalar_bar.SetPosition2(0.10, 0.75)
# Renderer
renderer = vtk.vtkRenderer()
renderer.SetBackground(0.0, 0.0, 0.0)
renderer.AddActor(actor)
コード例 #36
0
def main():
    colors = vtk.vtkNamedColors()

    file_name = get_program_parameters()

    # Read the polydata for the icon
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(file_name)

    icon_mapper = vtk.vtkDataSetMapper()
    icon_mapper.SetInputConnection(reader.GetOutputPort())

    icon_actor = vtk.vtkActor()
    icon_actor.SetMapper(icon_mapper)
    icon_actor.GetProperty().SetColor(colors.GetColor3d('Silver'))

    # Set up the renderer, window, and interactor
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(renderer)
    ren_win.SetSize(400, 400)
    ren_win.SetWindowName('OrientationMarkerWidget1')

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

    rgb = [0.0, 0.0, 0.0]
    colors.GetColorRGB('Wheat', rgb)
    # Set up the widget
    widget = vtk.vtkOrientationMarkerWidget()
    widget.SetOrientationMarker(icon_actor)
    widget.SetInteractor(iren)
    widget.SetViewport(0.0, 0.0, 0.2, 0.2)
    widget.SetOutlineColor(*rgb)
    widget.SetEnabled(1)
    widget.InteractiveOn()

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

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

    superquadric_actor = vtk.vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)
    superquadric_actor.GetProperty().SetInterpolationToFlat()
    superquadric_actor.GetProperty().SetDiffuseColor(
        colors.GetColor3d('Carrot'))
    superquadric_actor.GetProperty().SetSpecularColor(
        colors.GetColor3d('White'))
    superquadric_actor.GetProperty().SetDiffuse(0.6)
    superquadric_actor.GetProperty().SetSpecular(0.5)
    superquadric_actor.GetProperty().SetSpecularPower(5.0)

    renderer.AddActor(superquadric_actor)
    renderer.ResetCamera()

    ren_win.Render()

    iren.Initialize()

    iren.Start()
コード例 #37
0
ファイル: UGrid.py プロジェクト: yoavfreund/MouseBrainSlicer
def main():
    colors = vtk.vtkNamedColors()

    x = [[0, 0, 0], [1, 0, 0], [2, 0, 0], [0, 1, 0], [1, 1, 0], [2, 1, 0],
         [0, 0, 1], [1, 0, 1], [2, 0, 1], [0, 1, 1], [1, 1, 1], [2, 1, 1],
         [0, 1, 2], [1, 1, 2], [2, 1, 2], [0, 1, 3], [1, 1, 3], [2, 1, 3],
         [0, 1, 4], [1, 1, 4], [2, 1, 4], [0, 1, 5], [1, 1, 5], [2, 1, 5],
         [0, 1, 6], [1, 1, 6], [2, 1, 6]]
    pts = [[0, 1, 4, 3, 6, 7, 10, 9], [1, 2, 5, 4, 7, 8, 11, 10],
           [6, 10, 9, 12, 0, 0, 0, 0], [8, 11, 10, 14, 0, 0, 0, 0],
           [16, 17, 14, 13, 12, 15, 0, 0], [18, 15, 19, 16, 20, 17, 0, 0],
           [22, 23, 20, 19, 0, 0, 0, 0], [21, 22, 18, 0, 0, 0, 0, 0],
           [22, 19, 18, 0, 0, 0, 0, 0], [23, 26, 0, 0, 0, 0, 0, 0],
           [21, 24, 0, 0, 0, 0, 0, 0], [25, 0, 0, 0, 0, 0, 0, 0]]
    print(len(x), len(pts))

    renderer = vtk.vtkRenderer()

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

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

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

    ugrid.SetPoints(points)

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

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

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

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

    renWin.SetSize(640, 480)

    # Interact with the data.
    renWin.Render()

    iren.Start()
コード例 #38
0
ファイル: SelectionLoop.py プロジェクト: ciwei100000/vtk7
selectionPoints.InsertPoint(0, 0.07325, 0.8417, 0.5612)
selectionPoints.InsertPoint(1, 0.07244, 0.6568, 0.7450)
selectionPoints.InsertPoint(2, 0.1727, 0.4597, 0.8850)
selectionPoints.InsertPoint(3, 0.3265, 0.6054, 0.7309)
selectionPoints.InsertPoint(4, 0.5722, 0.5848, 0.5927)
selectionPoints.InsertPoint(5, 0.4305, 0.8138, 0.4189)
loop = vtk.vtkImplicitSelectionLoop()
loop.SetLoop(selectionPoints)
extract = vtk.vtkExtractGeometry()
extract.SetInputConnection(sphere.GetOutputPort())
extract.SetImplicitFunction(loop)
connect = vtk.vtkConnectivityFilter()
connect.SetInputConnection(extract.GetOutputPort())
connect.SetExtractionModeToClosestPointRegion()
connect.SetClosestPoint(selectionPoints.GetPoint(0))
clipMapper = vtk.vtkDataSetMapper()
clipMapper.SetInputConnection(connect.GetOutputPort())
backProp = vtk.vtkProperty()
backProp.SetDiffuseColor(GetRGBColor('tomato'))
clipActor = vtk.vtkActor()
clipActor.SetMapper(clipMapper)
clipActor.GetProperty().SetColor(GetRGBColor('peacock'))
clipActor.SetBackfaceProperty(backProp)

# Create graphics stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
コード例 #39
0
    def add_geometry(self):
        """
        #(N,)  for stress, x-disp
        #(N,3) for warp vectors/glyphs
        grid_result = vtk.vtkFloatArray()

        point_data = self.grid.GetPointData()
        cell_data = self.grid.GetCellData()

        self.grid.GetCellData().SetScalars(grid_result)
        self.grid.GetPointData().SetScalars(grid_result)


        self.grid_mapper   <-input-> self.grid
        vtkDataSetMapper() <-input-> vtkUnstructuredGrid()

        self.grid_mapper   <--map--> self.geom_actor <-add-> self.rend
        vtkDataSetMapper() <--map--> vtkActor()      <-add-> vtkRenderer()
        """
        if self.is_groups:
            # solid_bending: eids 1-182
            self._setup_element_mask()
            #eids = np.arange(172)
            #eids = arange(172)
            #self.update_element_mask(eids)
        else:
            self.grid_selected = self.grid
        #print('grid_selected =', self.grid_selected)

        self.grid_mapper = vtk.vtkDataSetMapper()
        self.grid_mapper.SetInputData(self.grid_selected)

        self._make_contour_filter()

        #if 0:
        #self.warp_filter = vtk.vtkWarpVector()
        #self.warp_filter.SetScaleFactor(50.0)
        #self.warp_filter.SetInput(self.grid_mapper.GetUnstructuredGridOutput())

        #self.geom_filter = vtk.vtkGeometryFilter()
        #self.geom_filter.SetInput(self.warp_filter.GetUnstructuredGridOutput())

        #self.geom_mapper = vtk.vtkPolyDataMapper()
        #self.geom_actor.setMapper(self.geom_mapper)

        #if 0:
        #from vtk.numpy_interface import algorithms
        #arrow = vtk.vtkArrowSource()
        #arrow.PickableOff()

        #self.glyph_transform = vtk.vtkTransform()
        #self.glyph_transform_filter = vtk.vtkTransformPolyDataFilter()
        #self.glyph_transform_filter.SetInputConnection(arrow.GetOutputPort())
        #self.glyph_transform_filter.SetTransform(self.glyph_transform)

        #self.glyph = vtk.vtkGlyph3D()
        #self.glyph.setInput(xxx)
        #self.glyph.SetSource(self.glyph_transform_filter.GetOutput())

        #self.glyph.SetVectorModeToUseVector()
        #self.glyph.SetColorModeToColorByVector()
        #self.glyph.SetScaleModeToScaleByVector()
        #self.glyph.SetScaleFactor(1.0)

        #self.append_filter = vtk.vtkAppendFilter()
        #self.append_filter.AddInputConnection(self.grid.GetOutput())

        #self.warpVector = vtk.vtkWarpVector()
        #self.warpVector.SetInput(self.grid_mapper.GetUnstructuredGridOutput())
        #grid_mapper.SetInput(Filter.GetOutput())

        self.geom_actor = vtk.vtkLODActor()
        self.geom_actor.DragableOff()
        self.geom_actor.SetMapper(self.grid_mapper)
        #geometryActor.AddPosition(2, 0, 2)
        #geometryActor.GetProperty().SetDiffuseColor(0, 0, 1) # blue
        #self.geom_actor.GetProperty().SetDiffuseColor(1, 0, 0)  # red

        #if 0:
        #id_filter = vtk.vtkIdFilter()

        #ids = np.array([1, 2, 3], dtype='int32')
        #id_array = numpy_to_vtk(
        #num_array=ids,
        #deep=True,
        #array_type=vtk.VTK_INT,
        #)

        #id_filter.SetCellIds(id_array.GetOutputPort())
        #id_filter.CellIdsOff()
        #self.grid_mapper.SetInputConnection(id_filter.GetOutputPort())
        self.rend.AddActor(self.geom_actor)
        self.build_glyph()
コード例 #40
0
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor('leftBkg', [0.6, 0.5, 0.4, 1.0])
    colors.SetColor('centreBkg', [0.3, 0.1, 0.4, 1.0])
    colors.SetColor('rightBkg', [0.4, 0.5, 0.6, 1.0])

    sphereSource = vtk.vtkSphereSource()
    sphereSource.Update()

    print("There are %s input points" % sphereSource.GetOutput().GetNumberOfPoints())
    print("There are %s input cells" % sphereSource.GetOutput().GetNumberOfCells())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    # Specify that we want to extract cells 10 through 19
    i = 10
    while i < 20:
        ids.InsertNextValue(i)
        i += 1

    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selectionNode.SetSelectionList(ids)

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    extractSelection = vtk.vtkExtractSelection()
    extractSelection.SetInputConnection(0, sphereSource.GetOutputPort())
    extractSelection.SetInputData(1, selection)
    extractSelection.Update()

    # In selection
    selected = vtk.vtkUnstructuredGrid()
    selected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points in the selection" % selected.GetNumberOfPoints())
    print("There are %s cells in the selection" % selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)  # invert the selection
    extractSelection.Update()

    notSelected = vtk.vtkUnstructuredGrid()
    notSelected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points NOT in the selection" % notSelected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" % notSelected.GetNumberOfCells())

    backfaces = vtk.vtkProperty()
    backfaces.SetColor(colors.GetColor3d('Red'))

    inputMapper = vtk.vtkDataSetMapper()
    inputMapper.SetInputConnection(sphereSource.GetOutputPort())
    inputActor = vtk.vtkActor()
    inputActor.SetMapper(inputMapper)
    inputActor.SetBackfaceProperty(backfaces)

    selectedMapper = vtk.vtkDataSetMapper()
    selectedMapper.SetInputData(selected)

    selectedActor = vtk.vtkActor()
    selectedActor.SetMapper(selectedMapper)
    selectedActor.SetBackfaceProperty(backfaces)

    notSelectedMapper = vtk.vtkDataSetMapper()
    notSelectedMapper.SetInputData(notSelected)

    notSelectedActor = vtk.vtkActor()
    notSelectedActor.SetMapper(notSelectedMapper)
    notSelectedActor.SetBackfaceProperty(backfaces)

    # There will be one render window
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    leftViewport = [0.0, 0.0, 0.5, 1.0]
    centerViewport = [0.33, 0.0, .66, 1.0]
    rightViewport = [0.66, 0.0, 1.0, 1.0]

    # Create a camera for all renderers
    camera = vtk.vtkCamera()

    # Setup the renderers
    leftRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(leftRenderer)
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(colors.GetColor3d('leftBkg'))
    leftRenderer.SetActiveCamera(camera)

    centerRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(centerRenderer)
    centerRenderer.SetViewport(centerViewport)
    centerRenderer.SetBackground(colors.GetColor3d('centreBkg'))
    centerRenderer.SetActiveCamera(camera)

    rightRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(rightRenderer)
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(colors.GetColor3d('rightBkg'))
    rightRenderer.SetActiveCamera(camera)

    leftRenderer.AddActor(inputActor)
    centerRenderer.AddActor(selectedActor)
    rightRenderer.AddActor(notSelectedActor)

    leftRenderer.ResetCamera()

    renderWindow.Render()
    interactor.Start()
コード例 #41
0
    def View(self,filename):

        '''
        Nastavení interaktoru pro pohyb s objektem. Třída vtkInteractorStyleTrackballCamera(), nám umožní nastavit na levé tlačítko
        myši funkce pohybu s vizualizovaným objektem a na pravé možnost zoomu
        '''
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

        '''
        Nastavení readeru pro čtení vtk souboru v podobě nestrukturované mřížky
        '''
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()

        '''
        Jako filtr je použit objekt třídy vtkDataSetSurfaceFilter(), který nám z dat vyextrahuje vnější povrch
        '''
        surface.SetInput(reader.GetOutput())
        surface.Update()

        '''
        Dále použijeme třídu vtkClipPolyData(), ta nám při pohybu roviny způsobí, že za ní bude nechávat pouze obrysy spojení
        buněk bez vyplnění povrchu, tím snadno poznáme kde jsme s rovinou po objektu již přejeli a kde ne
        '''
        clipper = vtk.vtkClipPolyData()
        clipper.SetInput(surface.GetOutput())
        clipper.SetClipFunction(plane)
        clipper.GenerateClippedOutputOn()

        clipMapper = vtk.vtkPolyDataMapper()
        clipMapper.SetInput(clipper.GetOutput())

        clipActor = vtk.vtkActor()
        clipActor.SetMapper(clipMapper)

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(surface.GetOutput())



        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOn()
        # nastavuje šířku linek ohraničující buňky
        actor.GetProperty().SetLineWidth(0.1)
        actor.GetProperty().SetRepresentationToWireframe()
        self.ren.AddActor(clipActor)
        self.ren.AddActor(actor)

        self.iren.Initialize()
        self.iren.Start()
        '''
        Třídu vtkWindowToImageFilter použijeme pro uložení vizualizace z prohlížecího režimu ve formátu tif
        '''
        try:
            w2i = vtk.vtkWindowToImageFilter()
            writer = vtk.vtkTIFFWriter()
            w2i.SetInput(self.renWin)
            w2i.Update()
            writer.SetInputConnection(w2i.GetOutputPort())
            writer.SetFileName("image.tif")
            self.renWin.Render()
            writer.Write()
            self.renWin.Render()
            self.renWin.Finalize()
        except(AttributeError):
            print()
コード例 #42
0
def plot_materials(problem_name):
    # The source file
    #file_name = "uGridEx.vtk"
    #file_name = "2d1g_heter.mesh.vtk"
    file_name = problem_name + ".mesh.vtk"

    # Read the source file.
    reader = vtkUnstructuredGridReader()
    reader.SetFileName(file_name)

    reader.ReadAllScalarsOn()
    #reader.SetScalarsName("UserIndex")
    reader.SetScalarsName("material")
    #reader.SetScalarsName("Phi_0")

    reader.Update()  # Needed because of GetScalarRange
    output = reader.GetOutput()
    scalar_range = output.GetScalarRange()

    # Create the mapper that corresponds the objects of the vtk file
    # into graphics elements
    mapper = vtkDataSetMapper()
    if VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(output)
    else:
        mapper.SetInputData(output)
    mapper.SetScalarRange(scalar_range)
    # Create the Actor
    actor = vtkActor()
    actor.SetMapper(mapper)

    # Create the Renderer
    renderer = vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(1, 1, 1)  # Set background to white

    #--------------------------------------------------------------------------
    # Adding colors for categories --------------------------------------------
    cl = []
    cl.append([float(cc) / 255.0
               for cc in [27, 158, 119]])  # Colorbrewer Dark2
    cl.append([float(cc) / 255.0 for cc in [217, 95, 2]])
    cl.append([float(cc) / 255.0 for cc in [117, 112, 179]])
    cl.append([float(cc) / 255.0 for cc in [231, 41, 138]])
    cl.append([float(cc) / 255.0 for cc in [102, 166, 30]])
    cl.append([float(cc) / 255.0 for cc in [230, 171, 2]])
    cl.append([float(cc) / 255.0 for cc in [166, 118, 29]])
    cl.append([float(cc) / 255.0 for cc in [102, 102, 102]])

    lut = vtkLookupTable()
    lutNum = len(cl)
    lut.SetNumberOfTableValues(lutNum)
    lut.Build()
    for ii, cc in enumerate(cl):
        lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
    numCats = int(scalar_range[1])
    lut.SetRange(0, numCats - 1)

    mapper.SetLookupTable(lut)
    mapper.SelectColorArray("Category_ids")
    # Until here --------------------------------------------------------------
    #--------------------------------------------------------------------------

    # Create the RendererWindow
    renderer_window = vtkRenderWindow()
    renderer_window.AddRenderer(renderer)

    # Create the RendererWindowInteractor
    interactor = vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderer_window)

    # Display the vtk_file
    interactor.Initialize()
    interactor.Start()
コード例 #43
0
def plot_fluxes(problem_name):
    # The source file
    #file_name = "uGridEx.vtk"
    #file_name = "2d1g_heter.mesh.vtk"
    file_name = problem_name + ".vtk"

    # Read the source file.
    reader = vtkUnstructuredGridReader()
    reader.SetFileName(file_name)

    reader.ReadAllScalarsOn()
    #reader.SetScalarsName("UserIndex")
    #reader.SetScalarsName("material")
    reader.SetScalarsName("Phi_0")

    reader.Update()  # Needed because of GetScalarRange
    output = reader.GetOutput()
    scalar_range = output.GetScalarRange()

    # Create the mapper that corresponds the objects of the vtk file
    # into graphics elements
    mapper = vtkDataSetMapper()
    if VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(output)
    else:
        mapper.SetInputData(output)
    mapper.SetScalarRange(scalar_range)
    # Create the Actor
    actor = vtkActor()
    actor.SetMapper(mapper)

    # Create the Renderer
    renderer = vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(1, 1, 1)  # Set background to white

    #--------------------------------------------------------------------------
    # Adding colors for scalars -----------------------------------------------

    lut = vtkLookupTable()
    refLut = vtkLookupTable()
    lut.Build()
    refLut.Build()
    for i in range(256):
        lut.SetTableValue(i, refLut.GetTableValue(255 - i))
    mapper.SetLookupTable(lut)
    #mapper.SelectColorArray("Category_ids")
    # Until here --------------------------------------------------------------
    #--------------------------------------------------------------------------

    # Create the RendererWindow
    renderer_window = vtkRenderWindow()
    renderer_window.AddRenderer(renderer)

    # Create the RendererWindowInteractor
    interactor = vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderer_window)

    # Display the vtk_file
    interactor.Initialize()
    interactor.Start()
コード例 #44
0
ファイル: fieldToRGrid.py プロジェクト: wuhongjian139/VTK
    fd2ad.SetVectorComponent(1, "vectors", 1)
    fd2ad.SetVectorComponent(2, "vectors", 2)
    fd2ad.SetScalarComponent(0, "scalars", 0)
    fd2ad.Update()

    # create pipeline
    #
    plane = vtk.vtkRectilinearGridGeometryFilter()
    plane.SetInputData(fd2ad.GetRectilinearGridOutput())
    plane.SetExtent(0, 100, 0, 100, 15, 15)

    warper = vtk.vtkWarpVector()
    warper.SetInputConnection(plane.GetOutputPort())
    warper.SetScaleFactor(0.05)

    planeMapper = vtk.vtkDataSetMapper()
    planeMapper.SetInputConnection(warper.GetOutputPort())
    planeMapper.SetScalarRange(0.197813, 0.710419)

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

    cutPlane = vtk.vtkPlane()
    cutPlane.SetOrigin(fd2ad.GetOutput().GetCenter())
    cutPlane.SetNormal(1, 0, 0)

    planeCut = vtk.vtkCutter()
    planeCut.SetInputData(fd2ad.GetRectilinearGridOutput())
    planeCut.SetCutFunction(cutPlane)

    cutMapper = vtk.vtkDataSetMapper()
コード例 #45
0
def main():
    """
    ^y
    |
    8----9----10---11
    |  / |  / |  / |
    4----5----6----7
    |  / |  / |  / |
    0----1----2----3 --> x
    """
    ugrid = vtk.vtkUnstructuredGrid()
    xyzs = [
        [0., 0., 0.],
        [1., 0., 0.],
        [2., 0., 0.],
        [3., 0., 0.],
        [0., 1., 0.],
        [1., 1., 0.],
        [2., 1., 0.],
        [3., 1., 0.],
        [0., 2., 0.],
        [1., 2., 0.],
        [2., 2., 0.],
        [3., 2., 0.],
    ]
    # we make the lower triangle first, then the upper one to finish off the quad
    # go accross each row, left to right
    tris = [
        [0, 1, 5],
        [0, 5, 4],
        [1, 2, 6],
        [1, 6, 5],
        [2, 3, 7],
        [2, 7, 6],
        [4, 5, 9],
        [4, 9, 8],
        [5, 6, 10],
        [5, 10, 9],
        [6, 7, 11],
        [6, 11, 10],
    ]
    ids_to_show = [
        0,
        1,  #2, 3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12
    ]
    ids_to_show_updated = [
        0,
        1,  #2, 3,
        #4, 5,
        6,
        7,
        8,
        9,
        10,
        11,
        12
    ]

    nnodes = len(xyzs)
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(nnodes)

    nid = 0
    for i, xyz in enumerate(xyzs):
        points.InsertPoint(nid, *xyz)
        nid += 1

    for tri in tris:
        elem = vtk.vtkTriangle()
        (n1, n2, n3) = tri
        elem.GetPointIds().SetId(0, n1)
        elem.GetPointIds().SetId(1, n2)
        elem.GetPointIds().SetId(2, n3)
        ugrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

    ugrid.SetPoints(points)

    grid_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        grid_mapper.SetInputConnection(ugrid.GetProducerPort())
    else:
        grid_mapper.SetInputData(ugrid)
    input_actor = vtk.vtkActor()
    input_actor.SetMapper(grid_mapper)

    render_window = vtk.vtkRenderWindow()
    camera = vtk.vtkCamera()
    interactor = vtk.vtkRenderWindowInteractor()

    interactor.SetRenderWindow(render_window)

    print("There are %s input points" % ugrid.GetNumberOfPoints())
    print("There are %s input cells" % ugrid.GetNumberOfCells())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)
    ids.Allocate(len(ids_to_show))

    for id_to_show in ids_to_show:
        ids.InsertNextValue(id_to_show)

    selection_node = vtk.vtkSelectionNode()
    selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(ids)

    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    if vtk.VTK_MAJOR_VERSION <= 5:
        extract_selection.SetInput(0, ugrid)
        extract_selection.SetInput(1, selection)
    else:
        extract_selection.SetInputData(0, ugrid)
        extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    # In selection
    grid_selected = vtk.vtkUnstructuredGrid()
    grid_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points in the selection" %
          grid_selected.GetNumberOfPoints())
    print("There are %s cells in the selection" %
          grid_selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    # invert the selection
    selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
    extract_selection.Update()

    not_selected = vtk.vtkUnstructuredGrid()
    not_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points NOT in the selection" %
          not_selected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" %
          not_selected.GetNumberOfCells())

    selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        selected_mapper.SetInputConnection(grid_selected.GetProducerPort())
    else:
        selected_mapper.SetInputData(grid_selected)

    selected_actor = vtk.vtkActor()
    selected_actor.SetMapper(selected_mapper)

    not_selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        not_selected_mapper.SetInputConnection(not_selected.GetProducerPort())
    else:
        not_selected_mapper.SetInputData(not_selected)

    not_selected_actor = vtk.vtkActor()
    not_selected_actor.SetMapper(not_selected_mapper)

    # There will be one render window
    render_window = vtk.vtkRenderWindow()
    render_window.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    left_viewport = [0.0, 0.0, 0.5, 1.0]
    right_viewport = [0.5, 0.0, 1.0, 1.0]

    # Create a camera for all renderers
    camera = vtk.vtkCamera()

    # Setup the renderers
    left_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(left_renderer)
    left_renderer.SetViewport(left_viewport)
    left_renderer.SetBackground(.6, .5, .4)
    left_renderer.SetActiveCamera(camera)

    right_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(right_renderer)
    right_renderer.SetViewport(right_viewport)
    right_renderer.SetBackground(.3, .1, .4)
    right_renderer.SetActiveCamera(camera)
    right_renderer.AddActor(selected_actor)

    left_renderer.AddActor(input_actor)
    right_renderer.AddActor(not_selected_actor)

    right_renderer.ResetCamera()

    interactor.Start()
    #-----------------
    ids.Reset()
    ids.Allocate(len(ids_to_show_updated))
    for id_to_show in ids_to_show_updated:
        ids.InsertNextValue(id_to_show)
    ids.Modified()
    grid_selected.Modified()

    #ids.Update()
    ids.Modified()
    #selection_node.Update()
    selection_node.Modified()
    #selection.Update()
    selection.Modified()
    extract_selection.Update()
    extract_selection.Modified()
    #grid_selected.Update()
    grid_selected.Modified()
    selected_mapper.Update()
    selected_mapper.Modified()
    #selected_actor.Update()
    selected_actor.Modified()

    right_renderer.Modified()
    #right_renderer.Update()

    interactor.Modified()
    #interactor.Update()
    #-----------------
    render_window.Render()

    render_window.Modified()
コード例 #46
0
def execute():
    output = src.GetStructuredGridOutput()
    output.SetPoints(points)
    output.GetPointData().SetScalars(scalars)
    output.SetExtent(0, r.shape[0] - 1, 0, r.shape[1] - 1, 0, 0)
    output.SetWholeExtent(0, r.shape[0] - 1, 0, r.shape[1] - 1, 0, 0)


src.SetExecuteMethod(execute)

#dataset = vtk.vtkStructuredGrid()
#dataset.ShallowCopy(src.GetStructuredGridOutput())
dataset = src.GetStructuredGridOutput()
#print dataset

map = vtk.vtkDataSetMapper()
map.SetInput(dataset)

act = vtk.vtkActor()
act.SetMapper(map)

ren = vtk.vtkRenderer()
ren.AddActor(act)

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

iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renwin)
iren.Start()
コード例 #47
0
    def _add_alt_geometry(self, grid, name, color=None, line_width=None,
                          opacity=None, representation=None):
        """
        NOTE: color, line_width, opacity are ignored if name already exists
        """
        is_pickable = self.gui.geometry_properties[name].is_pickable
        quad_mapper = vtk.vtkDataSetMapper()
        if name in self.gui.geometry_actors:
            alt_geometry_actor = self.gui.geometry_actors[name]
            alt_geometry_actor.GetMapper().SetInputData(grid)
        else:
            quad_mapper.SetInputData(grid)
            alt_geometry_actor = vtk.vtkActor()
            if not is_pickable:
                alt_geometry_actor.PickableOff()
                alt_geometry_actor.DragableOff()

            alt_geometry_actor.SetMapper(quad_mapper)
            self.gui.geometry_actors[name] = alt_geometry_actor

        #geometryActor.AddPosition(2, 0, 2)
        if name in self.gui.geometry_properties:
            geom = self.gui.geometry_properties[name]
        else:
            geom = AltGeometry(self, name, color=color, line_width=line_width,
                               opacity=opacity, representation=representation)
            self.gui.geometry_properties[name] = geom

        color = geom.color_float
        opacity = geom.opacity
        point_size = geom.point_size
        representation = geom.representation
        line_width = geom.line_width
        #print('color_2014[%s] = %s' % (name, str(color)))
        assert isinstance(color[0], float), color
        assert color[0] <= 1.0, color

        prop = alt_geometry_actor.GetProperty()
        #prop.SetInterpolationToFlat()    # 0
        #prop.SetInterpolationToGouraud() # 1
        #prop.SetInterpolationToPhong()   # 2
        prop.SetDiffuseColor(color)
        prop.SetOpacity(opacity)
        #prop.Update()

        #print('prop.GetInterpolation()', prop.GetInterpolation()) # 1

        if representation == 'point':
            prop.SetRepresentationToPoints()
            prop.SetPointSize(point_size)
        elif representation in ['surface', 'toggle']:
            prop.SetRepresentationToSurface()
            prop.SetLineWidth(line_width)
        elif representation == 'wire':
            prop.SetRepresentationToWireframe()
            prop.SetLineWidth(line_width)

        self.rend.AddActor(alt_geometry_actor)
        vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

        if geom.is_visible:
            alt_geometry_actor.VisibilityOn()
        else:
            alt_geometry_actor.VisibilityOff()

        #print('current_actors = ', self.geometry_actors.keys())
        alt_geometry_actor.Modified()
コード例 #48
0
    if n[0] < 0.0:
        actor.RotateWXYZ(180, 0, 1, 0)
        actor.RotateWXYZ(180, (n[0] - 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)
    else:
        actor.RotateWXYZ(180, (n[0] + 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)


# Pick the actor
picker.Pick(70, 120, 0, ren)
#print picker
p = picker.GetPickPosition()
n = picker.GetPickNormal()

coneActor1 = vtk.vtkActor()
coneActor1.PickableOff()
coneMapper1 = vtk.vtkDataSetMapper()
coneMapper1.SetInputConnection(coneSource.GetOutputPort())
coneActor1.SetMapper(coneMapper1)
coneActor1.GetProperty().SetColor(1, 0, 0)
coneActor1.SetPosition(p)
PointCone(coneActor1, n)
ren.AddViewProp(coneActor1)

# Pick the image
picker.Pick(170, 220, 0, ren)
#print picker
p = picker.GetPickPosition()
n = picker.GetPickNormal()

coneActor2 = vtk.vtkActor()
coneActor2.PickableOff()
コード例 #49
0
def main():
    file_name, color_scheme = get_program_parameters()

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

    colors = vtk.vtkNamedColors()

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

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

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

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

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

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

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

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

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

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

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

    iren.Start()
コード例 #50
0
ファイル: fieldToUGrid.py プロジェクト: hefuhuang/VTKpersonel
    fd2ad.SetVectorComponent(2, "displacement9", 2)
    fd2ad.SetScalarComponent(0, "thickness9", 0)
    fd2ad.Update()

    # Now start visualizing
    warp = vtk.vtkWarpVector()
    warp.SetInputData(fd2ad.GetUnstructuredGridOutput())

    # extract mold from mesh using connectivity
    connect = vtk.vtkConnectivityFilter()
    connect.SetInputConnection(warp.GetOutputPort())
    connect.SetExtractionModeToSpecifiedRegions()
    connect.AddSpecifiedRegion(0)
    connect.AddSpecifiedRegion(1)

    moldMapper = vtk.vtkDataSetMapper()
    moldMapper.SetInputConnection(connect.GetOutputPort())
    moldMapper.ScalarVisibilityOff()

    moldActor = vtk.vtkActor()
    moldActor.SetMapper(moldMapper)
    moldActor.GetProperty().SetColor(.2, .2, .2)
    moldActor.GetProperty().SetRepresentationToWireframe()

    # extract parison from mesh using connectivity
    connect2 = vtk.vtkConnectivityFilter()
    connect2.SetInputConnection(warp.GetOutputPort())
    connect2.SetExtractionModeToSpecifiedRegions()
    connect2.AddSpecifiedRegion(2)

    parison = vtk.vtkGeometryFilter()
コード例 #51
0
ファイル: pickCells.py プロジェクト: ciwei100000/vtk7
voxelPoints.InsertPoint(6, 0, 1, 1)
voxelPoints.InsertPoint(7, 1, 1, 1)
aVoxel = vtk.vtkVoxel()
aVoxel.GetPointIds().SetId(0, 0)
aVoxel.GetPointIds().SetId(1, 1)
aVoxel.GetPointIds().SetId(2, 2)
aVoxel.GetPointIds().SetId(3, 3)
aVoxel.GetPointIds().SetId(4, 4)
aVoxel.GetPointIds().SetId(5, 5)
aVoxel.GetPointIds().SetId(6, 6)
aVoxel.GetPointIds().SetId(7, 7)
aVoxelGrid = vtk.vtkUnstructuredGrid()
aVoxelGrid.Allocate(1, 1)
aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds())
aVoxelGrid.SetPoints(voxelPoints)
aVoxelMapper = vtk.vtkDataSetMapper()
aVoxelMapper.SetInputData(aVoxelGrid)
aVoxelActor = vtk.vtkActor()
aVoxelActor.SetMapper(aVoxelMapper)
aVoxelActor.GetProperty().BackfaceCullingOn()
# Hexahedron
hexahedronPoints = vtk.vtkPoints()
hexahedronPoints.SetNumberOfPoints(8)
hexahedronPoints.InsertPoint(0, 0, 0, 0)
hexahedronPoints.InsertPoint(1, 1, 0, 0)
hexahedronPoints.InsertPoint(2, 1, 1, 0)
hexahedronPoints.InsertPoint(3, 0, 1, 0)
hexahedronPoints.InsertPoint(4, 0, 0, 1)
hexahedronPoints.InsertPoint(5, 1, 0, 1)
hexahedronPoints.InsertPoint(6, 1, 1, 1)
hexahedronPoints.InsertPoint(7, 0, 1, 1)
コード例 #52
0
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Manually create a sample image.
VTK_SHORT = 4
rowLen = 10
image = vtk.vtkImageData()
image.SetDimensions(rowLen, 7, 1)
image.AllocateScalars(VTK_SHORT, 1)

imMapper = vtk.vtkDataSetMapper()
imMapper.SetInputData(image)

imActor = vtk.vtkActor()
imActor.SetMapper(imMapper)


# Fill the scalars with 0 and then set particular values.
# Here we'll create several regions / labels.
def GenIndex(i, j):
    return i + j * rowLen


scalars = image.GetPointData().GetScalars()
scalars.Fill(0)
# Region 1
scalars.SetTuple1(GenIndex(0, 2), 1)
scalars.SetTuple1(GenIndex(1, 2), 1)
scalars.SetTuple1(GenIndex(2, 2), 1)
コード例 #53
0
    def testCells(self):

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

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

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

        # create a scene with one of each cell type

        # Voxel

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

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

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

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

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

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

        # Hexahedron

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

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

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

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

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

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

        # Tetra

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

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

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

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

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

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

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

        # Wedge

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

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

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

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

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

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

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

        # Pyramid

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

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

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

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

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

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

        # Pixel

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

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

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

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

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

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

        # Quad

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

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

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

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

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

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

        # Triangle

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

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

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

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

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

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

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

        # Polygon

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

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

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

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

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

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

        # Triangle Strip

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

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

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

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

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

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

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

        # Line

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

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

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

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

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

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

        # Poly line

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

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

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

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

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

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

        # Vertex

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

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

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

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

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

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

        # Poly Vertex

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

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

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

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

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

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

        # Pentagonal prism

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

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

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

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

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

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

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

        # Hexagonal prism

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

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

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

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

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

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

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

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

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

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

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

        if hasattr(vtk, 'vtkRIBLight'):
            aRIBLight = vtk.vtkRIBLight()

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

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

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

        # write to the temp directory if possible, otherwise use .
        dir = tempfile.gettempdir()

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

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

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

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

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

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

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

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


        DeleteCopies()


        # render and interact with data

        renWin.Render()

        img_file = "cells.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
コード例 #54
0
contour.SetValue(0, 1)
contour.SetMergePoints(mergePoints)
contour.SetInterpolateAttributes(interpolateAttr)
contour.SetComputeNormals(computeNormals)
contour.Update()

contMapper = vtk.vtkPolyDataMapper()
contMapper.SetInputConnection(contour.GetOutputPort())
contMapper.ScalarVisibilityOff()

contActor = vtk.vtkActor()
contActor.SetMapper(contMapper)
contActor.GetProperty().SetColor(.8, .4, .4)

# Display the cells
cellMapper = vtk.vtkDataSetMapper()
cellMapper.SetInputData(ugrid)
cellMapper.ScalarVisibilityOff()

cellActor = vtk.vtkActor()
cellActor.SetMapper(cellMapper)
cellActor.GetProperty().SetColor(.8, .4, .4)
cellActor.GetProperty().SetRepresentationToWireframe()

# Define graphics objects
renWin = vtk.vtkRenderWindow()

ren1 = vtk.vtkRenderer()
ren1.SetBackground(1, 1, 1)
ren1.GetActiveCamera().SetFocalPoint(0, 0, 0)
ren1.GetActiveCamera().SetPosition(0, 0.5, 1)
コード例 #55
0
    def testVolumePicker(self):
        # volume render a medical data set

        # renderer and interactor
        ren = vtk.vtkRenderer()

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

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

        # read the volume
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetImageRange(1, 93)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
        v16.SetDataSpacing(3.2, 3.2, 1.5)

        #---------------------------------------------------------
        # set up the volume rendering

        rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction()

        volumeMapper = vtk.vtkVolumeRayCastMapper()
        volumeMapper.SetInputConnection(v16.GetOutputPort())
        volumeMapper.SetVolumeRayCastFunction(rayCastFunction)

        volumeColor = vtk.vtkColorTransferFunction()
        volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0)
        volumeColor.AddRGBPoint(180, 0.3, 0.1, 0.2)
        volumeColor.AddRGBPoint(1000, 1.0, 0.7, 0.6)
        volumeColor.AddRGBPoint(2000, 1.0, 1.0, 0.9)

        volumeScalarOpacity = vtk.vtkPiecewiseFunction()
        volumeScalarOpacity.AddPoint(0, 0.0)
        volumeScalarOpacity.AddPoint(180, 0.0)
        volumeScalarOpacity.AddPoint(1000, 0.2)
        volumeScalarOpacity.AddPoint(2000, 0.8)

        volumeGradientOpacity = vtk.vtkPiecewiseFunction()
        volumeGradientOpacity.AddPoint(0, 0.0)
        volumeGradientOpacity.AddPoint(90, 0.5)
        volumeGradientOpacity.AddPoint(100, 1.0)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(volumeColor)
        volumeProperty.SetScalarOpacity(volumeScalarOpacity)
        volumeProperty.SetGradientOpacity(volumeGradientOpacity)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()
        volumeProperty.SetAmbient(0.6)
        volumeProperty.SetDiffuse(0.6)
        volumeProperty.SetSpecular(0.1)

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

        #---------------------------------------------------------
        # Do the surface rendering
        boneExtractor = vtk.vtkMarchingCubes()
        boneExtractor.SetInputConnection(v16.GetOutputPort())
        boneExtractor.SetValue(0, 1150)

        boneNormals = vtk.vtkPolyDataNormals()
        boneNormals.SetInputConnection(boneExtractor.GetOutputPort())
        boneNormals.SetFeatureAngle(60.0)

        boneStripper = vtk.vtkStripper()
        boneStripper.SetInputConnection(boneNormals.GetOutputPort())

        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(v16.GetOutputPort())
        mapToColors.SetLookupTable(table)

        imageActor = vtk.vtkImageActor()
        imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort())
        imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92)

        #---------------------------------------------------------
        # make a transform and some clipping planes

        transform = vtk.vtkTransform()
        transform.RotateWXYZ(-20, 0.0, -0.7, 0.7)

        volume.SetUserTransform(transform)
        bone.SetUserTransform(transform)
        imageActor.SetUserTransform(transform)

        c = volume.GetCenter()

        volumeClip = vtk.vtkPlane()
        volumeClip.SetNormal(0, 1, 0)
        volumeClip.SetOrigin(c)

        boneClip = vtk.vtkPlane()
        boneClip.SetNormal(0, 0, 1)
        boneClip.SetOrigin(c)

        volumeMapper.AddClippingPlane(volumeClip)
        boneMapper.AddClippingPlane(boneClip)

        #---------------------------------------------------------
        ren.AddViewProp(volume)
        ren.AddViewProp(bone)
        ren.AddViewProp(imageActor)

        camera = ren.GetActiveCamera()
        camera.SetFocalPoint(c)
        camera.SetPosition(c[0] + 500, c[1] - 100, c[2] - 100)
        camera.SetViewUp(0, 0, -1)

        ren.ResetCameraClippingRange()

        renWin.Render()

        #---------------------------------------------------------
        # the cone should point along the Z axis
        coneSource = vtk.vtkConeSource()
        coneSource.CappingOn()
        coneSource.SetHeight(12)
        coneSource.SetRadius(5)
        coneSource.SetResolution(31)
        coneSource.SetCenter(6, 0, 0)
        coneSource.SetDirection(-1, 0, 0)

        #---------------------------------------------------------
        picker = vtk.vtkVolumePicker()
        picker.SetTolerance(1.0e-6)
        picker.SetVolumeOpacityIsovalue(0.01)
        # This should usually be left alone, but is used here to increase coverage
        picker.UseVolumeGradientOpacityOn()

        # A function to point an actor along a vector
        def PointCone(actor, n):
            if n[0] < 0.0:
                actor.RotateWXYZ(180, 0, 1, 0)
                actor.RotateWXYZ(180, (n[0] - 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)
            else:
                actor.RotateWXYZ(180, (n[0] + 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)

        # Pick the actor
        picker.Pick(192, 103, 0, ren)
        #print picker
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor1 = vtk.vtkActor()
        coneActor1.PickableOff()
        coneMapper1 = vtk.vtkDataSetMapper()
        coneMapper1.SetInputConnection(coneSource.GetOutputPort())
        coneActor1.SetMapper(coneMapper1)
        coneActor1.GetProperty().SetColor(1, 0, 0)
        coneActor1.SetPosition(p)
        PointCone(coneActor1, n)
        ren.AddViewProp(coneActor1)

        # Pick the volume
        picker.Pick(90, 180, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor2 = vtk.vtkActor()
        coneActor2.PickableOff()
        coneMapper2 = vtk.vtkDataSetMapper()
        coneMapper2.SetInputConnection(coneSource.GetOutputPort())
        coneActor2.SetMapper(coneMapper2)
        coneActor2.GetProperty().SetColor(1, 0, 0)
        coneActor2.SetPosition(p)
        PointCone(coneActor2, n)
        ren.AddViewProp(coneActor2)

        # Pick the image
        picker.Pick(200, 200, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor3 = vtk.vtkActor()
        coneActor3.PickableOff()
        coneMapper3 = vtk.vtkDataSetMapper()
        coneMapper3.SetInputConnection(coneSource.GetOutputPort())
        coneActor3.SetMapper(coneMapper3)
        coneActor3.GetProperty().SetColor(1, 0, 0)
        coneActor3.SetPosition(p)
        PointCone(coneActor3, n)
        ren.AddViewProp(coneActor3)

        # Pick a clipping plane
        picker.PickClippingPlanesOn()
        picker.Pick(145, 160, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor4 = vtk.vtkActor()
        coneActor4.PickableOff()
        coneMapper4 = vtk.vtkDataSetMapper()
        coneMapper4.SetInputConnection(coneSource.GetOutputPort())
        coneActor4.SetMapper(coneMapper4)
        coneActor4.GetProperty().SetColor(1, 0, 0)
        coneActor4.SetPosition(p)
        PointCone(coneActor4, n)
        ren.AddViewProp(coneActor4)

        ren.ResetCameraClippingRange()

        # render and interact with data

        renWin.Render()

        img_file = "VolumePicker.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
コード例 #56
0
ファイル: genmesh.py プロジェクト: kliegeois/progs
    ugrid.InsertNextCell(quad.GetCellType(), ids)

# save the grid
writer = vtk.vtkXMLUnstructuredGridWriter()
#compressor = vtk.vtkZLibDataCompressor()
#writer.SetCompressor(compressor)
writer.SetCompressor(None)
writer.SetDataModeToAscii()
#writer.SetDataModeToBinary()
writer.SetInputData(ugrid)
writer.SetFileName('mesh.vtu')
writer.Write()

# display (DEBUG)

mapper = vtk.vtkDataSetMapper()
mapper.SetInputData(ugrid)
actor = vtk.vtkActor()
actor.SetMapper(mapper)

gridMapper = vtk.vtkDataSetMapper()
gridMapper.SetResolveCoincidentTopologyToPolygonOffset()
gridMapper.ScalarVisibilityOff()
gridMapper.SetInputData(ugrid)
gridActor = vtk.vtkActor()
gridActor.GetProperty().SetRepresentationToWireframe()
gridActor.GetProperty().SetColor(0.1 * 2, 0.2 * 2, 0.4 * 2)
gridActor.GetProperty().SetAmbient(1.0)
gridActor.GetProperty().SetDiffuse(0.0)
gridActor.GetProperty().SetSpecular(0.0)
gridActor.SetMapper(gridMapper)
コード例 #57
0
ファイル: vmtkmeshviewer.py プロジェクト: Clemson-MSE/vmtk
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

        if self.Actor:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)
            if self.ArrayName:
                self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                array = self.Mesh.GetPointData().GetScalars()

                if self.ScalarRange[1] > self.ScalarRange[0]:
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))

                if self.ColorMap == 'grayscale':
                    lut = mapper.GetLookupTable()
                    lut.SetNumberOfTableValues(self.NumberOfColors)
                    lut.SetValueRange(0.0, 1.0)
                    lut.SetSaturationRange(0.0, 0.0)
                    lut.Build()
                    mapper.SetLookupTable(lut)

                if self.ColorMap == 'rainbow':
                    lut = mapper.GetLookupTable()
                    lut.SetHueRange(0.666667, 0.0)
                    lut.SetSaturationRange(0.75, 0.75)
                    lut.SetValueRange(1.0, 1.0)
                    lut.SetAlphaRange(1.0, 1.0)
                    lut.SetNumberOfColors(self.NumberOfColors)
                    lut.Build()
                    mapper.SetLookupTable(lut)

                if self.ColorMap == 'blackbody':
                    lut = mapper.GetLookupTable()
                    lut.SetNumberOfTableValues(self.NumberOfColors)
                    colorTransferFunction = vtk.vtkColorTransferFunction()
                    colorTransferFunction.SetColorSpaceToRGB()
                    colorTransferFunction.AddRGBPoint(0, 0.0, 0.0, 0.0)
                    colorTransferFunction.AddRGBPoint(0.4, 0.901961, 0.0, 0.0)
                    colorTransferFunction.AddRGBPoint(0.8, 0.901961, 0.901961,
                                                      0.0)
                    colorTransferFunction.AddRGBPoint(1.0, 1.0, 1.0, 1.0)
                    for ii, ss in enumerate([
                            float(xx) / float(self.NumberOfColors)
                            for xx in range(self.NumberOfColors)
                    ]):
                        cc = colorTransferFunction.GetColor(ss)
                        lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
                    lut.Build()
                    mapper.SetLookupTable(lut)

                if self.ColorMap == 'cooltowarm':
                    lut = mapper.GetLookupTable()
                    lut.SetNumberOfTableValues(self.NumberOfColors)
                    colorTransferFunction = vtk.vtkColorTransferFunction()
                    colorTransferFunction.SetColorSpaceToDiverging()
                    colorTransferFunction.AddRGBPoint(0, 0.231373, 0.298039,
                                                      0.752941)
                    colorTransferFunction.AddRGBPoint(0.5, 0.865003, 0.865003,
                                                      0.865003)
                    colorTransferFunction.AddRGBPoint(1.0, 0.705882, 0.0156863,
                                                      0.14902)
                    for ii, ss in enumerate([
                            float(xx) / float(self.NumberOfColors)
                            for xx in range(self.NumberOfColors)
                    ]):
                        cc = colorTransferFunction.GetColor(ss)
                        lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
                    lut.Build()
                    mapper.SetLookupTable(lut)
            else:
                mapper.ScalarVisibilityOff()
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if self.FlatInterpolation:
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.vmtkRenderer.AddKeyBinding('w',
                                            'Change surface representation.',
                                            self.RepresentationCallback)

        if self.Legend and self.Actor:
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(
                self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
            ##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        if self.Display:
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
コード例 #58
0
    def add_bounding_box(self, color="grey", corner_factor=0.5, line_width=None,
                         opacity=1.0, render_lines_as_tubes=False,
                         lighting=None, reset_camera=None, outline=True,
                         culling='front', loc=None):
        """Add an unlabeled and unticked box at the boundaries of plot.

        Useful for when wanting to plot outer grids while still retaining all
        edges of the boundary.

        Parameters
        ----------
        corner_factor : float, optional
            If ``all_edges``, this is the factor along each axis to
            draw the default box. Dafuault is 0.5 to show the full
            box.

        corner_factor : float, optional
            This is the factor along each axis to draw the default
            box. Dafuault is 0.5 to show the full box.

        line_width : float, optional
            Thickness of lines.

        opacity : float, optional
            Opacity of mesh.  Should be between 0 and 1.  Default 1.0

        outline : bool
            Default is ``True``. when False, a box with faces is shown with
            the specified culling

        culling : str, optional
            Does not render faces that are culled. Options are ``'front'`` or
            ``'back'``. Default is ``'front'`` for bounding box.

        loc : int, tuple, or list
            Index of the renderer to add the actor to.  For example,
            ``loc=2`` or ``loc=(1, 1)``.  If None, selects the last
            active Renderer.

        """
        if lighting is None:
            lighting = rcParams['lighting']

        self.remove_bounding_box()
        if color is None:
            color = rcParams['outline_color']
        rgb_color = parse_color(color)
        if outline:
            self._bounding_box = vtk.vtkOutlineCornerSource()
            self._bounding_box.SetCornerFactor(corner_factor)
        else:
            self._bounding_box = vtk.vtkCubeSource()
        self._bounding_box.SetBounds(self.bounds)
        self._bounding_box.Update()
        self._box_object = wrap(self._bounding_box.GetOutput())
        name = 'BoundingBox({})'.format(hex(id(self._box_object)))

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(self._box_object)
        self.bounding_box_actor, prop = self.add_actor(mapper,
                                                       reset_camera=reset_camera,
                                                       name=name, culling=culling,
                                                       pickable=False)

        prop.SetColor(rgb_color)
        prop.SetOpacity(opacity)
        if render_lines_as_tubes:
            prop.SetRenderLinesAsTubes(render_lines_as_tubes)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        prop.SetRepresentationToSurface()

        return self.bounding_box_actor
コード例 #59
0
clipOutlineActor = vtk.vtkActor()
clipOutlineActor.SetMapper(clipperOutlineMapper)
clipOutlineActor.GetProperty().SetColor(0, 1, 0)
clipOutlineActor.SetPosition(0.001, 0.001, 0.001)
# create an outline
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(sphere.GetOutputPort())
outline.GenerateFacesOn()
outlineClip = vtk.vtkClipClosedSurface()
outlineClip.SetClippingPlanes(planes)
outlineClip.SetInputConnection(outline.GetOutputPort())
outlineClip.GenerateFacesOff()
outlineClip.GenerateOutlineOn()
outlineClip.SetScalarModeToColors()
outlineClip.SetClipColor(0, 1, 0)
outlineMapper = vtk.vtkDataSetMapper()
outlineMapper.SetInputConnection(outlineClip.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.SetPosition(0.001, 0.001, 0.001)
# Create graphics stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetMultiSamples(0)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(clipActor)
コード例 #60
-1
    def __init__(self,delta,wing):

        self.arrowColor = vtk.vtkColorTransferFunction()

        self.update_look_up_table()

        self.print_counter=0
        self.ren = vtk.vtkRenderer()

        self.geo_reader = vtk.vtkUnstructuredGridReader()
        self.geo_reader.SetFileName(wing)


        self.vec_reader = vtk.vtkStructuredPointsReader()
        self.vec_reader.SetFileName(delta)

        """ This is for drawing the wing,"""
        geo_Mapper=vtk.vtkDataSetMapper()
        geo_Mapper.SetInputConnection(self.geo_reader.GetOutputPort())

        geo_actor = vtk.vtkActor()
        geo_actor.SetMapper(geo_Mapper)

        self.ren.AddActor(geo_actor)

        """End of adding the wing """


        self.ren.AddActor(self.create_stream_line(25,150,0,0.5))


        #Add renderer to renderwindow and render
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(1920, 1080)

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

        iren.AddObserver('RightButtonPressEvent', self.capture_image, 1.0)

        # Scalar Bar actor
        scalar_bar = vtk.vtkScalarBarActor()
        scalar_bar.SetOrientationToHorizontal()
        scalar_bar.SetLookupTable(self.arrowColor)
        scalar_bar.SetTitle("Color map")
        scalar_bar.SetLabelFormat("%5.2f")
        scalar_bar.SetMaximumHeightInPixels(300)
        scalar_bar.SetMaximumWidthInPixels(60)

        # Scalar Bar Widget
        scalar_bar_widget = vtk.vtkScalarBarWidget()
        scalar_bar_widget.SetInteractor(iren)
        scalar_bar_widget.SetScalarBarActor(scalar_bar)
        scalar_bar_widget.On()

        self.ren.SetBackground(0,0,0)
        self.renWin.Render()
        iren.Start()