当前位置: 首页>>代码示例>>Python>>正文


Python vtk.vtkIdTypeArray函数代码示例

本文整理汇总了Python中vtk.vtkIdTypeArray函数的典型用法代码示例。如果您正苦于以下问题:Python vtkIdTypeArray函数的具体用法?Python vtkIdTypeArray怎么用?Python vtkIdTypeArray使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了vtkIdTypeArray函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: GetTree

	def GetTree(self):
		"""Returns a full vtkTree based on data loaded in LoadData()."""

		if self.data_loaded:

			vertex_id = vtk.vtkIdTypeArray()
			vertex_id.SetName('vertex_ids')
			for ii in range(len(self.cp)):
				vertex_id.InsertNextValue(ii)

			NINvtk = VN.numpy_to_vtk(self.NumberInNet, deep=True)
			NINvtk.SetName('num_in_vertex')
			SCALESvtk = VN.numpy_to_vtk(self.Scales, deep=True)
			SCALESvtk.SetName('scale')

			# This array will default to empty strings
			BLANKvtk = vtk.vtkStringArray()
			BLANKvtk.SetNumberOfComponents(1)
			BLANKvtk.SetNumberOfTuples(self.NumberInNet.shape[0])
			BLANKvtk.SetName('blank')

			# Build tree out of CP list of "is a child of"
			#	remembering that Matlab indices are 1-based and numpy/VTK 0-based
			print 'Building graph'
			dg = vtk.vtkMutableDirectedGraph()
			edge_id = vtk.vtkIdTypeArray()
			edge_id.SetName('edge_ids')
			for ii in range(self.cp.size):
				dg.AddVertex()
			for ii in range(self.cp.size):
				if self.cp[ii] > 0:		# CP already zero-based
					dg.AddGraphEdge(self.cp[ii],ii)		# Method for use with wrappers -- AddEdge() in C++
					edge_id.InsertNextValue(ii)

			dg.GetVertexData().AddArray(NINvtk)
			dg.GetVertexData().AddArray(SCALESvtk)
			dg.GetVertexData().AddArray(vertex_id)
			dg.GetVertexData().SetActiveScalars('scale')
			dg.GetVertexData().SetActivePedigreeIds('vertex_ids')
			dg.GetEdgeData().AddArray(edge_id)
			dg.GetEdgeData().SetActivePedigreeIds('edge_ids')

			tree = vtk.vtkTree()
			tree.CheckedShallowCopy(dg)

			return tree

		else:
			raise IOError, "Can't get tree until data is loaded successfully"
开发者ID:emonson,项目名称:MultiScaleSVD,代码行数:49,代码来源:data_source.py

示例2: selectCell

    def selectCell(self, cellId):
        if cellId in (None, -1):
            return
        ids = vtk.vtkIdTypeArray();
        ids.SetNumberOfComponents(1);
        ids.InsertNextValue(cellId);

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

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

        extractSelection = vtk.vtkExtractSelection();

        extractSelection.SetInputData(0, self.actor.GetMapper().GetInput());
        extractSelection.SetInputData(1, selection);

        extractSelection.Update();

        selected = vtk.vtkUnstructuredGrid();
        selected.ShallowCopy(extractSelection.GetOutput());

        self.selectedMapper.SetInputData(selected);
        self.selectedMapper.Update()
开发者ID:devarajun,项目名称:uvcdat,代码行数:27,代码来源:colorpicker.py

示例3: numpy_to_vtkIdTypeArray

def numpy_to_vtkIdTypeArray(num_array, deep=0):
    isize = vtk.vtkIdTypeArray().GetDataTypeSize()
    dtype = num_array.dtype
    if isize == 4:
        if dtype != numpy.int32:
            raise ValueError, \
             'Expecting a numpy.int32 array, got %s instead.' % (str(dtype))
    else:
        if dtype != numpy.int64:
            raise ValueError, \
             'Expecting a numpy.int64 array, got %s instead.' % (str(dtype))
        
    return numpy_to_vtk(num_array, deep, vtkConstants.VTK_ID_TYPE)
开发者ID:Paulxia,项目名称:SlicerVTK,代码行数:13,代码来源:numpy_support.py

示例4: numpy2vtkDataArrayInt

def numpy2vtkDataArrayInt(npa):
#    print npa[1][0]
    size0, size1 = npa.shape
    data = vtk.vtkIdTypeArray()
    data.SetNumberOfComponents(4)
#    data.SetName("CELLS")
    for i in range(size0):
        n0 = int(npa[i, 0])
        n1 = int(npa[i, 1])
        n2 = int(npa[i, 2])
        n3 = int(npa[i, 3])
        data.InsertNextTuple4(n0, n1, n2, n3)
    
    return data
