def createGlyph(self): self.polyData = vtk.vtkPolyData() points = vtk.vtkPoints() lines = vtk.vtkCellArray() self.polyData.SetPoints( points ) self.polyData.SetLines( lines ) prevPoint = None firstPoint = None for x,y in ((0,0),)*4: p = points.InsertNextPoint( x, y, 0 ) if prevPoint is not None: idList = vtk.vtkIdList() idList.InsertNextId( prevPoint ) idList.InsertNextId( p ) self.polyData.InsertNextCell( vtk.VTK_LINE, idList ) prevPoint = p if firstPoint is None: firstPoint = p # make the last line in the polydata idList = vtk.vtkIdList() idList.InsertNextId( p ) idList.InsertNextId( firstPoint ) self.polyData.InsertNextCell( vtk.VTK_LINE, idList )
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 Frechet_distances_2(input_vtk_polydata_n, input_vtk_polydata_m): # compute Frechet distance from an array of fibers to another array number_of_lines_m = input_vtk_polydata_m.GetNumberOfLines() number_of_lines_n = input_vtk_polydata_n.GetNumberOfLines() all_fibers_m = range(0,number_of_lines_m) all_fibers_n = range(0,number_of_lines_n) distances = numpy.zeros([number_of_lines_m,number_of_lines_n]) #input_vtk_polydata2 = input_vtk_polydata input_vtk_polydata_m.GetLines().InitTraversal() line1_ptids = vtk.vtkIdList() inpoints1 = input_vtk_polydata_m.GetPoints() inpoints2 = input_vtk_polydata_n.GetPoints() for lidx1 in all_fibers_m: input_vtk_polydata_m.GetLines().GetNextCell(line1_ptids) input_vtk_polydata_n.GetLines().InitTraversal() line2_ptids = vtk.vtkIdList() for lidx2 in all_fibers_n: input_vtk_polydata_n.GetLines().GetNextCell(line2_ptids) distances[lidx1,lidx2] = _frechet_distance_internal_use(inpoints1,inpoints2,line1_ptids,line2_ptids) return distances
def getNumberOfPointsSharedByTwoCells( pd, iCell1, iCell2 ): '''Compute the number of shared points between iCell1 and iCell2 in the vtkPolyData pd.''' cell1_points = vtk.vtkIdList() pd.GetCellPoints( iCell1, cell1_points ) cell2_points = vtk.vtkIdList() pd.GetCellPoints( iCell2, cell2_points ) cell1_points.IntersectWith( cell2_points ) return cell1_points.GetNumberOfIds()
def __init__(self): self._Surface = None self._SeedIds = None self._SourceSeedIds = vtk.vtkIdList() self._TargetSeedIds = vtk.vtkIdList() self.PrintError = None self.PrintLog = None self.InputText = None self.OutputText = None
def VtkLoadElemMesh(self,field,defFScale=0.0,eigenMode=None): '''Load the element mesh :param field: scalar field to be represented :param defFScale: factor to apply to current displacement of nodes so that the display position of each node equals to the initial position plus its displacement multiplied by this factor. In case of modal analysis, the displayed position of each node equals to the initial position plus its eigenVector multiplied by this factor. (Defaults to 0.0, i.e. display of initial/undeformed shape) :param eigenMode: eigenvibration mode if we want to display the deformed shape associated with it when a modal analysis has been carried out. Defaults to None: no modal analysis. ''' # Define grid self.nodes= vtk.vtkPoints() self.gridRecord.uGrid= vtk.vtkUnstructuredGrid() self.gridRecord.uGrid.SetPoints(self.nodes) eSet= self.gridRecord.xcSet eSet.numerate() self.gridRecord.uGrid.name= eSet.name+'_grid' # Scalar values. nodeSet= eSet.getNodes if(field): arr= field.fillArray(nodeSet) field.creaLookUpTable() # Load nodes in vtk setNodes= eSet.getNodes if eigenMode==None: for n in setNodes: pos= n.getCurrentPos3d(defFScale) self.nodes.InsertPoint(n.getIdx,pos.x,pos.y,pos.z) else: for n in setNodes: pos= n.getEigenPos3d(defFScale,eigenMode) self.nodes.InsertPoint(n.getIdx,pos.x,pos.y,pos.z) # Load elements in vtk setElems= eSet.getElements for e in setElems: vertices= xc_base.vector_int_to_py_list(e.getIdxNodes) vtx= vtk.vtkIdList() for vIndex in vertices: vtx.InsertNextId(vIndex) if(e.getVtkCellType!= vtk.VTK_VERTEX): self.gridRecord.uGrid.InsertNextCell(e.getVtkCellType,vtx) setConstraints= eSet.getConstraints for c in setConstraints: vtx= vtk.vtkIdList() vtx.InsertNextId(c.getNodeIdx) if(c.getVtkCellType!= vtk.VTK_LINE): self.gridRecord.uGrid.InsertNextCell(c.getVtkCellType,vtx)
def createGlyph(self, polyData): """ create a brush circle of the right radius in XY space - assume uniform scaling between XY and RAS which is enforced by the view interactors """ sliceNode = self.sliceWidget.sliceLogic().GetSliceNode() self.rasToXY.DeepCopy(sliceNode.GetXYToRAS()) self.rasToXY.Invert() maximum, maxIndex = 0,0 for index in range(3): if abs(self.rasToXY.GetElement(0, index)) > maximum: maximum = abs(self.rasToXY.GetElement(0, index)) maxIndex = index point = [0, 0, 0, 0] point[maxIndex] = self.radius xyRadius = self.rasToXY.MultiplyPoint(point) import math xyRadius = math.sqrt( xyRadius[0]**2 + xyRadius[1]**2 + xyRadius[2]**2 ) if self.pixelMode: xyRadius = 0.01 # make a circle paint brush points = vtk.vtkPoints() lines = vtk.vtkCellArray() polyData.SetPoints(points) polyData.SetLines(lines) PI = 3.1415926 TWOPI = PI * 2 PIoverSIXTEEN = PI / 16 prevPoint = -1 firstPoint = -1 angle = 0 while angle <= TWOPI: x = xyRadius * math.cos(angle) y = xyRadius * math.sin(angle) p = points.InsertNextPoint( x, y, 0 ) if prevPoint != -1: idList = vtk.vtkIdList() idList.InsertNextId(prevPoint) idList.InsertNextId(p) polyData.InsertNextCell( vtk.VTK_LINE, idList ) prevPoint = p if firstPoint == -1: firstPoint = p angle = angle + PIoverSIXTEEN # make the last line in the circle idList = vtk.vtkIdList() idList.InsertNextId(p) idList.InsertNextId(firstPoint) polyData.InsertNextCell( vtk.VTK_LINE, idList )
def create_cylinder(r=.5, h=1., res=30): pts = vtk.vtkPoints() pts.SetNumberOfPoints(10*res) pd = vtk.vtkPolyData() pd.Allocate(3*res, 1) ang = 2*math.pi/res ind = 0 for sign in [-1, 1]: y = sign*h/2 for i in range(res): c0, s0 = math.cos(i*ang), math.sin(i*ang) c1, s1 = math.cos((i+1)*ang), math.sin((i+1)*ang) x0, z0 = round(r*c0, 6), round(r*s0, 6) x1, z1 = round(r*c1, 6), round(r*s1, 6) pts.InsertPoint(ind, 0, y, 0) pts.InsertPoint(ind+1, x0, y, z0) pts.InsertPoint(ind+2, x1, y, z1) tri = vtk.vtkIdList() [ tri.InsertNextId(ind+j) for j in range(3) ] t = pd.InsertNextCell(vtk.VTK_TRIANGLE, tri) ind += 3 if sign == 1: pd.ReverseCell(t) pts.InsertPoint(ind, x0, -h/2, z0) pts.InsertPoint(ind+1, x0, y, z0) pts.InsertPoint(ind+2, x1, y, z1) pts.InsertPoint(ind+3, x1, -h/2, z1) poly = vtk.vtkIdList() [ poly.InsertNextId(ind+j) for j in range(4) ] pd.InsertNextCell(vtk.VTK_POLYGON, poly) ind += 4 pd.SetPoints(pts) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) return prod
def getDual( pd ): '''Get the dual of a vtkPolyData. The finite parts only.''' pd.BuildLinks() cells = vtk.vtkCellArray() points = vtk.vtkPoints() for iPt in range(pd.GetNumberOfPoints()): neighbor_cellIds = vtk.vtkIdList() pd.GetPointCells( iPt, neighbor_cellIds ) if neighbor_cellIds.GetNumberOfIds() < 3: continue # sort the neighbor_cellIds into a ring around iPt sorted_neighbor_cellIds = [ neighbor_cellIds.GetId( 0 ) ] for it in range( neighbor_cellIds.GetNumberOfIds() - 1 ): for iicell in range( 1, neighbor_cellIds.GetNumberOfIds() ): icell = neighbor_cellIds.GetId( iicell ) if icell in sorted_neighbor_cellIds: continue # does this cell share exactly two vertices with the last one in the list? if getNumberOfPointsSharedByTwoCells( pd, sorted_neighbor_cellIds[-1], icell ) == 2: sorted_neighbor_cellIds += [ icell ] break if len( sorted_neighbor_cellIds ) < neighbor_cellIds.GetNumberOfIds(): continue # was a boundary vertex or non-manifold if not getNumberOfPointsSharedByTwoCells( pd, sorted_neighbor_cellIds[-1], sorted_neighbor_cellIds[0] ) == 2: continue # boundary vertex, in the case where cell id 0 was on the boundary # make a face around this vertex: a new point at each centroid of the neighboring cells cells.InsertNextCell( neighbor_cellIds.GetNumberOfIds() ) for id in sorted_neighbor_cellIds: # find centroid of this cell neighbor_verts = vtk.vtkIdList() pd.GetCellPoints( id, neighbor_verts ) c = (0,0,0) for iiv in range(neighbor_verts.GetNumberOfIds()): iv = neighbor_verts.GetId(iiv) p = pd.GetPoint( iv ) c = add( c, p ) c = mul( c, 1.0 / neighbor_verts.GetNumberOfIds() ) # insert the centroid as a point and as an index into the new face cells.InsertCellPoint( points.InsertNextPoint( c ) ) dual_pd = vtk.vtkPolyData() dual_pd.SetPoints( points ) dual_pd.SetPolys( cells ) # merge duplicate points cleaner = vtk.vtkCleanPolyData() if vtk.vtkVersion.GetVTKMajorVersion() >= 6: cleaner.SetInputData( dual_pd ) else: cleaner.SetInput( dual_pd ) cleaner.SetTolerance(0.0001) cleaner.Update() return cleaner.GetOutput()
def __get_common_cells(self,p1,p2,exclude=-1): """ Get all the cells containing p1 and p2 """ cell_list_1 = vtk.vtkIdList() self.__vtk_model.GetPointCells(p1,cell_list_1) nb_ids = cell_list_1.GetNumberOfIds() cell_list_1 = [cell_list_1.GetId(j) for j in xrange(nb_ids)] cell_list_2 = vtk.vtkIdList() self.__vtk_model.GetPointCells(p2,cell_list_2) nb_ids = cell_list_2.GetNumberOfIds() cell_list_2 = [cell_list_2.GetId(j) for j in xrange(nb_ids)] common_cells = [cell for cell in cell_list_1 if cell in cell_list_2 and cell!=exclude] return common_cells
def GetConnectedVertices(self, connectedVerticesIDList, polyData, pointID): # Return IDs of all the vertices that compose the first neighbor. cellList = vtk.vtkIdList() connectedVerticesIDList.InsertUniqueId(pointID) # Get cells that vertex 'pointID' belongs to polyData.GetPointCells(pointID, cellList) numberOfIds = cellList.GetNumberOfIds() for i in range(0, numberOfIds): # Get points which compose all cells pointIdList = vtk.vtkIdList() polyData.GetCellPoints(cellList.GetId(i), pointIdList) for j in range(0, pointIdList.GetNumberOfIds()): connectedVerticesIDList.InsertUniqueId(pointIdList.GetId(j)) return connectedVerticesIDList
def generateMesh(self, x, y, z, in_x, in_y, in_z): x_coord = vtk.vtkFloatArray() x_coord.InsertNextValue(x) y_coord = vtk.vtkFloatArray() y_coord.InsertNextValue(y) z_coord = vtk.vtkFloatArray() z_coord.InsertNextValue(z) grid = vtk.vtkRectilinearGrid() grid.SetDimensions(self.nx if in_x else 1, self.ny if in_y else 1, self.nz if in_z else 1) grid.SetXCoordinates(self.x_coords if in_x else x_coord); grid.SetYCoordinates(self.y_coords if in_y else y_coord); grid.SetZCoordinates(self.z_coords if in_z else z_coord); # We're going to generate all of the IDs of the cells in that rectilinear grid so we can extract them as an UnstructuredGrid # Why would we do such a thing? Because there is some bug associated with RecitilinearGrids and clipping / rendering # So, instead I'm going to use RectilinearGrid for generating the cells and then "copy" it to an UnstructuredGrid using ExtractCells num_cells = grid.GetNumberOfCells() id_list = vtk.vtkIdList() for i in xrange(num_cells): id_list.InsertNextId(i) extract = vtk.vtkExtractCells() if vtk.VTK_MAJOR_VERSION <= 5: extract.SetInput(grid) else: extract.SetInputData(grid) extract.SetCellList(id_list) return extract.GetOutput()
def testStartingWithTwoCells(): points = vtk.vtkPoints() points.InsertNextPoint((0., 0., 0.)) points.InsertNextPoint((2., 0., 0.)) points.InsertNextPoint((2., 1., 0.)) points.InsertNextPoint((0., 1., 0.)) 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, 2) ptIds.SetId(1, 3) ptIds.SetId(2, 0) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) rs = RefineSurface(pdata) rs.refine(max_edge_length=1.1) assert(rs.getVtkPolyData().GetNumberOfPolys() == 8)
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 convert_to_polydata(self): """Convert fiber array to vtkPolyData object.""" outpd = vtk.vtkPolyData() outpoints = vtk.vtkPoints() outlines = vtk.vtkCellArray() outlines.InitTraversal() for lidx in range(0, self.number_of_fibers): cellptids = vtk.vtkIdList() for pidx in range(0, self.points_per_fiber): idx = outpoints.InsertNextPoint(self.fiber_array_r[lidx, pidx], self.fiber_array_a[lidx, pidx], self.fiber_array_s[lidx, pidx]) cellptids.InsertNextId(idx) outlines.InsertNextCell(cellptids) # put data into output polydata outpd.SetLines(outlines) outpd.SetPoints(outpoints) return outpd
def _findAndSetGeometryReference(self, referencedSeriesUID, segmentationNode): shn = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(slicer.mrmlScene) segID = shn.GetItemByDataNode(segmentationNode) parentID = shn.GetItemParent(segID) childIDs = vtk.vtkIdList() shn.GetItemChildren(parentID, childIDs) uidName = slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMUIDName() matches = [] for childID in reversed([childIDs.GetId(id) for id in range(childIDs.GetNumberOfIds()) if segID]): if childID == segID: continue if shn.GetItemUID(childID, uidName) == referencedSeriesUID: if shn.GetItemDataNode(childID): matches.append(shn.GetItemDataNode(childID)) reference = None if len(matches): if any(x.GetAttribute("DICOM.RWV.instanceUID") is not None for x in matches): for x in matches: if x.GetAttribute("DICOM.RWV.instanceUID") is not None: reference = x break else: reference = matches[0] if reference: segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(reference)
def pd_to_array(inpd, dims=225): count_vol = numpy.ndarray([dims,dims,dims]) ptids = vtk.vtkIdList() points = inpd.GetPoints() data_vol = [] # check for cell data cell_data = inpd.GetCellData().GetScalars() if cell_data: data_vol = numpy.ndarray([dims,dims,dims]) # loop over lines inpd.GetLines().InitTraversal() print "<filter.py> Input number of points: ",\ points.GetNumberOfPoints(),\ "lines:", inpd.GetNumberOfLines() # loop over all lines for lidx in range(0, inpd.GetNumberOfLines()): # progress #if verbose: # if lidx % 1 == 0: # print "<filter.py> Line:", lidx, "/", inpd.GetNumberOfLines() inpd.GetLines().GetNextCell(ptids) num_points = ptids.GetNumberOfIds() for pidx in range(0, num_points): point = points.GetPoint(ptids.GetId(pidx)) # center so that 0,0,0 moves to 100,100,100 point = numpy.round(numpy.array(point) + 110) count_vol[point[0], point[1], point[2]] += 1 if cell_data: data_vol[point[0], point[1], point[2]] += cell_data.GetTuple(lidx)[0] return count_vol, data_vol
def array2vtkIdList(num_array, vtk_idlist=None): """Converts a numpy array/Python list to a vtkIdList object. Parameters ---------- - num_array : numpy array or Python list/tuple The input array must be 2D with `shape[1] == 3`. - vtk_idlist : `vtkIdList` (default: `None`) If an optional `vtkIdList` instance, is passed as an argument then a new array is not created and returned. The passed array is itself modified and returned. """ if vtk_idlist: ids = vtk_idlist else: ids = vtk.vtkIdList() arr = numpy.asarray(num_array) assert len(arr.shape) == 1, "Array for vtkIdList must be 1D" ids.SetNumberOfIds(len(arr)) for i, j in enumerate(arr): ids.SetId(i, j) return ids
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 compute_max_array_along_lines(pd, array_name, output_array_name): lines = pd.GetLines() point_array = pd.GetPointData().GetArray(array_name) point_array_max = vtk.vtkFloatArray() point_array_lines_list = list() point_array_max_list = list() lines.InitTraversal() for lidx in range(0, pd.GetNumberOfLines()): if (lidx % 100) == 0: print lidx, '/', pd.GetNumberOfLines() pts = vtk.vtkIdList() lines.GetNextCell(pts) # compute mean POINT_ARRAY for this line if pts.GetNumberOfIds(): point_array_list = list() for pidx in range(0, pts.GetNumberOfIds()): point_array_list.append(point_array.GetTuple1(pts.GetId(pidx))) point_array_max.InsertNextTuple1(numpy.max(numpy.array(point_array_list))) #fa_max.InsertNextTuple1(numpy.median(numpy.array(fa_list))) else: point_array_max.InsertNextTuple1(0.0) point_array_max.SetName(output_array_name) outpd = pd outpd.GetCellData().AddArray(point_array_max) outpd.GetCellData().SetActiveScalars(output_array_name) return outpd
def ReadTecplotSurfaceFile(self): self.PrintLog('Reading Tecplot surface file.') f=open(self.InputFileName, 'r') line = f.readline() if line.split()[0] == 'TITLE': line = f.readline() if (line.split()[0] == 'VARIABLES') | (line.split('=')[0] == 'VARIABLES'): arrayNames = line.split('=')[1].strip().split(',') arrayNames[0:3] = [] self.PrintLog("ArrayNames" + str(arrayNames)) line = f.readline() if line.split()[0] == 'ZONE': lineNid = line.find('N=') lineN = line[lineNid : lineNid+line[lineNid:].find(',') ].split('=')[1] numberOfNodes = int(lineN) lineEid = line.find('E=') lineE = line[lineEid : lineEid+line[lineEid:].find(',') ].split('=')[1] numberOfElements = int(lineE) elementType = 'TRIANGLE' if line.find('ET=') != -1: if 'TRIANGLE' in line: elementType = 'TRIANGLE' elif 'QUADRILATERAL' in line: elementType = 'QUADRILATERAL' self.PrintLog("Reading " + str(numberOfNodes)+" nodes.") points = vtk.vtkPoints() cells = vtk.vtkCellArray() points.SetNumberOfPoints(numberOfNodes) self.Surface = vtk.vtkPolyData() self.Surface.SetPoints(points) self.Surface.SetPolys(cells) for arrayName in arrayNames: array = vtk.vtkDoubleArray() array.SetName(arrayName) array.SetNumberOfTuples(numberOfNodes) self.Surface.GetPointData().AddArray(array) self.Surface.Update() data = f.read().split() dataCounter = 0 for i in range(numberOfNodes): point = [float(data[dataCounter]),float(data[dataCounter+1]),float(data[dataCounter+2])] dataCounter += 3 points.SetPoint(i,point) for j in range(len(arrayNames)): self.Surface.GetPointData().GetArray(arrayNames[j]).SetComponent(i,0,float(data[dataCounter])) dataCounter += 1 self.PrintLog("Reading " + str(numberOfElements)+" elements.") cellIds = vtk.vtkIdList() for i in range(numberOfElements): cellIds.Initialize() cellIds.InsertNextId(int(data[dataCounter])-1) dataCounter += 1 cellIds.InsertNextId(int(data[dataCounter])-1) dataCounter += 1 cellIds.InsertNextId(int(data[dataCounter])-1) dataCounter += 1 if elementType == "QUADRILATERAL": cellIds.InsertNextId(int(data[dataCounter])-1) dataCounter += 1 cells.InsertNextCell(cellIds)
def testStartingWithTwoCells(): points = vtk.vtkPoints() points.InsertNextPoint((0., 0., 0.)) points.InsertNextPoint((2., 0., 0.)) points.InsertNextPoint((2., 1., 0.)) points.InsertNextPoint((0., 1., 0.)) 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, 2) ptIds.SetId(1, 3) ptIds.SetId(2, 0) pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds) rs = CoarsenSurface(pdata) rs.coarsen(min_cell_area=1.e-5) assert(rs.getVtkPolyData().GetNumberOfPolys() == 2)
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 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 __init__(self): vmtkSeedSelector.__init__(self) self.PickedSeedIds = vtk.vtkIdList() self.PickedSeeds = vtk.vtkPolyData() self.vmtkRenderer = None self.OwnRenderer = 0 self.Script = None
def __init__(self, pdata, max_edge_length, order=5): """ Constructor @param pdata instance of vtkPolyData @param max_edge_length maximum edge length, used to turn polygons into triangles """ # triangulate rs = RefineSurface(pdata) rs.refine(max_edge_length=max_edge_length) self.pdata = rs.getVtkPolyData() # store the point indices for each cell self.ptIdList = [] ptIds = vtk.vtkIdList() polys = self.pdata.GetPolys() polys.InitTraversal() for i in range(polys.GetNumberOfCells()): polys.GetNextCell(ptIds) assert(ptIds.GetNumberOfIds() == 3) self.ptIdList.append([ptIds.GetId(0), ptIds.GetId(1), ptIds.GetId(2)]) self.points = self.pdata.GetPoints() self.polys = self.pdata.GetPolys() self.numTriangles = self.polys.GetNumberOfCells() # order of the integration, method dependent self.order = order # set in the derived classes self.responseName = 'NO-SET' self.sourceName = 'NOT-SET'
def setSourceFromExpression(self, expression): """ Set the source from expression @param expression expression of x, y, and z """ from math import sqrt, pi, sin, cos, tan, log, exp n = self.pdata.GetNumberOfPolys() sourceData = vtk.vtkDoubleArray() sourceData.SetNumberOfComponents(1) sourceData.SetNumberOfTuples(n) sourceData.SetName(self.sourceName) midPoint = numpy.zeros((3,), numpy.float64) ptIds = vtk.vtkIdList() cells = self.pdata.GetPolys() cells.InitTraversal() for i in range(n): cell = cells.GetNextCell(ptIds) npts = ptIds.GetNumberOfIds() midPoint *= 0 # reset for j in range(npts): midPoint += self.points.GetPoint(ptIds.GetId(j)) midPoint /= float(npts) x, y, z = midPoint v = eval(expression) sourceData.SetTuple(i, [v]) self.pdata.GetCellData().AddArray(sourceData)
def extrude (pts, z, h): cell = vtk.vtkIdList() vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() [ (vtk_pts.InsertNextPoint(pt[0], pt[1], z), cell.InsertNextId(i)) for i, pt in enumerate(pts) ] pd = vtk.vtkPolyData() pd.Allocate(1, 1) pd.SetPoints(vtk_pts) pd.InsertNextCell(vtk.VTK_POLYGON, cell) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) extr = vtk.vtkLinearExtrusionFilter() extr.SetInputConnection(prod.GetOutputPort()) extr.SetVector(0, 0, h) pn = vtk.vtkPolyDataNormals() pn.SetInputConnection(extr.GetOutputPort()) pn.AutoOrientNormalsOn() return pn
def convertFiducialHierarchyToVtkIdList(hierarchyNode,volumeNode): outputIds = vtk.vtkIdList() if not hierarchyNode or not volumeNode: return outputIds if isinstance(hierarchyNode,slicer.vtkMRMLMarkupsFiducialNode) and isinstance(volumeNode,slicer.vtkMRMLScalarVolumeNode): image = volumeNode.GetImageData() # now we have the children which are fiducialNodes - let's loop! for n in range(hierarchyNode.GetNumberOfFiducials()): currentCoordinatesRAS = [0,0,0] # grab the current coordinates hierarchyNode.GetNthFiducialPosition(n,currentCoordinatesRAS) # convert the RAS to IJK currentCoordinatesIJK = LevelSetSegmentationWidget.ConvertRAStoIJK(volumeNode,currentCoordinatesRAS) # strip the last element since we need a 3based tupel currentCoordinatesIJKlist = (int(currentCoordinatesIJK[0]),int(currentCoordinatesIJK[1]),int(currentCoordinatesIJK[2])) outputIds.InsertNextId(int(image.ComputePointId(currentCoordinatesIJKlist))) # IdList was created, return it even if it might be empty return outputIds
def cpnonzerocolor(data): CellIdList = vtk.vtkIdList() CellIdList.Reset() colors = data.GetCellData().GetScalars() count = 0 # Get indices from nonzero colored cells for i in range(data.GetNumberOfCells()): if ( colors.GetTuple(i) != (0.0, 0.0, 0.0, 0.0) ): CellIdList.InsertId(count, i) count = count + 1 # print "Number Of cell:\t",i # print "Number of cell added:\t",count else: pass # Extract cells with nonzero color from data extractor = vtk.vtkExtractCells() extractor.SetInputData(data) extractor.SetCellList(CellIdList) extractor.Modified() extractor.Update() print "Number of nodes in clipped subvolume:\t",extractor.GetOutput().GetNumberOfPoints() print "Number of egdes in clipped subvolume:\t",extractor.GetOutput().GetNumberOfCells() # rearrange the id's of the cells and points - consecutive increasing ids print "...extracted zerocolor cells." return extractor.GetOutput()
def add_point_data_array(inpd, data, array_name): """Make a vtk point data array from input data array and add to inpd. Input data must have dimensions of the number of lines in the input polydata. The output array will be added to the polydata and will be point data, so the per-line values will be duplicated to become per-point values (each point on the line) for visualization. """ ptids = vtk.vtkIdList() inpd.GetLines().InitTraversal() outarray = vtk.vtkFloatArray() outarray.SetName(array_name) for lidx in range(0, inpd.GetNumberOfLines()): inpd.GetLines().GetNextCell(ptids) for pidx in range(0, ptids.GetNumberOfIds()): outarray.InsertNextTuple1(data[lidx]) inpd.GetPointData().AddArray(outarray)
def getCellValue(vtkSGrid2D, newPoint2D, cellID, valarray): pcoords = [0.0, 0.0, 0.0] weights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] clspoint = [0., 0., 0.] tmpid = vtk.mutable(0) vtkid2 = vtk.mutable(0) vtkcell2D = vtk.vtkQuad() vtkcell2D = vtkSGrid2D.GetCell(cellID) tmpres = vtkcell2D.EvaluatePosition(newPoint2D, clspoint, tmpid, pcoords, vtkid2, weights) # print(newPoint2D, clspoint, tmpid, pcoords, vtkid2, weights) idlist1 = vtk.vtkIdList() numpts = vtkcell2D.GetNumberOfPoints() idlist1 = vtkcell2D.GetPointIds() tmpVal = 0.0 for x in range(0, numpts): tmpVal = tmpVal + weights[x] * valarray.GetTuple(idlist1.GetId(x))[0] return tmpVal
def measure_line_lengths(inpd): ptids = vtk.vtkIdList() points = inpd.GetPoints() output_lengths = numpy.zeros(inpd.GetNumberOfLines()) # loop over lines inpd.GetLines().InitTraversal() print("<filter.py> Input number of points: ",\ points.GetNumberOfPoints(),\ "lines:", inpd.GetNumberOfLines()) # loop over all lines for lidx in range(0, inpd.GetNumberOfLines()): # progress #if verbose: # if lidx % 1 == 0: # print "<filter.py> Line:", lidx, "/", inpd.GetNumberOfLines() inpd.GetLines().GetNextCell(ptids) output_lengths[lidx] = ptids.GetNumberOfIds() return (output_lengths)
def read_vtk(self, datadir='data', file_name='spines.vtk'): """ Read the spines from a vtk file. call signature: read_vtk(datadir='data', file_name='spines.vtk') Arguments: *datadir*: Target data directory. *file_name*: Target file name. """ import numpy as np import os as os try: import vtk as vtk except: print("Warning: no vtk library found.") reader = vtk.vtkPolyDataReader() reader.SetFileName(os.path.join(datadir, file_name)) reader.Update() output = reader.GetOutput() # Read the spines. points = output.GetPoints() cells = output.GetLines() id_list = vtk.vtkIdList() self.spines = [] offset = 0 for cell_idx in range(cells.GetNumberOfCells()): cells.GetNextCell(id_list) n_points = id_list.GetNumberOfIds() point_array = np.zeros((n_points, 3)) for point_idx in range(n_points): point_array[point_idx] = points.GetPoint(point_idx + offset) offset += n_points self.spines.append(point_array) self.spines = np.array(self.spines)
def getCellIDsAtXY(self, x, y): bounds = self._grid.GetBounds() p1 = [x, y, bounds[-1]] p2 = [x, y, bounds[-2]] cell_ids = vtk.vtkIdList() self._cell_finder.FindCellsAlongLine(p1, p2, 1, cell_ids) def linepoints(y): return np.array(p1)[np.newaxis, :] + y[:, np.newaxis] * ( np.array(p2)[np.newaxis, :] - np.array(p1)[np.newaxis, :]) search = 1 yi = np.array([0, .5, 1]) points = (linepoints(yi)) ids = [] i = 0 for point in points: iD = (self.getCellId(point[0], point[1], point[2])) if (iD not in ids) and (iD != -1): ids.append(iD) while (search): new_yi = (yi[:-1] + yi[1:]) / 2. points = linepoints(new_yi) for point in points: iD = (self.getCellId(point[0], point[1], point[2])) if (iD not in ids) and (iD != -1): ids.append(iD) i += 1 dist = np.abs((points[:-1] - points[1:]))[0, 2] if len(ids) == 3: search = 0 elif dist < 1e-3: search = 0 if len(ids) < 1: raise ValueError("It seems like some trees are located " + "outside the ogs bulk mesh!" + " Please check for consistency.") elif i == 1e4: search = 0 raise ValueError("Search algorithm failed! Please improve" + " algorithm!") yi = np.concatenate((yi, new_yi)) yi.sort() return ids
def per_vertex_occlusion_accurate(mesh): from menpo3d.vtkutils import trimesh_to_vtk import vtk tol = mesh.mean_edge_length() / 1000 min_, max_ = mesh.bounds() z_min = min_[-1] - 10 z_max = max_[-1] + 10 ray_start = mesh.points.copy() ray_end = mesh.points.copy() points = mesh.points ray_start[:, 2] = z_min ray_end[:, 2] = z_max vtk_mesh = trimesh_to_vtk(mesh) obbTree = vtk.vtkOBBTree() obbTree.SetDataSet(vtk_mesh) obbTree.BuildLocator() vtk_points = vtk.vtkPoints() vtk_cellIds = vtk.vtkIdList() bad_val = tuple(ray_start[0]) first_intersects = [] for start, end, point in zip(ray_start, ray_end, points): start = tuple(start) end = tuple(end) obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds) data = vtk_points.GetData() break for start, end, point in zip(ray_start, ray_end, points): start = tuple(start) end = tuple(end) #obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds) data = vtk_points.GetData() if data.GetNumberOfTuples() > 0: first_intersects.append(data.GetTuple3(0)) else: first_intersects.append(bad_val) visible = np.linalg.norm(points - np.array(first_intersects), axis=1) < tol return visible
def writeExodusIIGrid(path, points, cellNodes, case): """ Methods writes the points and the cells in the Exodus II file format Args: path (string): The path where to write the Exodus II mesh points (list): The coordinates of the nodes of the grid cellNodes (list): The indices of the points to define the mesh case (int) The type of the vtk cells 1 = VTK_LINE 2 = VTK_TRIANGLE 3 = VTK_QUAD 4 = VTK_TETRA """ mesh = vtkUnstructuredGrid() vtk_points = vtkPoints() for point in points: vtk_points.InsertNextPoint(float(point[0]), float(point[1]), float(point[2])) mesh.SetPoints(vtk_points) for cellNodes in cellNodes: pts = vtkIdList() num_local_nodes = len(cellNodes) pts.SetNumberOfIds(num_local_nodes) for k, node_index in enumerate(cellNodes): pts.InsertId(k, int(node_index) - 1) if case == '1': mesh.InsertNextCell(VTK_LINE, pts) if case == '2': mesh.InsertNextCell(VTK_TRIANGLE, pts) if case == '3': mesh.InsertNextCell(VTK_QUAD, pts) if case == '4': mesh.InsertNextCell(VTK_TETRA, pts) writer = vtkExodusIIWriter() writer.WriteAllTimeStepsOn() writer.WriteOutBlockIdArrayOn() writer.WriteOutGlobalNodeIdArrayOn() writer.WriteOutGlobalElementIdArrayOn() writer.SetFileName(path) setInput(mesh, writer) writer.Write()
def mapPointDataToCellData(ugrid_data, ugrid_mesh, field_name, cell_length_ratio_for_radius=0.5, verbose=True): if (verbose): print '*** mapPointDataToCellData ***' nb_cells = ugrid_mesh.GetNumberOfCells() filter_cell_centers = vtk.vtkCellCenters() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): filter_cell_centers.SetInputData(ugrid_mesh) else: filter_cell_centers.SetInput(ugrid_mesh) filter_cell_centers.Update() pdata_mesh_cell_centers = filter_cell_centers.GetOutput() point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(ugrid_data) point_locator.Update() nb_components = ugrid_data.GetPointData().GetArray(field_name).GetNumberOfComponents() farray_tensors = createFloatArray(field_name, nb_components, nb_cells) points_within_radius = vtk.vtkIdList() for num_cell in range(nb_cells): l = (ugrid_mesh.GetCell(num_cell).GetLength2())**(0.5) point_locator.FindPointsWithinRadius(l*cell_length_ratio_for_radius, pdata_mesh_cell_centers.GetPoint(num_cell), points_within_radius) #points_in_cell = findPointsInCell(ugrid_data.GetPoints(), ugrid_mesh.GetCell(num_cell)) if (points_within_radius.GetNumberOfIds()): tensor = sum([numpy.array(ugrid_data.GetPointData().GetArray(field_name).GetTuple(points_within_radius.GetId(num_id))) for num_id in range(points_within_radius.GetNumberOfIds())])/points_within_radius.GetNumberOfIds() else: tensor = [0]*nb_components farray_tensors.InsertTuple(num_cell, tensor) ugrid_mesh.GetCellData().AddArray(farray_tensors)
def split4(_=False): r = vtk.vtkSTLReader() r.SetFileName('Schuerze4.stl') r.Update() bnds = Bnds(*r.GetOutput().GetBounds()) y = bnds.y1 / 2 pts = [[bnds.x1 - 1, y, bnds.z1 - 1], [bnds.x2 + 1, y, bnds.z1 - 1], [bnds.x2 + 1, y, bnds.z2 + 1], [bnds.x1 - 1, y, bnds.z2 + 1]] if _: pts.reverse() cell = vtk.vtkIdList() vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() [(vtk_pts.InsertNextPoint(pt), cell.InsertNextId(i)) for i, pt in enumerate(pts)] pd = vtk.vtkPolyData() pd.Allocate(1, 1) pd.SetPoints(vtk_pts) pd.InsertNextCell(vtk.VTK_POLYGON, cell) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) bf = vtkboolPython.vtkPolyDataBooleanFilter() bf.SetInputConnection(r.GetOutputPort()) bf.SetInputConnection(1, prod.GetOutputPort()) bf.SetOperModeToDifference() clean = vtk.vtkCleanPolyData() clean.SetInputConnection(bf.GetOutputPort()) pn = vtk.vtkPolyDataNormals() pn.SetInputConnection(clean.GetOutputPort()) pn.AutoOrientNormalsOn() return pn
def vtkGetLineComponents(surf): """vtkds must be polydata describing lines returns list of index arrays, point coordinates""" assert isinstance(surf, vtk.vtkPolyData) components = [] num_points = surf.GetNumberOfPoints() mask = np.zeros(num_points, dtype=np.int) component_num = 0 for main_p in xrange(num_points): if mask[main_p] <> 0: continue l = [] last_p = -1 p = main_p component_num += 1 #while mask[p] == 0: while True: l.append(p) if mask[p] <> 0: break mask[p] = component_num pts = [] r = vtk.vtkIdList() surf.GetPointCells(p, r) #print "at %i discovered: " % p, for ci in range(r.GetNumberOfIds()): c = surf.GetCell(r.GetId(ci)) for i in vtkIterCellPointIds(c): #print "%i(%s)" % (i, ci), if not (i == p or i == last_p): pts.append(i) #for ci, c in [ (r.GetId(i), surf.GetCell(r.GetId(i))) for i in range(r.GetNumberOfIds()) ]: #for i in tuple(c.GetPointId(j) for j in range(2)): #print "" if not pts: break last_p = p p = pts[0] if l: components.append(l) #print mask #pprint.pprint(components) points = np.asarray([surf.GetPoint(j)[:2] for j in xrange(num_points)]) components = [np.asarray(c, dtype=np.int) for c in components] return components, points
def add_graphics_edges(self, poly_data, color): pt1 = [0,0,0] pt2 = [0,0,0] points = poly_data.GetPoints(); """ for i in range(points.GetNumberOfPoints()-1): points.GetPoint(i,pt1) points.GetPoint(i+1,pt2) self.add_cyl(pt1, pt2) """ poly_data.GetLines().InitTraversal() idList = vtk.vtkIdList() while poly_data.GetLines().GetNextCell(idList): #print(">> Line has " + str(idList.GetNumberOfIds()) + " points." ) node1 = idList.GetId(0) node2 = idList.GetId(1) points.GetPoint(node1,pt1) points.GetPoint(node2,pt2) self.add_cyl(pt1, pt2)
def compute_descriptor(self, obb, normal, center_disc, radius): points = [] distances = [] points_disc = self.points_on_disc(normal, center_disc, radius) for p in points_disc: point_other_side = -normal * const_values.FLAGS.T + p point_another_size = normal * const_values.FLAGS.T + p intersected_points, intersected_cells = vtk.vtkPoints( ), vtk.vtkIdList() obb.SetTolerance(const_values.FLAGS.tolerance_of_obb) obb.IntersectWithLine(point_other_side, point_another_size, intersected_points, intersected_cells) intersect = [] if intersected_points.GetNumberOfPoints() > 1: min_distance = np.inf for i in range(intersected_points.GetNumberOfPoints()): if np.linalg.norm(p - self.points_to_array( intersected_points.GetPoint(i))) < min_distance: min_distance = np.linalg.norm(p - self.points_to_array( intersected_points.GetPoint(i))) intersect = self.points_to_array( intersected_points.GetPoint(i)) vec = p - intersect vec = vec / np.linalg.norm(vec) if vec.dot(normal) < 0: distances.append(-np.linalg.norm(p - intersect)) else: distances.append(np.linalg.norm(p - intersect)) elif intersected_points.GetNumberOfPoints() == 0: intersect = p distances.append(0.0) else: intersect = [ intersected_points.GetPoint(0)[x] for x in range(3) ] distances.append(np.linalg.norm(p - intersect)) intersect = np.array(intersect) points.append(intersect) points_mesh = np.array(points) distances = np.array(distances) return points_mesh, points_disc, distances
def findNuclearLocalMaximas(mesh, data, nuclear_data, Threshold): numPts = mesh.GetNumberOfPoints() localMaxPtList = vtk.vtkIdList() for ptID in xrange(0, numPts): pt_list = getConnectedVerticesNotIncludingSeed(mesh, ptID) seed_data_value = getValue(mesh, ptID, data) max_found = 1 nuclear_found = 1 for i in xrange(0, pt_list.GetNumberOfIds()): data_value = getValue(mesh, pt_list.GetId(i), data) nuclear_value = getValue(mesh, pt_list.GetId(i), nuclear_data) if (data_value >= seed_data_value): max_found = 0 if (nuclear_value < Threshold): nuclear_found = 0 if max_found == 1 and nuclear_found == 1: localMaxPtList.InsertUniqueId(ptID) return localMaxPtList
def convertToVTK(self, scalarArray, scalarType): """ Convert fibers in array form to VTK polydata. INPUT: scalarArray - Variable containing scalar information pertaining to VTK polydata scalarType - Type of quantitative scalar (ie. FA, T1) to be included with the poyldata OUTPUT: outVTK - Tractography polydata in VTK form """ outVTK = vtk.vtkPolyData() outPts = vtk.vtkPoints() outFibers = vtk.vtkCellArray() outScalars = vtk.vtkFloatArray() outFibers.InitTraversal() # Get fiber information to convert to VTK form for fidx in range(0, self.no_of_fibers): ptIds = vtk.vtkIdList() for pidx in range(0, self.pts_per_fiber): idx = outPts.InsertNextPoint(self.fiberArray_x[fidx, pidx], self.fiberArray_y[fidx, pidx], self.fiberArray_z[fidx, pidx]) ptIds.InsertNextId(idx) outScalars.InsertNextValue\ (float(scalarArray.fiberTree_scalar[fidx][pidx][scalarType])) outFibers.InsertNextCell(ptIds) # Group data into VTK format outVTK.SetLines(outFibers) outVTK.SetPoints(outPts) outVTK.GetPointData().SetScalars(outScalars) return outVTK
def main(): origin = [0.0, 0.0, 0.0] p0 = [1.0, 0.0, 0.0] p1 = [0.0, 1.0, 0.0] p2 = [0.0, 1.0, 2.0] p3 = [1.0, 2.0, 3.0] # Create a vtkPoints object and store the points in it. points = vtk.vtkPoints() points.InsertNextPoint(origin) points.InsertNextPoint(p0) points.InsertNextPoint(p1) points.InsertNextPoint(p2) points.InsertNextPoint(p3) # Create a cell array to store the lines in and add the lines to it. lines = vtk.vtkCellArray() # Create four lines. for i in range(4): line = vtk.vtkLine() line.GetPointIds().SetId(0, i) line.GetPointIds().SetId(1, i + 1) lines.InsertNextCell(line) # 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) print("There are {0} lines.".format(linesPolyData.GetNumberOfLines())) linesPolyData.GetLines().InitTraversal() idList = vtk.vtkIdList() while(linesPolyData.GetLines().GetNextCell(idList)): print("Line has {0} points".format(idList.GetNumberOfIds())) for pointId in range(idList.GetNumberOfIds() - 1): print("{0} {1}".format(idList.GetId(pointId), idList.GetId(pointId + 1)))
def triangulate(pd): """ Generates a triangle mesh for a spherical point cloud. It is assumed that 'pd' is an object of dsa.PolyData type. """ # Project on a sphere sphereXyz = alg.norm(pd.Points) * np.linalg.norm(pd.Points, axis=1).mean() sphereXyz = np.around(sphereXyz, decimals=2) sphereArr = dsa.numpyTovtkDataArray(sphereXyz, name='SpherePts') pts = v.vtkPoints() pts.SetData(sphereArr) sphere = v.vtkPolyData() sphere.SetPoints(pts) # Store the original point ids idf = v.vtkIdFilter() idf.SetIdsArrayName('PointIds') idf.PointIdsOn() idf.SetInputData(sphere) # Delaunay3D to make a convex hull d3d = v.vtkDelaunay3D() d3d.SetInputConnection(idf.GetOutputPort()) # Extract the surface surf = v.vtkDataSetSurfaceFilter() surf.SetInputConnection(d3d.GetOutputPort()) surf.Update() # Now make a new cell array mapping to the old ids polyCells = v.vtkCellArray() sphereCells = surf.GetOutput().GetPolys() sphereCells.InitTraversal() origIds = surf.GetOutput().GetPointData().GetArray('PointIds') ptIds = v.vtkIdList() while (sphereCells.GetNextCell(ptIds)): polyCells.InsertNextCell(3) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(0)))) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(1)))) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(2)))) return polyCells
def generateMeshPolyData(points): pts = v.vtkPoints() for p in points: pts.InsertNextPoint(p) pd = v.vtkPolyData() pd.SetPoints(pts) # Create a IdFilter to preserve original point ids idf = v.vtkIdFilter() idf.SetIdsArrayName('origIds') idf.PointIdsOn() idf.SetInputData(pd) # Create a 2D Delaunay triangulation d2d = v.vtkDelaunay2D() d2d.SetInputConnection(idf.GetOutputPort()) # Create mesh quality cell data array to filter out # boundary triangles mq = v.vtkMeshQuality() mq.SetInputConnection(d2d.GetOutputPort()) mq.SetTriangleQualityMeasureToAspectRatio() mq.SaveCellQualityOn() mq.Update() # Generate the polydata with mesh plateTriPoly = mq.GetOutput() plateTri = plateTriPoly.GetPolys() # Map the connectivity to original point ids newTriangles = v.vtkCellArray() plateTri.InitTraversal() triIds = v.vtkIdList() origIds = plateTriPoly.GetPointData().GetArray('origIds') aspectRatioArray = plateTriPoly.GetCellData().GetArray('Quality') triangleIndex = 0 while plateTri.GetNextCell(triIds): # Keep only the equilateral triangles to get rid of boundary triangles aspectRatio = aspectRatioArray.GetTuple1(triangleIndex) triangleIndex += 1 if aspectRatio < 1.5: newTriangles.InsertNextCell(3) for i in range(3): newTriangles.InsertCellPoint( int(origIds.GetTuple1(triIds.GetId(i)))) pd.SetPolys(newTriangles) return pd
def meshPointCloud( inputVTKfile, searchRad ): reader = v.vtkPolyDataReader() reader.SetFileName( inputVTKfile ) reader.Update() pd = reader.GetOutput() N = pd.GetNumberOfPoints() kdt = v.vtkKdTree() kdt.BuildLocatorFromPoints( pd.GetPoints() ) polys = v.vtkCellArray() for i in range( N ): currPoint = pd.GetPoint(i) idList = v.vtkIdList() kdt.FindPointsWithinRadius( searchRad, currPoint, idList ) neighbors = [] for j in range( idList.GetNumberOfIds() ): currId = idList.GetId(j) if j != i: neighbors.append(currId)
def makeConnectivityList(poly): listOut = [] idf = v.vtkIdFilter() idf.SetInputData(poly) idf.SetIdsArrayName('OrigIds') idf.PointIdsOn() edgeExt = v.vtkExtractEdges() edgeExt.SetInputConnection(idf.GetOutputPort()) edgeExt.Update() edges = edgeExt.GetOutput() origIds = edges.GetPointData().GetArray('OrigIds') ids = v.vtkIdList() cells = edges.GetLines() cells.InitTraversal() while cells.GetNextCell(ids): connectivity = [] for i in range(ids.GetNumberOfIds()): connectivity.append(int(origIds.GetTuple1(ids.GetId(i)))) listOut.append(connectivity) return listOut
def extract_points(self, source): # Travers the cells and add points while keeping their order. points = source.GetPoints() cells = source.GetLines() cells.InitTraversal() idList = vtk.vtkIdList() pointIds = [] while cells.GetNextCell(idList): for i in range(0, idList.GetNumberOfIds()): pId = idList.GetId(i) # Only add the point id if the previously added point does not # have the same id. Avoid p->p duplications which occur for example # if a poly-line is traversed. However, other types of point # duplication currently are not avoided: a->b->c->a->d if len(pointIds) == 0 or pointIds[-1] != pId: pointIds.append(pId) result = [] for i in pointIds: result.append(points.GetPoint(i)) return result
def get_outlet_branches(self): """ Get list of branches connected to outlets """ # branch ids br_id = self.get_point_data(self.PointDataFields.BRANCH) bf_id = self.get_point_data(self.PointDataFields.BIFURCATION) # global node id gid = self.get_point_data(self.PointDataFields.NODEID) # outlet points are only connected to one cell (skip inlet point) ids = vtkIdList() outlets = [] for p in range(self.centerline.GetNumberOfPoints()): self.centerline.GetPointCells(p, ids) if ids.GetNumberOfIds() == 1 and gid[p] != 0: assert br_id[p] != -1, 'bifurcation ' + str(bf_id[p]) + ' is connected to an outlet' outlets += [br_id[p]] return outlets
def isCellWet(vtkSGrid2D, newPoint2D, cellID, IBC_2D): pcoords = [0.0,0.0,0.0] weights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] clspoint = [0.,0.,0.] tmpid = vtk.mutable(0) vtkid2 = vtk.mutable(0) vtkcell2D = vtk.vtkQuad() vtkcell2D = vtkSGrid2D.GetCell(cellID) tmpres = vtkcell2D.EvaluatePosition(newPoint2D,clspoint,tmpid,pcoords,vtkid2, weights ) idlist1 = vtk.vtkIdList() numpts = vtkcell2D.GetNumberOfPoints() idlist1 = vtkcell2D.GetPointIds() tmpIBC = 0.0 for x in range(0,numpts): tmpIBC = tmpIBC + weights[x]*abs(IBC_2D.GetTuple(idlist1.GetId(x))[0]) # print(tmpIBC,abs(IBC_2D.GetTuple(idlist1.GetId(x))[0])) if tmpIBC >= .9999999: return True else: return False
def vtk_to_mat(polydata, path): num_points = polydata.GetNumberOfPoints() sps_acc = sps.coo_matrix((num_points, num_points)) data = [] row_indices = [] column_indices = [] lines = polydata.GetLines() vtk_data = polydata.GetCellData().GetScalars() print "np: ", num_points for idx in range(lines.GetNumberOfCells()): points = vtk.vtkIdList() lines.GetCell(idx, points) if points.GetNumberOfIds() == 2: row_indices.append(points.GetId(0)) column_indices.append(points.GetId(1)) data.append(vtk_data.GetTuple1(idx)) sps_acc = sps_acc + sps.coo_matrix((data, (row_indices, column_indices)), shape=(num_points, num_points)) savemat(path, {'skeleton': sps_acc})
def drawCells(self, cellIdList, color): triangles = vtk.vtkCellArray() pointslist = vtk.vtkIdList() fullPoints = self.mesh.GetPoints() partPoints = vtk.vtkPoints() for i in range(cellIdList.GetNumberOfIds()): cell = cellIdList.GetId(i) triangle = self.mesh.GetCell(cell) triangles.InsertNextCell(triangle) self.mesh.GetCellPoints(cell, pointslist) partPoints.InsertPoints(pointslist, pointslist, fullPoints) trianglePoly = vtk.vtkPolyData() trianglePoly.SetPoints(partPoints) trianglePoly.SetPolys(triangles) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(trianglePoly) self.addActor(mapper, color)
def search(self, points, radius=None): """ Get ids of points in geometry closest to input points Args: points: list of points to be searched radius: optional, search radius Returns: Id list """ ids = [] for p in points: if radius is not None: result = vtk.vtkIdList() self.locator.FindPointsWithinRadius(radius, p, result) ids += [ result.GetId(k) for k in range(result.GetNumberOfIds()) ] else: ids += [self.locator.FindClosestPoint(p)] return ids
def _rbe2(elem, cell_type, ugrid, nid_dict): independent = elem.gn dependent = elem.Gmi nids = [] for i in range(len(dependent)): nids.append(nid_dict[independent]) nids.append(nid_dict[dependent[i]]) ids = vtk.vtkIdList() ids.SetNumberOfIds(len(nids)) for i in range(len(nids)): ids.SetId(i, nids[i]) ugrid.InsertNextCell(cell_type, ids) return elem.eid
def PopulateFromVtkData(self, inInputCsData, globalCellIdArray, quadIndex): self.index = quadIndex cellPointIds = vtk.vtkIdList() inInputCsData.GetCellPoints(quadIndex, cellPointIds) numids = cellPointIds.GetNumberOfIds() if numids != 4: myDebugPrint3AndException( "GetQuadClosestToPointsInBlock2Params: not a quad") inInputCsData.GetPoint(cellPointIds.GetId(0), self.ptA) inInputCsData.GetPoint(cellPointIds.GetId(1), self.ptB) inInputCsData.GetPoint(cellPointIds.GetId(2), self.ptC) inInputCsData.GetPoint(cellPointIds.GetId(3), self.ptD) self.ptAverage[0] = (self.ptA[0] + self.ptB[0] + self.ptC[0] + self.ptD[0]) * 0.25 self.ptAverage[1] = (self.ptA[1] + self.ptB[1] + self.ptC[1] + self.ptD[1]) * 0.25 self.ptAverage[2] = (self.ptA[2] + self.ptB[2] + self.ptC[2] + self.ptD[2]) * 0.25 if globalCellIdArray != None: self.cellId = globalCellIdArray.GetValue(quadIndex)
def cacheState(self): self.clearCachedState() self.cachedState = [] #clone nodes children = vtk.vtkIdList() shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode( slicer.mrmlScene) shNode.GetItemChildren( self.folder, children ) # Add a third argument with value True for recursive query state = [] for i in range(children.GetNumberOfIds()): child = children.GetId(i) childNode = shNode.GetItemDataNode(child) if not self.isNodeCurrent(childNode): continue clonedChild = self.cloneNode(childNode) self.archiveNode(clonedChild) self.cachedState.append(clonedChild)
def VtkCargaMalla(recordGrid): kpoints = vtk.vtkPoints() # Definimos grid recordGrid.uGrid.SetPoints(kpoints) setToDraw = recordGrid.xcSet setToDraw.numerate() pnts = setToDraw.getPoints for p in pnts: kpoints.InsertPoint(p.getIdx, p.getPos.x, p.getPos.y, p.getPos.z) cellSet = setToDraw.getLines # cells are lines as default. if (recordGrid.cellType == "faces"): cellSet = setToDraw.getSurfaces elif (recordGrid.cellType == "bodies"): cellSet = setToDraw.getBodies for c in cellSet: vertices = xc_base.vector_int_to_py_list(c.getIdxVertices) vtx = vtk.vtkIdList() for vIndex in vertices: vtx.InsertNextId(vIndex) recordGrid.uGrid.InsertNextCell(c.getVtkCellType, vtx)
def draw_faces(self): faces = vtkCellArray() for face in self.data['faces']: vil = vtkIdList() for pt in face['vertices']: vil.InsertNextId(pt) faces.InsertNextCell(vil) color = face.get('color', [150, 255, 150]) try: self.colors.InsertNextTypedTuple(color) except Exception: self.colors.InsertNextTupleValue(color) self.polydata.SetPolys(faces) self.main.window.Render()