def __init__(self): pypes.pypeScript.__init__(self) self.Surface = None self.ResolutionArrayName = 'ResolutionArray' self.RBFType = 'biharmonic' self.Spheres = vtk.vtkPolyData() self.SphereIds = vtk.vtkIdList() self.vmtkRenderer = None self.OwnRenderer = 0 self.DisplayArray = False self.SurfaceMapper = None self.CurrentSphereId = -1 self.SphereWidget = None self.Opacity = 1. self.SpheresActor = None self.ScalarBarActor = None self.InteractionMode = 0 self.ExamineSurface = None self.ExamineSpheres = vtk.vtkPolyData() self.ExamineSpheresActor = None self.ExamineText = None self.SetScriptName('vtksurfaceresolution') self.SetInputMembers([ ['Surface','i','vtkPolyData',1,'','the input surface','vmtksurfacereader'], ['ResolutionArrayName','resolutionarray','str',1,'','array storing the desired edge length'], ['RBFType','rbftype','str',1,'["thinplatespline","biharmonic","triharmonic"]','the type of RBF interpolation'], ['Opacity','opacity','float',1,'(0.0,1.0)','object opacities in the scene'], ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer'] ]) self.SetOutputMembers([ ['Surface','o','vtkPolyData',1,'','','vmtksurfacewriter'] ])
def __init__(self): pypes.pypeScript.__init__(self) self.Surface = None self.DeformedSurface = None self.SourcePoints = vtk.vtkPoints() self.TargetPoints = vtk.vtkPoints() self.DisplacementNorms = vtk.vtkDoubleArray() self.Displacements = vtk.vtkDoubleArray() self.Displacements.SetNumberOfComponents(3) self.SourceSpheres = vtk.vtkPolyData() self.TargetSpheres = vtk.vtkPolyData() self.SourceSpheres.SetPoints(self.SourcePoints) self.TargetSpheres.SetPoints(self.TargetPoints) self.SourceSpheres.GetPointData().SetScalars(self.DisplacementNorms) self.SourceSpheres.GetPointData().SetVectors(self.Displacements) self.vmtkRenderer = None self.OwnRenderer = 0 self.DisplayDeformed = False self.SurfaceMapper = None self.Opacity = 1.0 self.SourceSpheresActor = None self.TargetSpheresActor = None self.SetScriptName("vmtkthinplatesplinedeformation") self.SetInputMembers( [ ["Surface", "i", "vtkPolyData", 1, "", "the input surface", "vmtksurfacereader"], ["Opacity", "opacity", "float", 1, "(0.0,1.0)", "object opacities in the scene"], ["vmtkRenderer", "renderer", "vmtkRenderer", 1, "", "external renderer"], ] ) self.SetOutputMembers([["DeformedSurface", "o", "vtkPolyData", 1, "", "", "vmtksurfacewriter"]])
def CreateCoords_versore(o, r): """ Ritorna una lista di attori contenenti i il sistema di coordinate: o = origine r = versore""" points = [] Lines=[] Polygon = vtk.vtkPolyData() ac=[] points = vtk.vtkPoints() points.SetNumberOfPoints(4) points.SetPoint(0, self.midPoint) points.SetPoint(1, [self.FrenetBinormalArray[0]+self.midPoint[0], self.FrenetBinormalArray[1]+self.midPoint[1], self.FrenetBinormalArray[2]+self.midPoint[2]]) points.SetPoint(2, [self.FrenetNormalArray[0]+self.midPoint[0], self.FrenetNormalArray[1]+self.midPoint[1], self.FrenetNormalArray[2]+self.midPoint[2]]) points.SetPoint(3, [self.FrenetTangentArray[0]+self.midPoint[0], self.FrenetTangentArray[1]+self.midPoint[1], self.FrenetTangentArray[2]+self.midPoint[2]]) points.SetPoint(0, o) points.SetPoint(1, [o[0]+r[0], o[1] , o[2]]) points.SetPoint(2, [o[0] , o[1]+r[1] , o[2]]) points.SetPoint(3, [o[0] , o[1] , o[2]+r[2]]) polyLine0 = vtk.vtkPolyLine() polyLine0.GetPointIds().SetNumberOfIds(2) polyLine0.GetPointIds().SetId(0,0) polyLine0.GetPointIds().SetId(1,1) polyLine1 = vtk.vtkPolyLine() polyLine1.GetPointIds().SetNumberOfIds(2) polyLine1.GetPointIds().SetId(0,0) polyLine1.GetPointIds().SetId(1,2) polyLine2 = vtk.vtkPolyLine() polyLine2.GetPointIds().SetNumberOfIds(2) polyLine2.GetPointIds().SetId(0,0) polyLine2.GetPointIds().SetId(1,3) cells0 = vtk.vtkCellArray() cells0.InsertNextCell(polyLine0) cells0.InsertNextCell(polyLine1) cells0.InsertNextCell(polyLine2) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(cells0) ac=[] ac.append(CreateSphere(points.GetPoint(0), 0.05, [1, 1, 1])) ac.append(CreateSphere(points.GetPoint(1), 0.1, [1, 0, 0])) ac.append(CreateSphere(points.GetPoint(2), 0.1, [0, 1, 0])) ac.append(CreateSphere(points.GetPoint(3), 0.1, [0, 0, 1])) ac.append(CreateActor(polyData)) return ac
def RequestInformation(): import vtk ############# Get I/O ############# # Get the two inputs, and the output polyDataA = self.GetInputDataObject(0, 0) polyDataB = self.GetInputDataObject(0, 1) pdo = self.GetPolyDataOutput() # If only one input is given, raise an exception if polyDataA is None or polyDataB is None: raise Exception("\nThis filter takes 2 inputs:\n" "Point Cloud Data files: pc_HHMMSSDD_NNN.vtk\n" "Pose Data file: pc_HHMMSSDD_poses.vtk\n" "Note that ParaView groups all the Point Cloud Data files in one\n") # Initialize vtkPolyData for point cloud data (PC) and pose data (P) polyData_PC = vtk.vtkPolyData() polyData_P = vtk.vtkPolyData() if polyDataA.GetFieldData().GetArray("timestamp") is not None and \ polyDataB.GetPointData().GetArray("timestamp") is not None: pointCloudPortIndex = 0 else: if polyDataB.GetFieldData().GetArray("timestamp") is not None and \ polyDataA.GetPointData().GetArray("timestamp") is not None: pointCloudPortIndex = 1 else: # If none of the configuration above is met, raise an exception raise Exception("\nOne or both of the inputs don't have a \"timestamp\" Point/Field Data\n" "Is this data coming from the \"Paraview Tango Recorder\" app ?\n" "The input that ends with \'_poses.vtk\" must have a \"timestamp\" PointData\n" "The input that ends with \'*.vtk\" must have a \"timestamp\" FieldData\n") def setOutputTimesteps ( algorithm , timesteps ): "helper routine to set timestep information" executive = algorithm . GetExecutive () outInfo = executive . GetOutputInformation (0) outInfo.Remove ( executive.TIME_STEPS () ) for timestep in timesteps : outInfo . Append ( executive . TIME_STEPS () , timestep ) outInfo . Remove ( executive . TIME_RANGE () ) outInfo . Append ( executive . TIME_RANGE () , timesteps [0]) outInfo . Append ( executive . TIME_RANGE () , timesteps [ -1]) def getInputTimesteps( algorithm, portindex): "helper routine to set timestep information" executive = algorithm . GetExecutive () inInfo = executive . GetInputInformation (0, portindex) return inInfo.Get(executive.TIME_STEPS()) myrange = getInputTimesteps(self, pointCloudPortIndex) setOutputTimesteps(self, myrange)
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) vertexFilter = vtk.vtkVertexGlyphFilter() vertexFilter.SetInputConnection(pointsPolydata.GetProducerPort()) vertexFilter.Update() polydata = vtk.vtkPolyData() polydata.ShallowCopy(vertexFilter.GetOutput()) # Setup colors colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTupleValue((255, 0, 0)) colors.InsertNextTupleValue((0, 255, 0)) colors.InsertNextTupleValue((0, 0, 255)) polydata.GetPointData().SetScalars(colors) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(polydata.GetProducerPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetPointSize(5) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def ReadPDB(file_name): pdb = vtk.vtkPDBReader() pdb.SetFileName(file_name) pdb.SetHBScale(1.0) pdb.SetBScale(1.0) pdb.Update() sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) sphere.SetRadius(1) glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(pdb.GetOutputPort()) glyph.SetSourceConnection(sphere.GetOutputPort()) glyph.SetOrient(1) glyph.SetColorMode(1) glyph.SetScaleMode(2) glyph.SetScaleFactor(.25) glyph.Update() tube = vtk.vtkTubeFilter() tube.SetInputConnection(pdb.GetOutputPort()) tube.SetNumberOfSides(6) tube.CappingOff() tube.SetRadius(0.2) tube.SetVaryRadius(0) tube.SetRadiusFactor(10) tube.Update() tubeMesh = vtk.vtkPolyData() tubeMesh.ShallowCopy(tube.GetOutput()) N = tubeMesh.GetNumberOfPoints() rgb_colors = tubeMesh.GetPointData().GetArray("rgb_colors") if rgb_colors is not None: if rgb_colors.GetNumberOfComponents() == 3: for i in range(N): rgb_colors.SetTupleValue(i, (127, 127, 127)) appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputConnection(glyph.GetOutputPort()) try: appendFilter.AddInputData(tubeMesh) except: appendFilter.AddInput(tubeMesh) appendFilter.Update() polyData = vtk.vtkPolyData() polyData.ShallowCopy(appendFilter.GetOutput()) return polyData
def CreatePlanarCrossSectionPolyDataFromFile(file): with open(file, 'r') as f: read_data = f.read() tokens = string.split(read_data) offset = 2 planeAppender = vtk.vtkAppendPolyData() outlineAppender = vtk.vtkAppendPolyData() # Iterate over separate pieces in the file while True: if (offset >= len(tokens)): break pointsInPiece = int(tokens[offset]) newPoints = vtk.vtkPoints() newPoints.SetNumberOfPoints(pointsInPiece) for ptId in xrange(pointsInPiece): x = float(tokens[ptId*3 + 0 + offset + 1]) y = float(tokens[ptId*3 + 1 + offset + 1]) z = float(tokens[ptId*3 + 2 + offset + 1]) newPoints.SetPoint(ptId, x, y, z) offset = offset + 3*pointsInPiece + 1 polygon = vtk.vtkPolyData() polygon.SetPoints(newPoints) polygon.Allocate(pointsInPiece) polygon.InsertNextCell(vtk.VTK_POLYGON, pointsInPiece, range(pointsInPiece)) triFilter = vtk.vtkTriangleFilter() triFilter.SetInputData(polygon) planeAppender.AddInputConnection(triFilter.GetOutputPort()) outline = vtk.vtkPolyData() outline.SetPoints(newPoints) outline.Allocate(pointsInPiece) outline.InsertNextCell(vtk.VTK_POLY_LINE, pointsInPiece, range(pointsInPiece)) outlineAppender.AddInputData(outline) planeAppender.Update() outlineAppender.Update() return (planeAppender.GetOutput(), outlineAppender.GetOutput())
def add_lines(self, points, lines, colors=(255, 0, 0)): line_collection = vtk.vtkCellArray() line_collection.Allocate(len(lines)) for line in lines: line_collection.InsertNextCell(len(line), line) poly_data = vtk.vtkPolyData() poly_data.SetPoints(self._convert_points_array(points)) poly_data.SetLines(line_collection) actor = self._actor_from_poly_data(poly_data) colors = np.asarray(colors) if colors.size == 3: # only one color given colors = colors.ravel() actor.GetProperty().SetColor(colors[0], colors[1], colors[2]) elif colors.shape[0] == len(lines): # array of line colors colors = np.ascontiguousarray( colors.astype(np.uint8, subok=True, copy=False)) colors_array = numpy_to_vtk(colors) colors_array.SetName("Colors") # to avoid the colors array going out of scope setattr(colors_array, '_np_color_array', colors) poly_data.GetCellData().SetScalars(colors_array) else: # array of vertex colors self._add_color_to_actor(actor, colors) return self._add_mesh_actor(actor)
def make_cylinderActor (r, x0, x1, rgb, opacity): points = vtk.vtkPoints() lines = vtk.vtkCellArray() lines.InsertNextCell(2) # point 0 points.InsertNextPoint(x0[0], x0[1], x0[2]) lines.InsertCellPoint(0) # point 1 points.InsertNextPoint(x1[0], x1[1], x1[2]) lines.InsertCellPoint(1) cData = vtk.vtkPolyData() cData.SetPoints(points) cData.SetLines(lines) c = vtk.vtkTubeFilter() c.SetNumberOfSides(8) c.SetInput(cData) c.SetRadius(r) cMapper = vtk.vtkPolyDataMapper() cMapper.SetInput(c.GetOutput()) cActor = vtk.vtkActor() cActor.SetMapper(cMapper) cActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2]) cActor.GetProperty().SetOpacity(opacity) return cActor
def UpdateCube(self,object, event): polyData = vtk.vtkPolyData() object.GetPolyData(polyData) polyData.ComputeBounds() self.CubeSource.SetBounds(polyData.GetBounds()) self.CubeSource.Modified() self.CubeActor.VisibilityOn()
def make_sphereActor (x, r, rgb, opacity): points = vtk.vtkPoints() points.InsertNextPoint(x[0], x[1], x[2]) diameter = vtk.vtkDoubleArray() diameter.SetNumberOfComponents(1) diameter.InsertNextTuple1(2.0*r) pData = vtk.vtkPolyData() pData.SetPoints(points) pData.GetPointData().SetScalars(diameter) pSource = vtk.vtkSphereSource() pSource.SetPhiResolution(16) pSource.SetThetaResolution(16) pGlyph = vtk.vtkGlyph3D() pGlyph.SetSource(pSource.GetOutput()) pGlyph.SetInput(pData) pGlyph.ScalingOn() pGlyph.SetScaleModeToScaleByScalar() pMapper = vtk.vtkPolyDataMapper() pMapper.ScalarVisibilityOff() pMapper.SetInput(pGlyph.GetOutput()) pActor = vtk.vtkActor() pActor.SetMapper(pMapper) pActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2]) pActor.GetProperty().SetOpacity(opacity) return pActor
def testTwoTrianglesCoplanar(): "Two triangles" # create set of points points = vtk.vtkPoints() points.SetNumberOfPoints(4) points.SetPoint(0, [0., 0., 0.]) points.SetPoint(1, [1., 0., 0.]) points.SetPoint(2, [0., 1., 0.]) points.SetPoint(3, [1., 1., 0.]) # create vtkPolyData object pdata = vtk.vtkPolyData() pdata.SetPoints(points) pdata.Allocate(2, 1) ptIds = vtk.vtkIdList() ptIds.SetNumberOfIds(3) ptIds.SetId(0, 0) ptIds.SetId(1, 1) ptIds.SetId(2, 2) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) ptIds.SetId(0, 1) ptIds.SetId(1, 3) ptIds.SetId(2, 2) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) for order in range(1, 6): lslm = PoissonSolver(pdata, max_edge_length=1000., order=order) print('order = ', order) print('g matrix: ', lslm.getGreenMatrix())
def createPolyData(faces, vtList, verts, tcoords): points = vtk.vtkPoints() points.SetDataTypeToDouble() points.SetNumberOfPoints(len(vtList)) tcoordArray = vtk.vtkDoubleArray() tcoordArray.SetName('tcoords') tcoordArray.SetNumberOfComponents(2) tcoordArray.SetNumberOfTuples(len(vtList)) for i, vt in enumerate(vtList): vi, ti = vt xyz = verts[vi] uv = tcoords[ti] points.SetPoint(i, xyz) tcoordArray.SetTuple2(i, uv[0], uv[1]) cells = vtk.vtkCellArray() for i, face in enumerate(faces): tri = vtk.vtkTriangle() tri.GetPointIds().SetId(0, face[0]) tri.GetPointIds().SetId(1, face[1]) tri.GetPointIds().SetId(2, face[2]) cells.InsertNextCell(tri) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(cells) polyData.GetPointData().SetTCoords(tcoordArray) return polyData
def __init__(self): vmtkSeedSelector.__init__(self) self.PickedSeedIds = vtk.vtkIdList() self.PickedSeeds = vtk.vtkPolyData() self.vmtkRenderer = None self.OwnRenderer = 0 self.Script = None
def testSingleTriangle(): "Single triangle" h = 0.1 # create set of points points = vtk.vtkPoints() points.SetNumberOfPoints(3) points.SetPoint(0, [1., -1.*h/3., -1.*h/3.]) points.SetPoint(1, [1., 2.*h/3., -1.*h/3.]) points.SetPoint(2, [1., -1.*h/3., 2.*h/3.]) # create vtkPolyData object pdata = vtk.vtkPolyData() pdata.SetPoints(points) ptIds = vtk.vtkIdList() ptIds.SetNumberOfIds(3) ptIds.SetId(0, 0) ptIds.SetId(1, 1) ptIds.SetId(2, 2) pdata.Allocate(1, 1) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) for order in range(1, 6): lslm = PoissonSolver(pdata, max_edge_length=1000.) print('order = ', order) print('g matrix: ', lslm.getGreenMatrix())
def draw_lines(nodes, color): points = vtk.vtkPoints() lines = vtk.vtkCellArray() nodecnt = 0 colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for node in nodes: edges = node.getedges() for edge in edges: x0,y0,z0 = edge[0] x1,y1,z1 = edge[1] points.InsertNextPoint(edge[0]) points.InsertNextPoint(edge[1]) line = vtk.vtkLine() line.GetPointIds().SetId(0,nodecnt) line.GetPointIds().SetId(1,nodecnt+1) lines.InsertNextCell(line) nodecnt += 2 colors.InsertNextTupleValue(color) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) linesPolyData.GetCellData().SetScalars(colors) return linesPolyData
def copyFirstNLines(self, sourcePolyData, lineCount): """make a polydata with only the first N polylines""" polyData = vtk.vtkPolyData() points = vtk.vtkPoints() polyData.SetPoints(points) lines = vtk.vtkCellArray() polyData.SetLines(lines) sourcePoints = sourcePolyData.GetPoints() sourceLines = sourcePolyData.GetLines() sourceIdList = vtk.vtkIdList() sourceLines.InitTraversal() while sourceLines.GetNextCell(sourceIdList): pointCount = sourceIdList.GetNumberOfIds() idList = vtk.vtkIdList() for idIndex in range(pointCount): sourceId = sourceIdList.GetId(idIndex) point = sourcePoints.GetPoint(sourceId) id = points.InsertNextPoint(point) idList.InsertNextId(id) lines.InsertNextCell(idList) if lines.GetNumberOfCells() > lineCount: break return polyData
def createCurtain( self, **args ): trajectory_points = self.getTrajectoryPoints( **args ) extent = self.input().GetExtent() spacing = self.input().GetSpacing() nStrips = extent[5] - extent[4] zmax = spacing[2] * nStrips z_inc = zmax / nStrips polydata = vtk.vtkPolyData() stripArray = vtk.vtkCellArray() stripData = [ vtk.vtkIdList() for ix in range(nStrips) ] points = vtk.vtkPoints() for iPt in range( trajectory_points.GetNumberOfPoints() ): pt_coords = trajectory_points.GetPoint( iPt ) z = 0.0 for iLevel in range( nStrips ): vtkId = points.InsertNextPoint( pt_coords[0], pt_coords[1], z ) sd = stripData[ iLevel ] sd.InsertNextId( vtkId ) sd.InsertNextId( vtkId+1 ) z = z + z_inc points.InsertNextPoint( pt_coords[0], pt_coords[1], z ) for strip in stripData: stripArray.InsertNextCell(strip) polydata.SetPoints( points ) polydata.SetStrips( stripArray ) return polydata
def ProbeData(self, coordinates, name): """Interpolate field values at these coordinates.""" # Initialise locator locator = vtk.vtkPointLocator() locator.SetDataSet(self.ugrid) locator.SetTolerance(10.0) locator.Update() # Initialise probe points = vtk.vtkPoints() points.SetDataTypeToDouble() ilen, jlen = coordinates.shape for i in range(ilen): points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetInput(polydata) probe.SetSource(self.ugrid) probe.Update() # Generate a list invalidNodes, containing a map from invalid nodes in the # result to their closest nodes in the input valid_ids = probe.GetValidPoints() valid_loc = 0 invalidNodes = [] for i in range(ilen): if valid_ids.GetTuple1(valid_loc) == i: valid_loc += 1 else: nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]]) invalidNodes.append((i, nearest)) # Get final updated values pointdata=probe.GetOutput().GetPointData() vtkdata=pointdata.GetArray(name) nc=vtkdata.GetNumberOfComponents() nt=vtkdata.GetNumberOfTuples() array = arr([vtkdata.GetValue(i) for i in range(nt * nc)]) # Fix the point data at invalid nodes if len(invalidNodes) > 0: try: oldField = self.ugrid.GetPointData().GetArray(name) components = oldField.GetNumberOfComponents() except: try: oldField = self.ugrid.GetCellData().GetArray(name) components = oldField.GetNumberOfComponents() except: raise Exception("ERROR: couldn't find point or cell field data with name "+name+" in file "+self.filename+".") for invalidNode, nearest in invalidNodes: for comp in range(nc): array[invalidNode * nc + comp] = oldField.GetValue(nearest * nc + comp) valShape = self.GetField(name)[0].shape array.shape = tuple([nt] + list(valShape)) return array
def latitude_create( arg_lat, arg_projection): if arg_projection == 'linear' : n_polypoints=2 polygonpoints=vtk.vtkPoints() polygonpoints.SetNumberOfPoints(n_polypoints) polygonpoints.InsertPoint(0,-180,arg_lat,0) polygonpoints.InsertPoint(1,540,arg_lat,0) else: n_polypoints=360 polygonpoints=vtk.vtkPoints() polygonpoints.SetNumberOfPoints(n_polypoints) deg2rad=numpy.pi/180. for n in range(n_polypoints) : theta=2*numpy.pi*n/(n_polypoints-1) x=numpy.cos(arg_lat*deg2rad)*numpy.cos(theta) y=numpy.cos(arg_lat*deg2rad)*numpy.sin(theta) z=numpy.sin(arg_lat*deg2rad) polygonpoints.InsertPoint(n,x,y,z) polygonlines=vtk.vtkCellArray() polygonlines.InsertNextCell(n_polypoints) for n in range(n_polypoints) : polygonlines.InsertCellPoint(n) latpolydata=vtk.vtkPolyData() latpolydata.SetPoints(polygonpoints) latpolydata.SetLines(polygonlines) return latpolydata
def setEdgesPolydata(self, vd): self.edges = [] self.edges = vd.getEdgesGenerators() self.epts = vtk.vtkPoints() nid = 0 lines=vtk.vtkCellArray() for e in self.edges: p1 = self.scale*e[0] p2 = self.scale*e[1] self.epts.InsertNextPoint( p1.x, p1.y, p1.z) self.epts.InsertNextPoint( p2.x, p2.y, p2.z) line = vtk.vtkLine() line.GetPointIds().SetId(0,nid) line.GetPointIds().SetId(1,nid+1) nid = nid+2 lines.InsertNextCell(line) linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(self.epts) linePolyData.SetLines(lines) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linePolyData) self.edge_actor = vtk.vtkActor() self.edge_actor.SetMapper(mapper) self.edge_actor.GetProperty().SetColor( camvtk.cyan ) myscreen.addActor( self.edge_actor ) myscreen.render()
def CreatePolyData( pts, faces ): """ Creates vtkPolyData from vertices and faces pts numpy.array: Nx3 array of vertices faces numpy.array: Mx3 array of faces Return vtkPolyData """ (nv,mv) = pts.shape (nf,mf) = faces.shape cells = vtk.vtkCellArray() for j in range(nf): cell = vtk.vtkTriangle() cell.GetPointIds().SetNumberOfIds(3) cell.GetPointIds().SetId( 0, faces[j,0] ) cell.GetPointIds().SetId( 1, faces[j,1] ) cell.GetPointIds().SetId( 2, faces[j,2] ) cells.InsertNextCell( cell ) points = vtk.vtkPoints() points.SetNumberOfPoints(nv) for j in range(nv): points.SetPoint( j, pts[j,0], pts[j,1], pts[j,2] ) new_mesh = vtk.vtkPolyData() new_mesh.SetPoints( points ) new_mesh.SetPolys( cells ) new_mesh.BuildCells() return new_mesh
def VTKPoints2PolyData( pts ): """ Transforms numpy point array into vtkPolyData pts numpy.array: Nx3 array of vertices Return vtkPolyData """ (nv,mv) = pts.shape vertices = vtk.vtkCellArray() points = vtk.vtkPoints() points.SetNumberOfPoints(nv) for j in range(nv): points.SetPoint( j, pts[j,0], pts[j,1], pts[j,2] ) vertices.InsertNextCell(1) vertices.InsertCellPoint(j) # Create a polydata object mesh = vtk.vtkPolyData() # Set the points and vertices we created as the geometry and topology of the polydata mesh.SetPoints(points) mesh.SetVerts(vertices) mesh.BuildCells() return mesh
def overlay_polygon_internal(self, coords, height, colour): """Add a polygon to the output of the visualiser. coords is a list of 2-tuples representing x and y coordinates. These are triangulated by vtkDelaunay2D. height is the z-value given to all points. colour is the colour of the polygon, as a 3-tuple representing r, g, b values between 0 and 1. This function should not be called from outside the visualiser thread. Use overlay_polygon instead. """ points = vtkPoints() for coord in coords: points.InsertNextPoint(coord[0], coord[1], height) profile = vtkPolyData() profile.SetPoints(points) delny = vtkDelaunay2D() delny.SetInput(profile) mesh = vtkPolyDataMapper() mesh.SetInput(delny.GetOutput()) actor = vtkActor() actor.SetMapper(mesh) actor.GetProperty().SetColor(colour) self.vtk_renderer.AddActor(actor)
def ConvertDataSetToSurface(algorithmOutputPort): dataSetSurfaceFilter = vtk.vtkDataSetSurfaceFilter() dataSetSurfaceFilter.SetInputConnection(algorithmOutputPort) dataSetSurfaceFilter.Update() polyData = vtk.vtkPolyData() polyData.ShallowCopy(dataSetSurfaceFilter.GetOutput()) return polyData
def GetLineFromWidget(self, obj, event): if self.Type == "freehand": path = vtk.vtkPolyData() obj.GetPath(path) elif self.Type == "contour": path = self.ImageTracerWidget.GetRepresentation().GetContourRepresentationAsPolyData() spacing = self.Image.GetSpacing() translation = [0.0, 0.0, 0.0] translation[self.Axis] = self.SliceVOI[self.Axis * 2] * spacing[self.Axis] transform = vtk.vtkTransform() transform.Translate(translation) pathTransform = vtk.vtkTransformPolyDataFilter() pathTransform.SetInput(path) pathTransform.SetTransform(transform) pathTransform.Update() self.Line = pathTransform.GetOutput() if self.Line.GetSource(): self.Line.GetSource().UnRegisterAllOutputs()
def readPolyData(file_name, readerType): reader = readerType() reader.SetFileName(file_name) reader.Update() polyData = vtk.vtkPolyData() polyData.ShallowCopy(reader.GetOutput()) return polyData
def __init__(self, pointlist=[]): points = vtk.vtkPoints() cellArr = vtk.vtkCellArray() Colors = vtk.vtkUnsignedCharArray() Colors.SetNumberOfComponents(3) Colors.SetName("Colors") n=0 for p in pointlist: vert = vtk.vtkVertex() points.InsertNextPoint(p.x, p.y, p.z) vert.GetPointIds().SetId(0,n) cellArr.InsertNextCell( vert ) col = clColor(p.cc()) Colors.InsertNextTuple3( float(255)*col[0], float(255)*col[1], float(255)*col[2] ) n=n+1 polydata= vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetVerts( cellArr ) polydata.GetPointData().SetScalars(Colors) polydata.Modified() polydata.Update() self.src=polydata self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.src) self.SetMapper(self.mapper)
def update_height_quantity(self, quantityName, dynamic=True): N_vert = len(self.source.get_vertex_coordinates()) qty_index = num.zeros(N_vert, num.float) triangles = self.source.get_triangles() vertex_values, _ = self.source.get_quantity(quantityName).get_vertex_values(xy=False, smooth=False) for n in range(N_vert): qty_index[n] = vertex_values[n] points = vtkPoints() for v in range(N_vert): points.InsertNextPoint(self.vert_index[v][0], self.vert_index[v][1], qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]) if self.xmin == None or self.xmin > self.vert_index[v][0]: self.xmin = self.vert_index[v][0] if self.xmax == None or self.xmax < self.vert_index[v][0]: self.xmax = self.vert_index[v][0] if self.ymin == None or self.ymin > self.vert_index[v][1]: self.ymin = self.vert_index[v][1] if self.ymax == None or self.ymax < self.vert_index[v][1]: self.ymax = self.vert_index[v][1] if self.zmin == None or self.zmin > qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]: self.zmin = qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName] if self.zmax == None or self.zmax < qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]: self.zmax = qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName] polydata = self.vtk_polyData[quantityName] = vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(self.vtk_cells)
def make_pData_periodic (np, x, a, lattice): pos = vtk.vtkPoints() diameter = vtk.vtkDoubleArray() diameter.SetNumberOfComponents(1) # primary cell for i in range(np): pos.InsertNextPoint(x[i*3], x[i*3+1], x[i*3+2]) if a != []: diameter.InsertNextTuple1(2.0*a[i]) else: diameter.InsertNextTuple1(2.0) # image cells for ix in range(-1,2): for iy in range(-1,2): for iz in range(-1,2): if ix == 0 and iy == 0 and iz == 0: continue for i in range(np): pos.InsertNextPoint(x[i*3 ]+float(ix)*lattice[0], x[i*3+1]+float(iy)*lattice[1], x[i*3+2]+float(iz)*lattice[2]) if a != []: diameter.InsertNextTuple1(2.0*a[i]) else: diameter.InsertNextTuple1(2.0) # first make pData containing particle coordinates pData = vtk.vtkPolyData() pData.SetPoints(pos) pData.GetPointData().SetScalars(diameter) return pData
def plot3d(self, data, date): camera = vtk.vtkCamera() camera.SetPosition(1,0,0) camera.SetFocalPoint(0,0,0) camera.Roll(-90) camera.Zoom(0.7) self.renderer = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer) plane = vtk.vtkPlaneSource() plane.SetCenter(0.0, 0.0, 0.0) plane.SetNormal(1.0, 0.0, 0.0) reader = vtk.vtkJPEGReader() reader.SetFileName("poland_plane.jpg") map_to_plane = vtk.vtkTextureMapToPlane() map_to_plane.SetInputConnection(plane.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(map_to_plane.GetOutputPort()) texture = vtk.vtkTexture() texture.SetInputConnection(reader.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetTexture(texture) self.renderer.AddActor(actor) points = vtk.vtkPoints() mat = [] if (self.option != 5): for city,x,y in zip(data["city_name"], data["x"], data["y"]): df = self.dataframe_collection[city] val = 0 if self.option == 1: val = df["humidity"].mean() elif self.option == 3: rain_max = df["rain"].max() val = (100 / (df["rain"].max() - df["rain"].min())) * (df["rain"].mean() - df["rain"].min()) if math.isnan(val): val = 0 if(val != 0): cubeActor = vtk_bar((0,x/700-0.72,-y/700+0.72), val/500) cubeActor.GetMapper().ScalarVisibilityOff() cubeActor.GetProperty().SetColor((0, 0, 255)) cubeActor.GetProperty().SetInterpolationToFlat() scale_transform = vtk.vtkTransform() scale_transform.Scale(0.5, 0.5, 0.5) cubeActor.SetUserTransform(scale_transform) self.renderer.AddActor(cubeActor) if self.option == 2: source = vtk.vtkSphereSource() source.SetCenter(0.1,x/1400-0.36,-y/1400+0.36) source.SetRadius(df["clouds"].mean()/1500) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.renderer.AddActor(actor) if self.option == 4: textActor = vtk.vtkTextActor() textActor.SetInput ("Hello world") textActor.SetPosition2 ( x/1400-0.36, -y/1400+0.36 ) textActor.GetTextProperty().SetFontSize ( 1 ) textActor.GetTextProperty().SetColor ( 1.0, 0.0, 0.0 ) self.renderer.AddActor2D ( textActor ) points.InsertNextPoint(df["temp"].mean(), x/1400-0.36, -y/1400+0.36) mat.append([x/1400-0.36, -y/1400+0.36, df["temp"].mean()]) if self.option == 4: mat = np.array(mat) plane = vtk.vtkPlaneSource() plane.SetCenter(0.0, 0.0, 0.0) plane.SetNormal(1.0, 0.0, 0.0) inputPolyData = vtk.vtkPolyData() inputPolyData.SetPoints(points) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(inputPolyData) delaunay.Update() outputPolyData = delaunay.GetOutput() bounds = [0 for i in range(6)] outputPolyData.GetBounds(bounds) xMin = bounds[2] xMax = bounds[3] yMin = bounds[4] yMax = bounds[5] x = np.linspace(xMin, xMax, 50) y = np.linspace(yMin, yMax, 50) x, y = np.meshgrid(x,y) x, y = x.flatten(), y.flatten() z = griddata((mat[:,0], mat[:,1]), mat[:,2], (x,y), method='nearest') z = z.flatten() plane.SetResolution(49,49) plane.SetOrigin([0.1, xMin, yMin]) plane.SetPoint1([0.1, xMax, yMin]) plane.SetPoint2([0.1, xMin, yMax]) plane.Update() nPoints = plane.GetOutput().GetNumberOfPoints() scalars = vtk.vtkFloatArray() scalars.SetNumberOfValues(nPoints) for i in range(nPoints): scalars.SetValue(i, float(z[i])) plane.GetOutput().GetPointData().SetScalars(scalars) lookupTable = vtk.vtkLookupTable() lookupTable.SetTableRange (np.amin(z), np.amax(z)) lookupTable.SetHueRange (0.5, 1); lookupTable.SetSaturationRange (1, 1); lookupTable.SetValueRange (1,1); lookupTable.Build() colorSeries = vtk.vtkColorSeries() colorSeries.SetColorScheme(vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_10) lut = vtk.vtkColorTransferFunction() lut.SetColorSpaceToHSV() nColors = colorSeries.GetNumberOfColors() zMin = np.min(z) zMax = np.max(z) for i in range(0, nColors): color = colorSeries.GetColor(i) color = [c/255.0 for c in color] t = zMin + float(zMax - zMin)/(nColors - 1) * i lut.AddRGBPoint(t, color[0], color[1], color[2]) colorbar = vtk.vtkScalarBarActor() colorbar.SetMaximumNumberOfColors(400) colorbar.SetLookupTable (lut) colorbar.SetWidth(0.05) colorbar.SetPosition(0.95, 0.1) colorbar.SetLabelFormat("%.3g") colorbar.VisibilityOn() self.renderer.AddActor(colorbar) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(plane.GetOutputPort()) mapper.ScalarVisibilityOn() mapper.SetScalarModeToUsePointData() mapper.SetLookupTable(lut) mapper.SetColorModeToMapScalars() actor = vtk.vtkActor() actor.GetProperty().SetOpacity(0.9) actor.SetMapper(mapper) self.renderer.AddActor(actor) self.renderer.SetActiveCamera(camera) self.vtkWidget.Initialize() self.vtkWidget.Start()
def writeConfigurationVTK(data, outfile): Points = vtk.vtkPoints() has_v = False has_n = False if not (data.keys.has_key('x') and data.keys.has_key('y') and data.keys.has_key('z')): raise "Particle coordinate not specified in the input data." x = np.array(data.data[data.keys['x']]) y = np.array(data.data[data.keys['y']]) z = np.array(data.data[data.keys['z']]) if (data.keys.has_key('vx') or data.keys.has_key('vy') or data.keys.has_key('vz')): vx = np.array(data.data[data.keys['vx']]) vy = np.array(data.data[data.keys['vy']]) vz = np.array(data.data[data.keys['vz']]) has_v = True if (data.keys.has_key('nx') or data.keys.has_key('ny') or data.keys.has_key('nz')): nx = np.array(data.data[data.keys['nx']]) ny = np.array(data.data[data.keys['ny']]) nz = np.array(data.data[data.keys['nz']]) has_n = True r = np.ones(len(x)) Radii = vtk.vtkDoubleArray() Radii.SetNumberOfComponents(1) Radii.SetName('Radius') if has_v: Velocities = vtk.vtkDoubleArray() Velocities.SetNumberOfComponents(3) Velocities.SetName("Velocity") if has_n: Directors = vtk.vtkDoubleArray() Directors.SetNumberOfComponents(3) Directors.SetName("Directors") #NDirectors = vtk.vtkDoubleArray() #NDirectors.SetNumberOfComponents(3) #NDirectors.SetName("NDirectors") for (xx, yy, zz, rr, nnx, nny, nnz) in zip(x, y, z, r, nx, ny, nz): Points.InsertNextPoint(xx, yy, zz) Radii.InsertNextValue(rr) if has_v: #vnorm=np.sqrt(vx**2+vy**2+vz**2) #u=0 for (vvx, vvy, vvz) in zip(vx, vy, vz): #no=vnorm[u] #u+=1 #Velocities.InsertNextTuple3(vvx/no,vvy/no,vvz/no) Velocities.InsertNextTuple3(vvx, vvy, vvz) if has_n: for (nnx, nny, nnz) in zip(nx, ny, nz): #Directors.InsertNextTuple3(0.5*nnx,0.5*nny,0.5*nnz) #NDirectors.InsertNextTuple3(-0.5*nnx,-0.5*nny,-0.5*nnz) Directors.InsertNextTuple3(nnx, nny, nnz) #if args.connected: #Lines = vtk.vtkCellArray() #Line = vtk.vtkLine() #points = np.column_stack((x,y,z)) #hull = ConvexHull(points) #edges = [] #for h in hull.simplices: #i, j, k = h #if not sorted([i,j]) in edges: edges.append(sorted([i,j])) #if not sorted([i,k]) in edges: edges.append(sorted([i,k])) #if not sorted([j,k]) in edges: edges.append(sorted([j,k])) #for (i,j) in edges: #Line.GetPointIds().SetId(0,i) #Line.GetPointIds().SetId(1,j) #Lines.InsertNextCell(Line) polydata = vtk.vtkPolyData() polydata.SetPoints(Points) #if args.connected: #polydata.SetLines(Lines) polydata.GetPointData().AddArray(Radii) if has_v: polydata.GetPointData().AddArray(Velocities) if has_n: polydata.GetPointData().AddArray(Directors) #polydata.GetPointData().AddArray(NDirectors) #polydata.GetPointData().AddArray(NDirectors) polydata.Modified() writer = vtk.vtkXMLPolyDataWriter() #outname = '.'.join(f.split('.')[:-1]) writer.SetFileName(outfile) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(polydata) else: writer.SetInputData(polydata) writer.SetDataModeToAscii() writer.Write()
def plot(self, data, color="black", color_value=None, cmap="viridis", point_size=None, pixel_point=False): """Add a 3D scatterplot to the current plot. Data is given as an array of size (N, 3). Color denotes the one color used for every point while color_value is an array of scalars that are used to color the points with a given color map. """ if len(data.shape) != 2 or data.shape[1] != 3: raise ValueError("data must have shape (n, 3) where n is the " "number of points.") data = _numpy.float32(data) data_vtk = array_to_float_array(data) point_data = _vtk.vtkPoints() point_data.SetData(data_vtk) points_poly_data = _vtk.vtkPolyData() points_poly_data.SetPoints(point_data) if color_value is not None: lut = get_lookup_table(color_value.min(), color_value.max(), colorscale=cmap) color_scalars = array_to_vtk(_numpy.float32(color_value.copy())) color_scalars.SetLookupTable(lut) points_poly_data.GetPointData().SetScalars(color_scalars) import matplotlib color_rgb = matplotlib.colors.to_rgb(color) if pixel_point: if point_size is None: point_size = 3 glyph_filter = _vtk.vtkVertexGlyphFilter() glyph_filter.SetInputData(points_poly_data) glyph_filter.Update() else: if point_size is None: point_size = _numpy.array(data).std() / len(data)**(1./3.) / 3. glyph_filter = _vtk.vtkGlyph3D() glyph_filter.SetInputData(points_poly_data) sphere_source = _vtk.vtkSphereSource() sphere_source.SetRadius(point_size) glyph_filter.SetSourceConnection(sphere_source.GetOutputPort()) glyph_filter.SetScaleModeToDataScalingOff() if color_value is not None: glyph_filter.SetColorModeToColorByScalar() else: glyph_filter.SetColorMode(0) glyph_filter.Update() poly_data = _vtk.vtkPolyData() poly_data.ShallowCopy(glyph_filter.GetOutput()) mapper = _vtk.vtkPolyDataMapper() mapper.SetInputData(poly_data) if color_value is not None: mapper.SetLookupTable(lut) mapper.SetUseLookupTableScalarRange(True) points_actor = _vtk.vtkActor() points_actor.SetMapper(mapper) points_actor.GetProperty().SetPointSize(point_size) points_actor.GetProperty().SetColor(*color_rgb) new_bounds = _numpy.array(points_actor.GetBounds()) self._bounds[0::2] = _numpy.minimum(self._bounds[0::2], new_bounds[0::2]) self._bounds[1::2] = _numpy.maximum(self._bounds[1::2], new_bounds[1::2]) self._axes_actor.SetBounds(self._bounds) self._renderer.AddActor(points_actor) self._render_window.Render()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') # cleaner = vtk.vtkCleanPolyData() # cleaner.SetInput(self.Surface) # cleaner.Update() # # triangleFilter = vtk.vtkTriangleFilter() # triangleFilter.SetInput(cleaner.GetOutput()) # triangleFilter.Update() # # self.Surface = triangleFilter.GetOutput() boundaryIds = vtk.vtkIdList() if self.Interactive: if not self.vmtkRenderer: from vmtk import vmtkrenderer self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor() boundaryExtractor.SetInputData(self.Surface) boundaryExtractor.Update() boundaries = boundaryExtractor.GetOutput() numberOfBoundaries = boundaries.GetNumberOfCells() seedPoints = vtk.vtkPoints() for i in range(numberOfBoundaries): barycenter = [0.0, 0.0, 0.0] vtkvmtk.vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter( boundaries.GetCell(i).GetPoints(), barycenter) seedPoints.InsertNextPoint(barycenter) seedPolyData = vtk.vtkPolyData() seedPolyData.SetPoints(seedPoints) labelsMapper = vtk.vtkLabeledDataMapper() labelsMapper.SetInputData(seedPolyData) labelsMapper.SetLabelModeToLabelIds() labelsActor = vtk.vtkActor2D() labelsActor.SetMapper(labelsMapper) self.vmtkRenderer.Renderer.AddActor(labelsActor) surfaceMapper = vtk.vtkPolyDataMapper() surfaceMapper.SetInputData(self.Surface) surfaceMapper.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(surfaceMapper) surfaceActor.GetProperty().SetOpacity(0.25) self.vmtkRenderer.Renderer.AddActor(surfaceActor) #self.vmtkRenderer.Render() #self.vmtkRenderer.Renderer.RemoveActor(labelsActor) #self.vmtkRenderer.Renderer.RemoveActor(surfaceActor) ok = False while not ok: labelString = self.InputText("Please input boundary ids: ", self.LabelValidator) labels = [int(label) for label in labelString.split()] ok = True for label in labels: if label not in list(range(numberOfBoundaries)): ok = False for label in labels: boundaryIds.InsertNextId(label) if self.Method == 'simple': capper = vtkvmtk.vtkvmtkSimpleCapPolyData() capper.SetInputData(self.Surface) elif self.Method == 'centerpoint': capper = vtkvmtk.vtkvmtkCapPolyData() capper.SetInputData(self.Surface) capper.SetDisplacement(0.0) capper.SetInPlaneDisplacement(0.0) elif self.Method == 'smooth': triangle = vtk.vtkTriangleFilter() triangle.SetInputData(self.Surface) triangle.PassLinesOff() triangle.PassVertsOff() triangle.Update() capper = vtkvmtk.vtkvmtkSmoothCapPolyData() capper.SetInputConnection(triangle.GetOutputPort()) capper.SetConstraintFactor(self.ConstraintFactor) capper.SetNumberOfRings(self.NumberOfRings) elif self.Method == 'annular': capper = vtkvmtk.vtkvmtkAnnularCapPolyData() capper.SetInputData(self.Surface) elif self.Method == 'concaveannular': from vmtk import vtkvmtkcontrib capper = vtkvmtkcontrib.vtkvmtkConcaveAnnularCapPolyData() capper.SetInputData(self.Surface) if self.Interactive: capper.SetBoundaryIds(boundaryIds) capper.SetCellEntityIdsArrayName(self.CellEntityIdsArrayName) capper.SetCellEntityIdOffset(self.CellEntityIdOffset) capper.Update() self.Surface = capper.GetOutput() if self.TriangleOutput == 1: triangle = vtk.vtkTriangleFilter() triangle.SetInputData(self.Surface) triangle.PassLinesOff() triangle.PassVertsOff() triangle.Update() self.Surface = triangle.GetOutput() normals = vtk.vtkPolyDataNormals() normals.SetInputData(self.Surface) normals.AutoOrientNormalsOn() normals.SplittingOff() normals.ConsistencyOn() normals.Update() self.Surface = normals.GetOutput()
pts_list_i.append(pt_j) pts_list.append(pts_list_i) # Procrustes Filter procrustes_filter = vtk.vtkProcrustesAlignmentFilter() group = vtk.vtkMultiBlockDataGroupFilter() pts_polyData_list = [] # Check # nObs = 3 for i in range(nObs): pt_polyData = vtk.vtkPolyData() pt_Points = vtk.vtkPoints() pt_lines = vtk.vtkCellArray() # Set Points for j in range(nPt): pt_Points.InsertNextPoint(pts_list[i][j][0], pts_list[i][j][1], 0) for j in range(nPt): line_j = vtk.vtkLine() line_j.GetPointIds().SetId(0, j) line_j.GetPointIds().SetId(1, j + 1) if j == (nPt - 1): line_j.GetPointIds().SetId(0, j) line_j.GetPointIds().SetId(1, 0)
def add_faces(self, faces, color, opacity=0.35): for face in faces: if len(face) == 3: points = vtk.vtkPoints() triangle = vtk.vtkTriangle() for ii in range(3): points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2]) triangle.GetPointIds().SetId(ii, ii) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInputConnection( trianglePolyData.GetProducerPort()) else: mapper.SetInputData(trianglePolyData) # mapper.SetInput(trianglePolyData) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) ac.GetProperty().SetColor(color) self.ren.AddActor(ac) elif False and len(face) == 4: points = vtk.vtkPoints() for ii in range(4): points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2]) line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, 0) line1.GetPointIds().SetId(1, 2) line2 = vtk.vtkLine() line2.GetPointIds().SetId(0, 3) line2.GetPointIds().SetId(1, 1) lines = vtk.vtkCellArray() lines.InsertNextCell(line1) lines.InsertNextCell(line2) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(lines) ruledSurfaceFilter = vtk.vtkRuledSurfaceFilter() ruledSurfaceFilter.SetInput(polydata) ruledSurfaceFilter.SetResolution(15, 15) ruledSurfaceFilter.SetRuledModeToResample() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(ruledSurfaceFilter.GetOutput()) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) ac.GetProperty().SetColor(color) self.ren.AddActor(ac) elif len(face) > 3: center = np.zeros(3, np.float) for site in face: center += site center /= np.float(len(face)) for ii in range(len(face)): points = vtk.vtkPoints() triangle = vtk.vtkTriangle() points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2]) ii2 = np.mod(ii + 1, len(face)) points.InsertNextPoint(face[ii2][0], face[ii2][1], face[ii2][2]) points.InsertNextPoint(center[0], center[1], center[2]) for ii in range(3): triangle.GetPointIds().SetId(ii, ii) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInputConnection( trianglePolyData.GetProducerPort()) else: mapper.SetInputData(trianglePolyData) # mapper.SetInput(trianglePolyData) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) ac.GetProperty().SetColor(color) self.ren.AddActor(ac) else: raise ValueError("Number of points for a face should be >= 3")
def voxelise(input_mesh: Union[np.ndarray, vtk.vtkDataObject, str], output_grid: Union[vtk.vtkStructuredGrid, str] \ = None, array_name: str = "", size: float = 0.3, grid_elements: int = 64, move_input: float = None, center: bool = False, scale_input: float = None, reuse_transform: bool = False, signed_df: bool = True ): """ Creates a voxelised distance field, stores it in a vtkStructuredGrid,\ optinally writes to disk. :param input_mesh: Input mesh/points. Can be path to model file, \ or numpy array. Units of mesh should be in metres. :type input_mesh: Union[np.ndarray, str] :param output_grid: Either a vtkStrucutredGrid object, or a file that contains one (or will be created), if not specified, a grid will be created. :type output_grid: Union[vtk.vtkStructuredGrid, str], optional :param array_name: Name of array in which to store distance field, \ if not specified, defaults to preoperativeSurface for if signed_df = True, else intraoperativeSurface :type array_name: str, optional :param size: Grid size, defaults to 0.3 :type size: float, optional :param grid_elements: Number of x/y/z elements in grid, defaults to 64 \ :type grid_elements: int, optional :param move_input: Move the input before transforming to distance field \ (movement is applied before scaling! defaults to None :type move_input: float, optional :param center: Center the data around the origin. defaults to False :type center: bool, optional :param scale_input: Scale the input before transforming to distance field \ (movement is applied before scaling!). Input is expected to be in metres, \ if it is in mm, set scale_input to 0.001 defaults to None :type scale_input: float, optional :param reuse_transform: Reuse transformation already stored in the grid. \ Use this if you want to center mesh 1 and then apply the same transformation to mesh 2. Mutually exclusive with center, scale_input and move_input. defaults to False :type reuse_transform: bool, optional :param signed_df: Calcualte signed or unsigned distance field. defaults to True :type signed_df: bool, optional :return grid: Grid containing distance field. :rtype: vtk.vtkStructuredGrid """ input_is_point_cloud = False if isinstance(input_mesh, str): mesh = load_points_from_file(input_mesh) elif isinstance(input_mesh, vtk.vtkDataObject): mesh = input_mesh else: input_is_point_cloud = True pts = vtk.vtkPoints() verts = vtk.vtkCellArray() for i in range(input_mesh.shape[0]): pts.InsertNextPoint(input_mesh[i][0], input_mesh[i][1], input_mesh[i][2]) verts.InsertNextCell(1, (i,)) mesh = vtk.vtkPolyData() mesh.SetPoints(pts) mesh.SetVerts(verts) input_is_point_cloud = True # If no array name was given, use sensible defaults: if array_name == "": if signed_df: array_name = "preoperativeSurface" else: array_name = "intraoperativeSurface" output_grid_is_file = isinstance(output_grid, str) output_grid_is_vtkgrid = isinstance(output_grid, vtk.vtkStructuredGrid) if output_grid_is_file and not output_grid.endswith(".vts"): raise IOError("Output grid file needs to be .vts!") if reuse_transform and (center or move_input or scale_input): raise IOError( "reuse_transform may not be used together with center, \ moveInput or --scaleInput!") mesh = unstructuredGridToPolyData(mesh) bounds = [0] * 6 mesh.GetBounds(bounds) LOGGER.debug( "Resulting bounds: \ ({:.3f}-{:.3f}, {:.3f}-{:.3f}, {:.3f}-{:.3f})".format(*bounds)) #################################################### # Load the output mesh if it is a file, otherwise it is a vtkStructuredGrid: if output_grid_is_file: if os.path.exists(output_grid): reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(output_grid) reader.Update() grid = reader.GetOutput() if grid.GetPointData().GetArray(array_name): err = "The output file {} already has a field named {}!".format( output_grid, array_name) raise IOError(err) b = grid.GetBounds() size = b[1] - b[0] grid_elements = grid.GetDimensions()[0] else: grid = createGrid(size, grid_elements) elif output_grid_is_vtkgrid: grid = output_grid b = grid.GetBounds() size = b[1] - b[0] grid_elements = grid.GetDimensions()[0] # We don't already have a grid, create one else: grid = createGrid(size, grid_elements) #################################################### # Transform input mesh: tf = vtk.vtkTransform() if scale_input is not None: LOGGER.debug("Scaling point cloud by: %s", scale_input) tf.Scale([scale_input] * 3) if move_input is not None: LOGGER.debug("Moving point cloud by: %s", move_input) tf.Translate(move_input) if center: bounds = [0] * 6 mesh.GetBounds(bounds) dx = -(bounds[1] + bounds[0]) * 0.5 dy = -(bounds[3] + bounds[2]) * 0.5 dz = -(bounds[5] + bounds[4]) * 0.5 LOGGER.debug("Moving point cloud by: %s", (dx, dy, dz)) tf.Translate((dx, dy, dz)) if reuse_transform: try: tf = loadTransformationMatrix(grid) except BaseException: print("Warning: reuse_transform was set, but no previous \ transformation found in grid. \ Won't apply any transformation.") tfFilter = vtk.vtkTransformFilter() tfFilter.SetTransform(tf) tfFilter.SetInputData(mesh) tfFilter.Update() mesh = tfFilter.GetOutput() LOGGER.debug("Applied transformation before voxelization:") LOGGER.debug(tf.GetMatrix()) # Remove previous array with the same name, if it exists if grid.GetPointData().GetArray(array_name): grid.GetPointData().RemoveArray(array_name) #################################################### # Compute the (signed) distance field on the output grid: LOGGER.debug("Will save results in array '" + array_name + "'.") LOGGER.info("Voxelization") if not input_is_point_cloud: surface = extractSurface(mesh) if signed_df: distanceField(surface, grid, array_name, signed=True) else: distanceField(surface, grid, array_name, signed=False) else: distanceFieldFromCloud(mesh, grid, array_name) #################################################### # Write the applied transform into a field data array: storeTransformationMatrix(grid, tf) #################################################### # Write the applied transform into a field data array: if output_grid_is_file: LOGGER.debug("Writing grid to file %s", output_grid) outputFolder = os.path.dirname(output_grid) if not os.path.exists(outputFolder): os.makedirs(outputFolder) write_grid_to_file(grid, output_grid) return grid
def symmetrizeLandmarks(self, meshNode, landmarkNode, plane, samplingPercentage): # clip and mirror mesh and points pointsVTK = vtk.vtkPoints() pointPolyData = vtk.vtkPolyData() pointPolyData.SetPoints(pointsVTK) mesh = meshNode.GetPolyData() for i in range(landmarkNode.GetNumberOfFiducials()): pointsVTK.InsertNextPoint( landmarkNode.GetNthControlPointPositionVector(i)) geometryFilter = vtk.vtkVertexGlyphFilter() geometryFilter.SetInputData(pointPolyData) geometryFilter.Update() vertPolyData = geometryFilter.GetOutput() mirrorPoints = self.clipAndMirrorWithPlane(vertPolyData, plane) mirrorMesh = self.clipAndMirrorWithPlane(mesh, plane) # get clipped point set clippedPoints = self.cropWithPlane(vertPolyData, plane) insideOutOption = True clippedMesh = self.cropWithPlane(mesh, plane, insideOutOption) # project mirrored points onto mesh maxProjection = mesh.GetLength() * .3 projectedPoints = self.projectPointsPolydata(mirrorMesh, clippedMesh, mirrorPoints, maxProjection) # convert symmetric points to landmark node clippedLMNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLMarkupsFiducialNode', "LM_normal") clippedLMNode.CreateDefaultDisplayNodes() clippedLMNode.SetDisplayVisibility(False) clippedLMNode.GetDisplayNode().SetPointLabelsVisibility(False) pink = [1, 0, 1] clippedLMNode.GetDisplayNode().SetSelectedColor(pink) projectedLMNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLMarkupsFiducialNode', "LM_inverse") projectedLMNode.CreateDefaultDisplayNodes() projectedLMNode.SetDisplayVisibility(False) projectedLMNode.GetDisplayNode().SetPointLabelsVisibility(False) teal = [0, 1, 1] projectedLMNode.GetDisplayNode().SetSelectedColor(teal) midlineLMNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLMarkupsFiducialNode', "LM_merged") midlineLMNode.CreateDefaultDisplayNodes() midlineLMNode.SetDisplayVisibility(False) midlineLMNode.GetDisplayNode().SetPointLabelsVisibility(False) orange = [1, .5, 0] midlineLMNode.GetDisplayNode().SetSelectedColor(orange) totalLMNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLMarkupsFiducialNode', "SymmetricPseudoLandmarks") totalLMNode.CreateDefaultDisplayNodes() totalLMNode.GetDisplayNode().SetPointLabelsVisibility(False) green = [0, 1, 0] purple = [1, 0, 1] totalLMNode.GetDisplayNode().SetSelectedColor(green) totalLMNode.GetDisplayNode().SetColor(purple) samplingDistance = mesh.GetLength() * samplingPercentage spatialConstraint = samplingDistance * samplingDistance mergedPoint = [0, 0, 0] for i in range(projectedPoints.GetNumberOfPoints()): clippedPoint = clippedPoints.GetPoint(i) projectedPoint = projectedPoints.GetPoint(i) distance = vtk.vtkMath().Distance2BetweenPoints( clippedPoint, projectedPoint) if distance > spatialConstraint: clippedLMNode.AddFiducialFromArray(clippedPoint, 'n_' + str(i)) projectedLMNode.AddFiducialFromArray(projectedPoint, 'i_' + str(i)) totalLMNode.AddFiducialFromArray(clippedPoint, 'n_' + str(i)) totalLMNode.AddFiducialFromArray(projectedPoint, 'i_' + str(i)) else: mergedPoint[0] = (clippedPoint[0] + projectedPoint[0]) / 2 mergedPoint[1] = (clippedPoint[1] + projectedPoint[1]) / 2 mergedPoint[2] = (clippedPoint[2] + projectedPoint[2]) / 2 totalLMNode.AddFiducialFromArray(mergedPoint, 'm_' + str(i)) midlineLMNode.AddFiducialFromArray(mergedPoint, 'm_' + str(i)) # set pseudo landmarks created to type II landmarkTypeSemi = True self.setAllLandmarksType(totalLMNode, landmarkTypeSemi) self.setAllLandmarksType(midlineLMNode, landmarkTypeSemi) self.setAllLandmarksType(projectedLMNode, landmarkTypeSemi) self.setAllLandmarksType(clippedLMNode, landmarkTypeSemi) return projectedLMNode
def projectPointsPolydata(self, sourcePolydata, targetPolydata, originalPoints, rayLength): #set up polydata for projected points to return projectedPointData = vtk.vtkPolyData() projectedPoints = vtk.vtkPoints() projectedPointData.SetPoints(projectedPoints) #set up locater for intersection with normal vector rays obbTree = vtk.vtkOBBTree() obbTree.SetDataSet(targetPolydata) obbTree.BuildLocator() #set up point locator for finding surface normals and closest point pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(sourcePolydata) pointLocator.BuildLocator() targetPointLocator = vtk.vtkPointLocator() targetPointLocator.SetDataSet(targetPolydata) targetPointLocator.BuildLocator() #get surface normal from each landmark point rayDirection = [0, 0, 0] normalArray = sourcePolydata.GetPointData().GetArray("Normals") if (not normalArray): print("no normal array, calculating....") normalFilter = vtk.vtkPolyDataNormals() normalFilter.ComputePointNormalsOn() normalFilter.SetInputData(sourcePolydata) normalFilter.Update() normalArray = normalFilter.GetOutput().GetPointData().GetArray( "Normals") if (not normalArray): print("Error: no normal array") return projectedPointData print('Original points:', originalPoints.GetNumberOfPoints()) for index in range(originalPoints.GetNumberOfPoints()): originalPoint = originalPoints.GetPoint(index) # get ray direction from closest normal closestPointId = pointLocator.FindClosestPoint(originalPoint) rayDirection = normalArray.GetTuple(closestPointId) rayEndPoint = [0, 0, 0] for dim in range(len(rayEndPoint)): rayEndPoint[ dim] = originalPoint[dim] + rayDirection[dim] * rayLength intersectionIds = vtk.vtkIdList() intersectionPoints = vtk.vtkPoints() obbTree.IntersectWithLine(originalPoint, rayEndPoint, intersectionPoints, intersectionIds) #if there are intersections, update the point to most external one. if intersectionPoints.GetNumberOfPoints() > 0: exteriorPoint = intersectionPoints.GetPoint( intersectionPoints.GetNumberOfPoints() - 1) projectedPoints.InsertNextPoint(exteriorPoint) #if there are no intersections, reverse the normal vector else: for dim in range(len(rayEndPoint)): rayEndPoint[dim] = originalPoint[ dim] + rayDirection[dim] * -rayLength obbTree.IntersectWithLine(originalPoint, rayEndPoint, intersectionPoints, intersectionIds) if intersectionPoints.GetNumberOfPoints() > 0: exteriorPoint = intersectionPoints.GetPoint(0) projectedPoints.InsertNextPoint(exteriorPoint) #if none in reverse direction, use closest mesh point else: closestPointId = targetPointLocator.FindClosestPoint( originalPoint) rayOrigin = targetPolydata.GetPoint(closestPointId) projectedPoints.InsertNextPoint(rayOrigin) print('Projected points:', originalPoints.GetNumberOfPoints()) return projectedPointData
points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 1, 1) points.InsertNextPoint(2, 2, 2) points.InsertNextPoint(3, 3, 3) points.InsertNextPoint(4, 4, 4) index = vtk.vtkIntArray() index.SetNumberOfComponents(1) index.SetName("index") index.InsertNextValue(0) index.InsertNextValue(1) index.InsertNextValue(2) index.InsertNextValue(3) index.InsertNextValue(4) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.GetPointData().AddArray(index) threshold = vtk.vtkThresholdPoints() threshold.SetInputData(polydata) threshold.ThresholdByLower(2) threshold.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "index") threshold.Update() polyMapper = vtk.vtkPolyDataMapper() polyMapper.SetInputData(threshold.GetOutput())
def HDF5toVTKCells(): input_meshes = [] # Read input SMC meshes. for in_file in input_mesh_files[output]: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(in_file) reader.Update() input_meshes += [reader.GetOutput()] # Find the number of writers and the number of branches given the # output files. writers = len(glob.glob("solution/" + output + "*t_0_b_1*")) branches = len(glob.glob("solution/" + output + "*t_0_b_*_0*")) print "Number of branches detected: " + str(branches) print "Number of writers detected: " + str(writers) for time_step in range(args.start, args.end + 1): append_filter = vtk.vtkAppendFilter() for branch in range(branches): mesh = vtk.vtkPolyData() mesh.DeepCopy(input_meshes[branch]) # The base input h5 filename given the branch and from which writer it came on said branch. h5_file_base = base_names[output] + str(time_step) + '_b_' + str( branch + 1) + '_' + 'x' + '.h5' print "Processing file", h5_file_base # Group all datasets of a branch at a specific time point given # the number of writers the data was split into. species_array = append_datasets(writers, h5_file_base, "data") # Loop through all attirbutes and append them to a new array in the # correct order given the quad to task ratio. for attribute in attributes[output]: reordered_array = vtk.vtkDoubleArray() reordered_array.SetName(attribute) reordered_array.SetNumberOfValues( numCells[output][0] * numCells[output][1] * circQuads * axialQuads) reorder_species(species_array[attribute], reordered_array, output) mesh.GetCellData().AddArray(reordered_array) append_filter.AddInputData(mesh) append_filter.Update() # Write the result. vtu_file = base_names[output] + str(time_step) + '.vtu' print 'Writing file', os.path.abspath(vtu_file) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(vtu_file) writer.SetInputData(append_filter.GetOutput()) writer.Update()
# The cell array can be thought of as a connectivity list. Here we # specify the number of points followed by that number of point # ids. This can be repeated as many times as there are primitives in # the list. strips = vtk.vtkCellArray() strips.InsertNextCell(8) # number of points strips.InsertCellPoint(0) strips.InsertCellPoint(1) strips.InsertCellPoint(2) strips.InsertCellPoint(3) strips.InsertCellPoint(4) strips.InsertCellPoint(5) strips.InsertCellPoint(6) strips.InsertCellPoint(7) profile = vtk.vtkPolyData() profile.SetPoints(points) profile.SetStrips(strips) map = vtk.vtkPolyDataMapper() map.SetInputData(profile) strip = vtk.vtkActor() strip.SetMapper(map) strip.GetProperty().SetColor(0.3800, 0.7000, 0.1600) # Create the usual rendering stuff. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor()
if child.tag != "DataSet": return None, None ts.append(float(child.get("timestep"))) fs.append(relpathfrom(pathroot, child.get("file"))) return ts, fs ### helpers end ########################################## ts, fns = read_pvd_file(pvd_file) reader = vtk.vtkXMLUnstructuredGridReader() loc_points = vtk.vtkPoints() loc_points.InsertNextPoint([0.0, 0.0, 0.0]) loc = vtk.vtkPolyData() loc.SetPoints(loc_points) probe = vtk.vtkProbeFilter() probe.SetSourceConnection(reader.GetOutputPort()) probe.SetInputData(loc) uys = np.zeros(len(ts)) ps = np.zeros(len(ts)) for i, (t, fn) in enumerate(zip(ts, fns)): print("###### time", t) reader.SetFileName(fn) probe.Update() grid = probe.GetOutput()
def HDF5toVTKLumen(): cellType = "ec" # Both ATP and WSS maps use EC mesh input_meshes = [] # Read input EC meshes. for in_file in input_mesh_files[cellType]: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(in_file) reader.Update() input_meshes += [reader.GetOutput()] # Find the number of writers and the number of branches given the # output files. writers = len(glob.glob("solution/" + output + "*_b_1*")) branches = len(glob.glob("solution/" + output + "*_b_*_0*")) append_filter = vtk.vtkAppendFilter() for branch in range(branches): species_array = [] mesh = vtk.vtkPolyData() mesh.DeepCopy(input_meshes[branch]) # The base input h5 filename given the branch and from which writer it came on said branch. h5_file_base = base_names[output] + '_b_' + str(branch + 1) + '_' + 'x' + '.h5' print "Processing file", h5_file_base for writer in range(writers): h5_file_name = h5_file_base[:-4] + str(writer) + h5_file_base[-3:] fid = h5py.h5f.open(h5_file_name) dset = h5py.h5d.open(fid, "data") shape = dset.shape rdata = numpy.zeros(shape[0], dtype=numpy.float64) dset.read(h5py.h5s.ALL, h5py.h5s.ALL, rdata) species_array += list(rdata.ravel())[:] reordered_array = vtk.vtkDoubleArray() reordered_array.SetName(output) reordered_array.SetNumberOfValues(numCells[cellType][0] * numCells[cellType][1] * circQuads * axialQuads) reorder_species(species_array, reordered_array, cellType) mesh.GetCellData().AddArray(reordered_array) append_filter.AddInputData(mesh) append_filter.Update() # Write the result. vtu_file = base_names[output] + '.vtu' print 'Writing file', os.path.abspath(vtu_file) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(vtu_file) writer.SetInputData(append_filter.GetOutput()) writer.Update()
points.InsertNextPoint(0.0, 1.0, 0.0) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) # make a quad polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(polygonPolyData) else: mapper.SetInputData(polygonPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) # Visualize renderer = vtk.vtkRenderer()
def __init__(self, data, rscale, src, name=None, csk=None): self.data = data self.name = name self.csk = csk points = vtk.vtkPoints() p_data = vtk.vtkPolyData() #note polydata self.p_data = p_data npnts = data.shape[0] points.SetNumberOfPoints(npnts) data2 = ns.numpy_to_vtk(num_array=data, deep=True, array_type=vtk.VTK_FLOAT) points.SetData(data2) #this will be used to scale the glyph size #could vary on sphere by sphere basis #rad = np.full(npnts,1.0) #note .2 srad = ns.numpy_to_vtk(num_array=rscale, deep=True, array_type=vtk.VTK_FLOAT) srad.SetName('scales') p_data.SetPoints(points) p_data.GetPointData().AddArray(srad) p_data.GetPointData().SetActiveScalars("scales") #radius first glyph = vtk.vtkGlyph3D() glyph.GeneratePointIdsOn() glyph.SetInputData(p_data) #glyph.SetSourceConnection(sphere.GetOutputPort()) #glyph.SetSourceConnection(cube.GetOutputPort()) glyph.SetSourceConnection(src.GetOutputPort()) glyph.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) #with out this the scales array is used for color #it seems to be necessary for using the color array #in later updates as well mapper.SetScalarModeToUsePointFieldData() #this version again yields white colors, despite col8 #mapper.SetScalarModeToUseCellData() white = np.full((npnts, 4), 255, dtype=np.uint8) white[:, 2] = 0 scol8 = ns.numpy_to_vtk(num_array=white, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR) scol8.SetName('col8') p_data.GetPointData().AddArray(scol8) #this sets the color array to be "col8", even tho it is not there yet #but it will be later in do_color2 mapper.SelectColorArray("col8") actor = vtk.vtkActor() actor.SetMapper(mapper) #white = np.full( (npnts,4),255,dtype=np.uint8) self.actor = actor self.glyph = glyph self.points = points self.p_data = p_data
anatomy_list = [ 'left_caudate', 'left_putamen', 'right_caudate', 'right_putamen' ] # M-Rep Lists CMRepDataList = [] riskGroupList = [] ageList = [] CAPList = [] SubjectList = [] # vtkPolyData for Intrinsic Mean meanPolyDataList = [] for d in range(len(anatomy_list)): meanPolyData_d = vtk.vtkPolyData() meanPolyDataList.append(meanPolyData_d) # For all subjects cnt = 0 for i in range(len(dataInfoList)): subj_dataFolder = dataFolderPath + 'PHD-AS1-' + dataInfoList[i].ID if not os.path.isdir(subj_dataFolder): print('PHD-AS1-' + dataInfoList[i].ID + "does not exist") continue # Skip if there is only one shape in the list if len(dataInfoList[i].AgeList) < 2: print(dataInfoList[i].ID + "has less than 2 data") continue
count += 6 triangles.InsertNextCell(triangle) # Add some color r = [int(i / float(size) * 255), int(j / float(size) * 255), 0] colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) # Use two different filters to show the difference smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
def extract_selection_vtp(poly_in, query=None, l_cell_idx=None, field_type="CELL", inverse_selection=False, verbose=False): """Returns a vtk polydata object as a subselection of an input polydata object Some words about indexes : Cells - CellId = index (of CellData and Polys (=connectivity and offset arrays)) = PK - vtkOriginalCellIds = index of original vtp (never changed, even after consecutive selections) - SelectionCellIds = index of previous selection(changes every selection step, allows you to go 1 level up) - vertexIndices = related point indices (=redundant = same as connectivity) = FK Points - PointId = index (of PointData and Points) = PK - vtkOriginalPointIds = index of original vtp (never changed, even after consecutive selections) - SelectionPointIds = index of previous selection(changes every selection step, allows you to go 1 level up) naming chosen as to comply with the paraview naming """ a_ix_cell = np.array([]) a_ix_point = np.array([]) wdo_in = dsa.WrapDataObject(poly_in) wdo_out = dsa.WrapDataObject(vtk.vtkPolyData()) if query: attributeType = set_attributetype(field_type) if verbose: print(wdo_in.GetAttributes(attributeType)) # d_attr_data = get_arrays(inputs[0].GetAttributes(attributeType)) attribs = wdo_in.GetAttributes(attributeType) # dict : key = 'attributename' , value = array of data d_attr_data = {key: attribs[key] for key in attribs.keys()} # add "id" array if the query string refers to id. if not "id" in d_attr_data.keys() and re.search(r'\bid\b', query): d_attr_data["id"] = _create_id_array(wdo_in, attributeType) try: # SELECTION :returns boolean mask maskArray = compute(wdo_in, query, ns=d_attr_data) except: print( "Error: Failed to evaluate Expression '%s'. " "The following exception stack should provide additional developer " "specific information. This typically implies a malformed " "expression. Verify that the expression is valid.\n", query) raise if not maskarray_is_valid(maskArray): raise RuntimeError( "Expression '%s' did not produce a valid mask array. The value " "produced is of the type '{0}'. This typically implies a malformed " "expression. Verify that the expression is valid. {1}".format( query, type(maskArray))) if inverse_selection: maskArray = algos.logical_not(maskArray) # returns indices of boolean mask nonzero_indices = algos.flatnonzero(maskArray) if field_type == "CELL": a_ix_cell = np.array(nonzero_indices) else: print("only cell based selections are supported right now.") return else: a_ix_cell = np.array(l_cell_idx) if not isinstance(a_ix_cell, np.ndarray) or a_ix_cell.size == 0: print('warning : nothing selected. None value will be returned') return None if field_type == "CELL": # STEP1 : Replace CellData nb_arrays = wdo_in.GetCellData().GetNumberOfArrays() if verbose: print("{0} arrays are present in {1}Data".format( nb_arrays, field_type)) for i in range(nb_arrays): vtk_array = wdo_in.GetAttributes( vtk.vtkDataObject.CELL).GetArray(i) attr_name = wdo_in.GetAttributes( vtk.vtkDataObject.CELL).GetArrayName(i) if attr_name == "SelectionCellIds": continue if a_ix_cell.size == 0: vtk_array_select = np.array([]) else: if isinstance(vtk_array.GetValue(0), str): # indexing not possible on vtkStringArray vtk_array_select = np.array( [vtk_array.GetValue(i) for i in a_ix_cell]) else: vtk_array_select = vtk_array[a_ix_cell] if attr_name == "vertexIndices": # not stored in output_poly, only used further down a_vtkOriginalPointIds = vtk_array_select.__array__() continue if verbose: print("{0}),{1},{2} ==> {3}".format(i, attr_name, vtk_array.size, vtk_array_select.size)) # wdo_out.GetAttributes(vtk.vtkDataObject.CELL).append(vtk_array_select,attr_name) if isinstance(vtk_array_select[0], str): add_array(wdo_out.VTKObject, vtk_array_select, attr_name, field_type="CELL", dtype='str') else: wdo_out.GetAttributes(vtk.vtkDataObject.CELL).append( vtk_array_select, attr_name) if verbose: print( wdo_out.GetAttributes( vtk.vtkDataObject.CELL)[attr_name], "compared to input : \n", wdo_in.GetAttributes( vtk.vtkDataObject.CELL)[attr_name]) # backup selectionIds to easily refer to the selection 1 level up wdo_out.GetAttributes(vtk.vtkDataObject.CELL).append( a_ix_cell, "SelectionCellIds") # at first selection, this column is newly added if isinstance(wdo_out.CellData['vtkOriginalCellIds'], dsa.VTKNoneArray): wdo_out.GetAttributes(vtk.vtkDataObject.CELL).append( a_ix_cell, "vtkOriginalCellIds") # STEP2 : Get points to be selected based on the cell selection # unique gives 1D SORTED ascending array a_ix_point = np.unique(a_vtkOriginalPointIds) d_oldPointId_newPointID = { old: new for new, old in enumerate(a_ix_point) } # STEP3 : Copy PointData nb_arrays = wdo_in.GetPointData().GetNumberOfArrays() if verbose: print("{0} arrays are present in CellData".format(nb_arrays)) for i in range(nb_arrays): vtk_array = wdo_in.GetAttributes( vtk.vtkDataObject.POINT).GetArray(i) attr_name = wdo_in.GetAttributes( vtk.vtkDataObject.POINT).GetArrayName(i) if attr_name == "SelectionPointIds": continue if a_ix_point.size == 0: vtk_array_select = np.array([]) else: vtk_array_select = vtk_array[a_ix_point] if verbose: print("{0}),{1},{2} ==> {3}".format(i, attr_name, vtk_array.size, vtk_array_select.size)) wdo_out.GetAttributes(vtk.vtkDataObject.POINT).append( vtk_array_select, attr_name) wdo_out.GetAttributes(vtk.vtkDataObject.POINT).append( a_ix_point, "SelectionPointIds") # backup original ids as extra column # at first selection, this column is newly added if isinstance(wdo_out.PointData['vtkOriginalPointIds'], dsa.VTKNoneArray): wdo_out.GetAttributes(vtk.vtkDataObject.POINT).append( a_ix_point, "vtkOriginalPointIds") # STEP4: Copy Points if a_ix_point.size != 0: wdo_out.Points = wdo_in.Points[a_ix_point] # STEP5: Construct Polygons (Cells) # wdo_out.Polygons = wdo_in.Polygons[a_ix_point] => not supported by wrapper, so use native VTK vtkCellArray = vtk.vtkCellArray() vertexIndices_new = [] for p1, p2, p3 in a_vtkOriginalPointIds: l_new_triangle = [ d_oldPointId_newPointID[p1], d_oldPointId_newPointID[p2], d_oldPointId_newPointID[p3] ] vtkCellArray.InsertNextCell(3, l_new_triangle) vertexIndices_new.append(l_new_triangle) wdo_out.VTKObject.SetPolys(vtkCellArray) # STEP6: update CellData vertexIndices wdo_out.GetAttributes(vtk.vtkDataObject.CELL).append( np.array(vertexIndices_new), "vertexIndices") if a_ix_point.size != 0: return wdo_out.VTKObject else: return None
def MST_tel_structure(): primary_reflector_diameter = 11.5 l = primary_reflector_diameter / (2 * (2**0.5)) x_points = [l, l, -l, -l] y_points = [-l, l, l, -l] appendFilter = vtk.vtkAppendPolyData() for i in range(4): input1 = vtk.vtkPolyData() # Create a cylinder. # Cylinder height vector is (0,1,0). # Cylinder center is in the middle of the cylinder cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetResolution(15) cylinderSource.SetRadius(0.1) cylinderSource.Update() # Generate a random start and end point startPoint = [x_points[i], y_points[i], 0] endPoint = [x_points[i] / 4, y_points[i] / 4, cam_height] rng = vtk.vtkMinimalStandardRandomSequence() rng.SetSeed(8775070) # For testing. normalizedX = [0, 0, 0] normalizedY = [0, 0, 0] normalizedZ = [0, 0, 0] # The X axis is a vector from start to end vtk.vtkMath.Subtract(endPoint, startPoint, normalizedX) length = vtk.vtkMath.Norm(normalizedX) vtk.vtkMath.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = [0, 0, 0] for i in range(0, 3): rng.Next() arbitrary[i] = rng.GetRangeValue(-10, 10) vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ) vtk.vtkMath.Normalize(normalizedZ) # The Y axis is Z cross X vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(0, 3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(startPoint) # translate to starting point transform.Concatenate(matrix) # apply direction cosines transform.RotateZ(-90.0) # align cylinder to x axis transform.Scale(1.0, length, 1.0) # scale along the height vector transform.Translate(0, .5, 0) # translate to start of cylinder transform.Update() # Transform the polydata transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(cylinderSource.GetOutputPort()) transformPD.Update() input1.ShallowCopy(transformPD.GetOutput()) appendFilter.AddInputData(input1) appendFilter.Update() cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(appendFilter.GetOutputPort()) cleanFilter.Update() # Create a mapper and actor for the arrow mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cleanFilter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.RotateY(90) actor.GetProperty().SetColor(tomato) return actor
def trk2vtkActor(trk, replace): # convert trk to vtkPolyData trk = np.transpose(np.asarray(trk)) numberOfPoints = trk.shape[0] points = vtk.vtkPoints() lines = vtk.vtkCellArray() colors = vtk.vtkFloatArray() colors.SetNumberOfComponents(4) colors.SetName("tangents") k = 0 lines.InsertNextCell(numberOfPoints) for j in range(numberOfPoints): points.InsertNextPoint(trk[j, :]) lines.InsertCellPoint(k) k = k + 1 if j < (numberOfPoints - 1): direction = trk[j + 1, :] - trk[j, :] direction = direction / np.linalg.norm(direction) colors.InsertNextTuple( np.abs([direction[0], direction[1], direction[2], 1])) else: colors.InsertNextTuple( np.abs([direction[0], direction[1], direction[2], 1])) trkData = vtk.vtkPolyData() trkData.SetPoints(points) trkData.SetLines(lines) trkData.GetPointData().SetScalars(colors) # make it a tube trkTube = vtk.vtkTubeFilter() trkTube.SetRadius(0.1) trkTube.SetNumberOfSides(4) trkTube.SetInputData(trkData) trkTube.Update() if replace: transx, transy, transz, rotx, roty, rotz = replace # create a transform that rotates the stl source transform = vtk.vtkTransform() transform.PostMultiply() transform.RotateX(rotx) transform.RotateY(roty) transform.RotateZ(rotz) transform.Translate(transx, transy, transz) transform_filt = vtk.vtkTransformPolyDataFilter() transform_filt.SetTransform(transform) transform_filt.SetInputConnection(trkTube.GetOutputPort()) transform_filt.Update() # mapper trkMapper = vtk.vtkPolyDataMapper() trkMapper.SetInputData(trkTube.GetOutput()) # actor trkActor = vtk.vtkActor() trkActor.SetMapper(trkMapper) return trkActor
def __init__(self, img_path, mask_path): self.peel = [] self.peelActors = [] T1_reader = vtk.vtkNIFTIImageReader() T1_reader.SetFileName(img_path) T1_reader.Update() # self.refImage = vtk.vtkImageData() self.refImage = T1_reader.GetOutput() mask_reader = vtk.vtkNIFTIImageReader() mask_reader.SetFileName(mask_path) mask_reader.Update() mc = vtk.vtkContourFilter() mc.SetInputConnection(mask_reader.GetOutputPort()) mc.SetValue(0, 1) mc.Update() refSurface = vtk.vtkPolyData() refSurface = mc.GetOutput() tmpPeel = vtk.vtkPolyData() tmpPeel = downsample(refSurface) mask_sFormMatrix = vtk.vtkMatrix4x4() mask_sFormMatrix = mask_reader.GetSFormMatrix() mask_ijk2xyz = vtk.vtkTransform() mask_ijk2xyz.SetMatrix(mask_sFormMatrix) mask_ijk2xyz_filter = vtk.vtkTransformPolyDataFilter() mask_ijk2xyz_filter.SetInputData(tmpPeel) mask_ijk2xyz_filter.SetTransform(mask_ijk2xyz) mask_ijk2xyz_filter.Update() tmpPeel = smooth(mask_ijk2xyz_filter.GetOutput()) tmpPeel = fixMesh(tmpPeel) tmpPeel = cleanMesh(tmpPeel) tmpPeel = upsample(tmpPeel) tmpPeel = smooth(tmpPeel) tmpPeel = fixMesh(tmpPeel) tmpPeel = cleanMesh(tmpPeel) # sFormMatrix = vtk.vtkMatrix4x4() qFormMatrix = T1_reader.GetQFormMatrix() # sFormMatrix = T1_reader.GetSFormMatrix() refImageSpace2_xyz_transform = vtk.vtkTransform() refImageSpace2_xyz_transform.SetMatrix(qFormMatrix) self.refImageSpace2_xyz = vtk.vtkTransformPolyDataFilter() self.refImageSpace2_xyz.SetTransform(refImageSpace2_xyz_transform) xyz2_refImageSpace_transform = vtk.vtkTransform() qFormMatrix.Invert() xyz2_refImageSpace_transform.SetMatrix(qFormMatrix) self.xyz2_refImageSpace = vtk.vtkTransformPolyDataFilter() self.xyz2_refImageSpace.SetTransform(xyz2_refImageSpace_transform) #self.currentPeel = vtk.vtkPolyData() self.currentPeel = tmpPeel self.currentPeelNo = 0 self.mapImageOnCurrentPeel() newPeel = vtk.vtkPolyData() newPeel.DeepCopy(self.currentPeel) self.peel.append(newPeel) self.currentPeelActor = vtk.vtkActor() self.getCurrentPeelActor() self.peelActors.append(self.currentPeelActor) self.numberOfPeels = 2 self.peelDown()
def main(): colors = vtk.vtkNamedColors() angle = 0 r1 = 50 r2 = 30 centerX = 10.0 centerY = 5.0 points = vtk.vtkPoints() idx = 0 while angle <= 2.0 * vtk.vtkMath.Pi() + (vtk.vtkMath.Pi() / 60.0): points.InsertNextPoint(r1 * math.cos(angle) + centerX, r2 * math.sin(angle) + centerY, 0.0) angle = angle + (vtk.vtkMath.Pi() / 60.0) idx += 1 line = vtk.vtkPolyLine() line.GetPointIds().SetNumberOfIds(idx) for i in range(0, idx): line.GetPointIds().SetId(i, i) lines = vtk.vtkCellArray() lines.InsertNextCell(line) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputData(polyData) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 100.0) extrude.Update() lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputData(polyData) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) lineActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(extrude.GetOutputPort()) back = vtk.vtkProperty() back.SetColor(colors.GetColor3d("Tomato")) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("Banana")) actor.SetBackfaceProperty(back) ren = vtk.vtkRenderer() ren.SetBackground(colors.GetColor3d("SlateGray")) ren.AddActor(actor) ren.AddActor(lineActor) renWin = vtk.vtkRenderWindow() renWin.SetWindowName("Elliptical Cylinder") renWin.AddRenderer(ren) renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) camera = vtk.vtkCamera() camera.SetPosition(0, 1, 0) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(0, 0, 1) camera.Azimuth(30) camera.Elevation(30) ren.SetActiveCamera(camera) ren.ResetCamera() ren.ResetCameraClippingRange() renWin.Render() iren.Start()
xy_trusses = [ truss1, truss2, itruss9, itruss10, itruss11, itruss12, truss3, truss4 ] yz_trusses = [ truss5, truss6, itruss1, itruss2, itruss3, itruss4, truss7, truss8 ] zx_trusses = [ truss9, truss10, itruss5, itruss6, itruss7, itruss8, truss11, truss12 ] #for diag in [truss1, truss2, truss3, truss4, truss5, truss6, truss7, truss8, truss9, truss10, truss11, truss12, itruss1, itruss3, itruss2, itruss4, itruss5, itruss7, itruss6, itruss8, itruss9, itruss10, itruss11, itruss12]: for truss_xy, truss_zy, truss_zx in zip(xy_trusses, yz_trusses, zx_trusses): i += 1 for j, diag in enumerate([truss_xy, truss_zx, truss_zy]): input1 = vtk.vtkPolyData() #draw line line.SetPoint1(diag[0]) line.SetPoint2(diag[1]) line.Update() #set tube radius tube.SetRadius(radius_scale * radius_tup[j]) tube.Update() input1.ShallowCopy(tube.GetOutput()) model.AddInputData(input1) model.Update() print("Number of cylinders {}".format(i))
def add_triangle( self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2, ): """ Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a line will be drawn at each edge edges_color: Color of the line for the edges edges_linewidth: Width of the line drawn for the edges """ points = vtk.vtkPoints() triangle = vtk.vtkTriangle() for ii in range(3): points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y, neighbors[ii].z) triangle.GetPointIds().SetId(ii, ii) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(trianglePolyData) ac = vtk.vtkActor() ac.SetMapper(mapper) ac.GetProperty().SetOpacity(opacity) if color == "element": if center is None: raise ValueError( "Color should be chosen according to the central atom, " "and central atom is not provided" ) # If partial occupations are involved, the color of the specie with # the highest occupation is used myoccu = 0.0 for specie, occu in center.species.items(): if occu > myoccu: myspecie = specie myoccu = occu color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]] ac.GetProperty().SetColor(color) else: ac.GetProperty().SetColor(color) if draw_edges: ac.GetProperty().SetEdgeColor(edges_color) ac.GetProperty().SetLineWidth(edges_linewidth) ac.GetProperty().EdgeVisibilityOn() self.ren.AddActor(ac)
def visualizeTriangulation(triangulation): # # importing point data from csv file vertices = [] # with open(r'vertices.csv') as file: # lines = file.readlines() # lines.pop(0) # for i, line in enumerate(lines): # line = line.split(',') # vertices.append(hstack((i, line))) for i, p in enumerate(triangulation.points): vertices.append(hstack((i, p, array([51, 153, 255])))) vertices = array(vertices) # importing triangle data from csv file triangles = [] # with open(r'triangles.csv') as file: # lines = file.readlines() # for i, line in enumerate(lines): # line = line.split(',') # triangles.append(hstack((i, line))) for i, tri in enumerate(triangulation.simplices): triangles.append(hstack((i, tri.Points[:, -1]))) triangles = array(triangles) # Initialize VTK triangulation.points object vtkPnt = vtk.vtkPoints() # Initialize color scalars pnt_rgb = vtk.vtkUnsignedCharArray() # R, G, B pnt_rgb.SetNumberOfComponents(3) # Colors?? pnt_rgb.SetName("Colors") # Initialize VTK PolyData object for vertices vtkVertex = vtk.vtkPolyData() # Initialize VTK PolyDataobject for triangulation vtkTri = vtk.vtkPolyData() # Initialize VTK vertices object for triangulation.points vtkVertex_ind = vtk.vtkCellArray() # Initialize VTK vertices object for triangles vtkTri_ind = vtk.vtkCellArray() # Setting up the vtkPoints and scalars for pnt in vertices: # Inserting the i-th point to the vtkPoints object rgb = pnt[4:7].astype(int) pnt = pnt.astype(float) id = vtkPnt.InsertNextPoint(pnt[1], pnt[2], pnt[3]) # Adding color for the i-th point pnt_rgb.InsertNextTuple3(rgb[0], rgb[1], rgb[2]) # Adding the index of i-th point to vertex vtk index array vtkVertex_ind.InsertNextCell(1) vtkVertex_ind.InsertCellPoint(id) # Set vtkpoint in triangle poly data object vtkTri.SetPoints(vtkPnt) # Add color to the vtkTri object vtkTri.GetPointData().SetScalars(pnt_rgb) # Set vtkpoint in vertexes poly data object vtkVertex.SetPoints(vtkPnt) vtkVertex.SetVerts(vtkVertex_ind) # Add color to the vtkVertex object vtkVertex.GetPointData().SetScalars(pnt_rgb) # Setting up the vtkPolyData and scalars for tri in triangles: # Set triangle's 3 vertices by ID ith_tri = vtk.vtkTriangle() ith_tri.GetPointIds().SetId(0, int(tri[1])) ith_tri.GetPointIds().SetId(1, int(tri[2])) ith_tri.GetPointIds().SetId(2, int(tri[3])) # Insert the i-th triangle data index vtkTri_ind.InsertNextCell(ith_tri) # Finishing up VTK pipeline # Initialize a VTK mapper vtkMapper = vtk.vtkPolyDataMapper() vtkMapper.SetInputData(vtkVertex) vtkTri.SetPolys(vtkTri_ind) vtkMapper.SetInputData(vtkTri) # Initialize a VTK actor vtkActor = vtk.vtkActor() vtkActor.SetMapper(vtkMapper) # Initialize a VTK render window vtkRenderWindow = vtk.vtkRenderWindow() # Initialize a VTK renderer # Contains the actors to render vtkRenderer = vtk.vtkRenderer() # Add the VTK renderer to the VTK render window vtkRenderWindow.AddRenderer(vtkRenderer) # define the renderer vtkRenderer.AddActor(vtkActor) vtkActor.GetProperty().LightingOn() #vtkActor.GetProperty().SetRepresentationToWireframe() #vtkActor.GetProperty().SetRepresentationToPoints() # # Set camera and background data vtkRenderer.ResetCamera() vtkRenderWindow.Render() # Enable user interface interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(vtkRenderWindow) vtkRenderWindow.Render() interactor.Start()
#!/usr/bin/python import vtk density = vtk.vtkGaussianCubeReader() density.SetFileName("crown.den.cube") density.Update() grid = density.GetGridOutput() planeWidget = vtk.vtkPlaneWidget() planeWidget.SetInputData(grid) planeWidget.NormalToZAxisOn() planeWidget.SetResolution(30) planeWidget.PlaceWidget() plane = vtk.vtkPolyData() planeWidget.GetPolyData(plane) probe = vtk.vtkProbeFilter() probe.SetInputData(plane) probe.SetSourceData(grid) # Update probe filter to get valid scalar range probe.Update() scalar_range = probe.GetOutput().GetScalarRange() lut = vtk.vtkLookupTable() lut.SetTableRange(scalar_range) lut.SetScaleToLog10() mapper = vtk.vtkPolyDataMapper()
for pt in lst: pts.InsertNextPoint( pt ) verts = vtk.vtkCellArray() verts.InsertNextCell(4) for i in range(4): verts.InsertCellPoint(i) lines = vtk.vtkCellArray() lines.InsertNextCell(4) for i in range(4,8): lines.InsertCellPoint(i) polys = vtk.vtkCellArray() polys.InsertNextCell(4) for i in range(8,12): polys.InsertCellPoint(i) PD = vtk.vtkPolyData() PD.SetPoints(pts) PD.SetVerts(verts) PD.SetLines(lines) PD.SetPolys(polys) PDA = Show(PD,(-3,-4, .1)) P = PDA.GetProperty() P.SetEdgeColor(1,0,0) P.SetPointSize(3) # vtkUnstructuredGrid example points = vtk.vtkPoints() UG = vtk.vtkUnstructuredGrid() UG.SetPoints(points)
scalar = vtk.vtkFloatArray() v = 1 for coord in coords: pts.InsertNextPoint(coord[0], coord[1], coord[2]) scalar.InsertNextValue(v) v += v cells = [[3, 2, 1, 0], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7], [4, 5, 6, 7]] polys = vtk.vtkCellArray() for cell in cells: polys.InsertNextCell(4) for pid in cell: polys.InsertCellPoint(pid) poly = vtk.vtkPolyData() poly.SetPoints(pts) poly.SetPolys(polys) poly.GetPointData().SetScalars(scalar) mbd = vtk.vtkMultiBlockDataSet() mbd.SetNumberOfBlocks(1) mbd.SetBlock(0, poly) m = vtk.vtkCompositePolyDataMapper2() m.SetInputDataObject(mbd) m.SetScalarModeToUsePointData() # Override scalar representation with solid color a = vtk.vtkActor() a.SetMapper(m)
import vtk # Create the geometry of a point (the coordinate) points = vtk.vtkPoints() p = [1.0, 2.0, 3.0] # Create the topology of the point (a vertex) vertices = vtk.vtkCellArray() id = points.InsertNextPoint(p) vertices.InsertNextCell(1) vertices.InsertCellPoint(id) # Create a polydata object point = vtk.vtkPolyData() # Set the points and vertices we created as the geometry and topology of the polydata point.SetPoints(points) point.SetVerts(vertices) # Visualize mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(point) else: mapper.SetInputData(point) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetPointSize(20)