开发者ID:beauof,项目名称:FSIViewer,代码行数:14,代码来源:organiseData.py

示例5: __init__

        def __init__(self, times, slider_repres):
            self._stimes = set(times)
            self._opacity = 1.0
            self._time_step = (max(self._stimes) - min(self._stimes)) \
                               / len(self._stimes)
            self._time = min(times)
            self._slider_repres = slider_repres
            self._current_id = vtk.vtkIdTypeArray()
            self._renderer = renderer
            self._renderer_window = renderer_window
            self._times = times
            self._image_counter = 0

            self._recording = False
开发者ID:xhub,项目名称:siconos,代码行数:14,代码来源:vview.py

示例6: WriteTecplotMeshFile

 def WriteTecplotMeshFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing Tecplot file.')
     triangleFilter = vtk.vtkDataSetTriangleFilter()
     triangleFilter.SetInputData(self.Mesh)
     triangleFilter.Update()
     self.Mesh = triangleFilter.GetOutput()
     f=open(self.OutputFileName, 'w')
     line = "VARIABLES = X,Y,Z"
     arrayNames = []
     for i in range(self.Mesh.GetPointData().GetNumberOfArrays()):
         array = self.Mesh.GetPointData().GetArray(i)
         arrayName = array.GetName()
         if arrayName == None:
             continue
         if (arrayName[-1]=='_'):
             continue
         arrayNames.append(arrayName)
         if (array.GetNumberOfComponents() == 1):
             line = line + ',' + arrayName
         else:
             for j in range(array.GetNumberOfComponents()):
                 line = line + ',' + arrayName + str(j)
     line = line + '\n'
     f.write(line)
     tetraCellIdArray = vtk.vtkIdTypeArray()
     tetraCellType = 10
     self.Mesh.GetIdsOfCellsOfType(tetraCellType,tetraCellIdArray)
     numberOfTetras = tetraCellIdArray.GetNumberOfTuples()
     line = "ZONE " + "N=" + str(self.Mesh.GetNumberOfPoints()) + ',' + "E=" + str(numberOfTetras) + ',' + "F=FEPOINT" + ',' + "ET=TETRAHEDRON" + '\n'
     f.write(line)
     for i in range(self.Mesh.GetNumberOfPoints()):
         point = self.Mesh.GetPoint(i)
         line = str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2])
         for arrayName in arrayNames:
             array = self.Mesh.GetPointData().GetArray(arrayName)
             for j in range(array.GetNumberOfComponents()):
                 line = line + ' ' + str(array.GetComponent(i,j))
         line = line + '\n'
         f.write(line)
     for i in range(numberOfTetras):
         cellPointIds = self.Mesh.GetCell(tetraCellIdArray.GetValue(i)).GetPointIds()
         line = ''
         for j in range(cellPointIds.GetNumberOfIds()):
             if (j>0):
                 line = line + ' '
             line = line + str(cellPointIds.GetId(j)+1)
         line = line + '\n'
         f.write(line)
开发者ID:151706061,项目名称:vmtk,代码行数:50,代码来源:vmtkmeshwriter2.py

示例7: GetSelection

def GetSelection(ids, inverse=False):
    selNode = vtk.vtkSelectionNode()
    selNode.SetContentType(vtk.vtkSelectionNode.BLOCKS)

    idArray = vtk.vtkIdTypeArray()
    idArray.SetNumberOfTuples(len(ids))
    for i in range(len(ids)):
        idArray.SetValue(i, ids[i])
    selNode.SetSelectionList(idArray)

    if inverse:
        selNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)

    sel = vtk.vtkSelection()
    sel.AddNode(selNode)

    return sel
开发者ID:ElsevierSoftwareX,项目名称:SOFTX-D-15-00004,代码行数:17,代码来源:extractBlocks.py

示例8: picker_callback

	def picker_callback(self,obj,event):
		
		extract = vtk.vtkExtractSelectedFrustum()
	
		fPlanes=obj.GetFrustum() #collection of planes based on unscaled display
	
		#scale frustum to account for the zaspect
		scaledPlanes=vtk.vtkPlanes()
		scaledNormals=vtk.vtkDoubleArray()
		scaledNormals.SetNumberOfComponents(3)
		scaledNormals.SetNumberOfTuples(6)
		scaledOrigins=vtk.vtkPoints()
		for j in range(6):
			i=fPlanes.GetPlane(j)
			k=i.GetOrigin()
			q=i.GetNormal()
			scaledOrigins.InsertNextPoint(k[0],k[1],k[2]/float(self.Zaspect))
			scaledNormals.SetTuple(j,(q[0],q[1],q[2]*float(self.Zaspect)))
		scaledPlanes.SetNormals(scaledNormals)
		scaledPlanes.SetPoints(scaledOrigins)
			
		
		extract.SetFrustum(scaledPlanes)
		extract.SetInputData(self.vtkPntsPolyData)
		extract.Update()
		extracted = extract.GetOutput()
		
		ids = vtk.vtkIdTypeArray()
		ids = extracted.GetPointData().GetArray("vtkOriginalPointIds")

		
		if ids:
			#store them in an array for an undo operation
			self.lastSelectedIds=ids
			for i in range(ids.GetNumberOfTuples()):
				#turn them red
				self.colors.SetTuple(ids.GetValue(i),(255,0,0))
				self.bool_pnt[ids.GetValue(i)]=False
		
			self.vtkPntsPolyData.GetPointData().SetScalars(self.colors)
			self.vtkPntsPolyData.Modified()
		
		
		self.ui.vtkWidget.update()
		#set flag on ui to show that data has been modified
		self.unsaved_changes=True
开发者ID:majroy,项目名称:pyCM,代码行数:46,代码来源:point_cloud.py

示例9: setPoints

    def setPoints( self, point_data ):
        self.vtkPoints.SetData( point_data )
        ncells = point_data.GetNumberOfTuples()               
        cells = vtk.vtkIdTypeArray()
        cell_data_array = np.empty( 2*ncells, dtype=np.int64 )  
        cell_data_array[1:2*ncells:2] = range( ncells )
        cell_data_array[0:2*ncells:2] = 1
#        cell_data_array = np.array( range( ncells ), dtype=np.int64 )  
        cells.SetVoidArray( cell_data_array, 2*ncells, 1 )
        self.vtkCells.SetCells ( ncells, cells )
#        self.vtkCells.InsertNextCell( cell )
#        for iCell in range( ncells ):
#            self.vtkCells.InsertNextCell( 1 )
#            self.vtkCells.InsertCellPoint( iCell )
        cellData = self.vtkCells.GetData ()
        print " Cell Data:\n %s " % str( [ cellData.GetValue(iCell) for iCell in range(cellData.GetNumberOfTuples())]  )
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
开发者ID:imclab,项目名称:vistrails,代码行数:18,代码来源:VoxelizerModule.py

示例10: trimesh_to_vtk

def trimesh_to_vtk(trimesh):
    r"""Return a `vtkPolyData` representation of a :map:`TriMesh` instance

    Parameters
    ----------
    trimesh : :map:`TriMesh`
        The menpo :map:`TriMesh` object that needs to be converted to a
        `vtkPolyData`

    Returns
    -------
    `vtk_mesh` : `vtkPolyData`
        A VTK mesh representation of the Menpo :map:`TriMesh` data

    Raises
    ------
    ValueError:
        If the input trimesh is not 3D.
    """
    import vtk
    from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray
    if trimesh.n_dims != 3:
        raise ValueError('trimesh_to_vtk() only works on 3D TriMesh instances')

    mesh = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    points.SetData(numpy_to_vtk(trimesh.points, deep=1))
    mesh.SetPoints(points)

    cells = vtk.vtkCellArray()

    # Seemingly, VTK may be compiled as 32 bit or 64 bit.
    # We need to make sure that we convert the trilist to the correct dtype
    # based on this. See numpy_to_vtkIdTypeArray() for details.
    isize = vtk.vtkIdTypeArray().GetDataTypeSize()
    req_dtype = np.int32 if isize == 4 else np.int64
    cells.SetCells(trimesh.n_tris,
                   numpy_to_vtkIdTypeArray(
                       np.hstack((np.ones(trimesh.n_tris)[:, None] * 3,
                                  trimesh.trilist)).astype(req_dtype).ravel(),
                       deep=1))
    mesh.SetPolys(cells)
    return mesh
开发者ID:HaoyangWang,项目名称:menpo3d,代码行数:43,代码来源:vtkutils.py

示例11: find_celledge_neighbors

                neighb = find_celledge_neighbors(tri_id, tri)

                #print('Neighbors ', neighb)

                for j in range( len(neighb) ):
                    if trilabel[neighb[j]]==0:
                        #see if the triangles tri_id and neighb[j] are on the different sides of the line
                        #i.e. if they share any pair of points of the line
                        if not triangles_on_any_line(tri_id, neighb[j], tri, lines):
                            tri_stack.append(neighb[j])


# In[11]:


array = vtk.vtkIdTypeArray()
array.SetName(array_name)
array.SetNumberOfComponents(1)
array.SetNumberOfTuples(trilabel.shape[0])

for i in range(trilabel.shape[0]):
    array.SetTuple1(i, trilabel[i])
    
mesh.GetCellData().AddArray(array)

wr = vtk.vtkPolyDataWriter()
wr.SetFileName(output_mesh)
wr.SetInputData(mesh)
wr.Write()

开发者ID:cbutakoff,项目名称:tools,代码行数:29,代码来源:cut_mesh.py

示例12: range

       xM = data2[:,1].max()
       ym = data2[:,0].min()
       yM = data2[:,0].max()
       N = data2.shape[0]
       m2 = numpy.ascontiguousarray(numpy.transpose(data2,(0,2,1)))
       nVertices = m2.shape[-2]
       m2.resize((m2.shape[0]*m2.shape[1],m2.shape[2]))
       m2=m2[...,::-1]
       # here we add dummy levels, might want to reconsider converting "trimData" to "reOrderData" and use actual levels?
       m3=numpy.concatenate((m2,numpy.zeros((m2.shape[0],1))),axis=1)
 except Exception,err: # Ok no mesh on file, will do with lat/lon
   pass
 if m3 is not None:
   #Create unstructured grid points
   vg = vtk.vtkUnstructuredGrid()
   lst = vtk.vtkIdTypeArray()
   cells = vtk.vtkCellArray()
   numberOfCells = N
   lst.SetNumberOfComponents(nVertices + 1)
   lst.SetNumberOfTuples(numberOfCells)
   for i in range(N):
     tuple = [None] * (nVertices + 1)
     tuple[0] = nVertices
     for j in range(nVertices):
       tuple[j + 1] = i * nVertices + j
     lst.SetTuple(i, tuple)
     ## ??? TODO ??? when 3D use CUBE?
   cells.SetCells(numberOfCells, lst)
   vg.SetCells(vtk.VTK_POLYGON, cells)
 else:
   #Ok a simple structured grid is enough
开发者ID:UNESCO-IHE,项目名称:uvcdat,代码行数:31,代码来源:vcs2vtk.py

示例13: WriteLifeVMeshFile

    def WriteLifeVMeshFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing LifeV file.')

        self.Mesh.BuildLinks()

        cellEntityIdsArray = vtk.vtkIntArray()
        cellEntityIdsArray.DeepCopy(self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName))

        tetraCellType = 10
        triangleCellType = 5

        f=open(self.OutputFileName, 'w')
        line = "MeshVersionFormatted 1\n\n"
        line += "Dimension\n"
        line += "3\n\n"
        line += "Vertices\n"
        line += "%d\n" % self.Mesh.GetNumberOfPoints()
        f.write(line)
        for i in range(self.Mesh.GetNumberOfPoints()):
            point = self.Mesh.GetPoint(i)
            pointCells = vtk.vtkIdList()
            self.Mesh.GetPointCells(i,pointCells)
            minTriangleCellEntityId = -1
            tetraCellEntityId = -1
            for j in range(pointCells.GetNumberOfIds()):
                cellId = pointCells.GetId(j)
                if self.Mesh.GetCellType(cellId) == triangleCellType:
                    cellEntityId = cellEntityIdsArray.GetValue(cellId)
                    if cellEntityId < minTriangleCellEntityId or minTriangleCellEntityId == -1:
                        minTriangleCellEntityId = cellEntityId
                else:
                    tetraCellEntityId = cellEntityIdsArray.GetValue(cellId)
            cellEntityId = tetraCellEntityId
            if minTriangleCellEntityId != -1:
                cellEntityId = minTriangleCellEntityId
            line = "%f  %f  %f  %d\n" % (point[0], point[1], point[2], cellEntityId)
            f.write(line)
        line = "\n"

        tetraCellIdArray = vtk.vtkIdTypeArray()
        self.Mesh.GetIdsOfCellsOfType(tetraCellType,tetraCellIdArray)
        numberOfTetras = tetraCellIdArray.GetNumberOfTuples()
        line += "Tetrahedra\n"
        line += "%d\n" % numberOfTetras
        f.write(line)
        for i in range(numberOfTetras):
            tetraCellId = tetraCellIdArray.GetValue(i) 
            cellPointIds = self.Mesh.GetCell(tetraCellId).GetPointIds()
            line = ''
            for j in range(cellPointIds.GetNumberOfIds()):
                if j>0:
                    line += '  '
                line += "%d" % (cellPointIds.GetId(j)+1)
            line += '  %d\n' % 1
            f.write(line)
        line = "\n"

        triangleCellIdArray = vtk.vtkIdTypeArray()
        self.Mesh.GetIdsOfCellsOfType(triangleCellType,triangleCellIdArray)
        numberOfTriangles = triangleCellIdArray.GetNumberOfTuples()
        line += "Triangles\n"
        line += "%d\n" % numberOfTriangles
        f.write(line)
        for i in range(numberOfTriangles):
            triangleCellId = triangleCellIdArray.GetValue(i)
            cellPointIds = self.Mesh.GetCell(triangleCellId).GetPointIds()
            line = ''
            for j in range(cellPointIds.GetNumberOfIds()):
                if j>0:
                    line += '  '
                line += "%d" % (cellPointIds.GetId(j)+1)
            cellEntityId = cellEntityIdsArray.GetValue(triangleCellId)
            line += '  %d\n' % cellEntityId
            f.write(line)
开发者ID:151706061,项目名称:vmtk,代码行数:76,代码来源:vmtkmeshwriter2.py

示例14: ExtractSelection

def ExtractSelection(fileList):
    # Report our CWD just for testing purposes.
    print "CWD:", os.getcwd()

    ringOffset = numQuadsPerRing * numSMCsPerCol * 4
    branchOffset = numRingsPerBranch * ringOffset

    # Prepare selection id array.    
    selectionIds = vtk.vtkIdTypeArray()
    
    for branch in branches:
        thisBranchOffset = branch * branchOffset
        # print thisBranchOffset,
    
        for ring in range(numRingsPerBranch):
            thisRingOffset = ring * ringOffset
            # print thisRingOffset, 
            
            for cell in range(numSMCsPerCol):
                thisOffset = start + thisBranchOffset + thisRingOffset + cell
                # print thisOffset,
                selectionIds.InsertNextValue(thisOffset)
    
    # Create selection node.
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(selectionNode.CELL)
    selectionNode.SetContentType(selectionNode.INDICES)
    selectionNode.SetSelectionList(selectionIds)
    
    # Create selection.
    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)
    
    sortNicely(fileList)
    
    # Process every file by extracting selection.
    for inFile in fileList:
        print 'Reading file', inFile
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(inFile)
        
        print '\tExtracting ', selectionIds.GetNumberOfTuples(), 'cells...'
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputConnection(reader.GetOutputPort())
        if vtk.vtkVersion().GetVTKMajorVersion() > 5:
            selectionExtractor.SetInputData(1, selection)
        else:
            selectionExtractor.SetInput(1, selection)
        
        baseName = os.path.basename(inFile)
        number = [int(s) for s in re.split('([0-9]+)', baseName) if s.isdigit()]
        outFile = outputPattern + str(number[0]) + '.vtu'
        
        print '\t\tSaving file', outFile
        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetInputConnection(selectionExtractor.GetOutputPort())
        writer.SetFileName(outFile)
        writer.Update()
        
        print '\n'
    
    print 'All done...'
开发者ID:BlueFern,项目名称:DBiharMesher,代码行数:62,代码来源:ExtractSelection.py

示例15: segfault

 - You need to make sure you hold a reference to a Numpy array you want
   to import into VTK.  If not you'll get a segfault (in the best case).
   The same holds in reverse when you convert a VTK array to a numpy
   array -- don't delete the VTK array.


Created by Prabhu Ramachandran in Feb. 2008.
"""

import vtk
import vtkConstants
import numpy

# Useful constants for VTK arrays.
VTK_ID_TYPE_SIZE = vtk.vtkIdTypeArray().GetDataTypeSize()
if VTK_ID_TYPE_SIZE == 4:
    ID_TYPE_CODE = numpy.int32
elif VTK_ID_TYPE_SIZE == 8:
    ID_TYPE_CODE = numpy.int64

VTK_LONG_TYPE_SIZE = vtk.vtkLongArray().GetDataTypeSize()
if VTK_LONG_TYPE_SIZE == 4:
    LONG_TYPE_CODE = numpy.int32
    ULONG_TYPE_CODE = numpy.uint32
elif VTK_LONG_TYPE_SIZE == 8:
    LONG_TYPE_CODE = numpy.int64
    ULONG_TYPE_CODE = numpy.uint64


def get_vtk_array_type(numpy_array_type):
开发者ID:Paulxia,项目名称:SlicerVTK,代码行数:30,代码来源:numpy_support.py


注:本文中的vtk.vtkIdTypeArray函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。