从python中的VTK文件中检索构面和指向

Ant*_*ier 5 python numpy vtk

我有一个包含3D模型的vtk文件,

我想提取点坐标和构面。

这是一个最小的工作示例:

import vtk
import numpy
from vtk.util.numpy_support import vtk_to_numpy

reader = vtk.vtkPolyDataReader()
reader.SetFileName('test.vtk')
reader.Update()

polydata = reader.GetOutput()

points = polydata.GetPoints()
array = points.GetData()
numpy_nodes = vtk_to_numpy(array)
Run Code Online (Sandbox Code Playgroud)

它的工作方式是numpy_nodes包含所有点的x,y,z坐标,但我不知所措,无法检索将该模型的各个方面与相应点相关联的列表。

我试过了:

facets= polydata.GetPolys()
array = facets.GetData()
numpy_nodes = vtk_to_numpy(array)
Run Code Online (Sandbox Code Playgroud)

但是,numpy_nodes这只是一个1D数组,我希望它是一个2D数组(大小为3 *刻面数),其中第一个维度包含指向该刻面的对应点数(如.ply文件中一样)。

任何有关如何进行的建议都将受到欢迎

nor*_*ius 3

你就快到了。为了允许不同类型的单元格(三角形、四边形等),numpy 数组使用以下方案对信息进行编码:

numpyArray = [ n_0, id_0(0), id_0(1), ..., id_0(n0-1), 
               n_1, id_1(0), id_1(1), ..., id_1(n1-1), 
               ... 
               n_i, id_i(0), id_i(1), ..., id_1(n1-1), 
               ...
              ]
Run Code Online (Sandbox Code Playgroud)

如果所有多边形都属于同一类型,即n_i==n对于 all i,只需重塑一维数组即可获得可解释的内容:

cells = polydata.GetPolys()
nCells = cells.GetNumberOfCells()
array = cells.GetData()
# This holds true if all polys are of the same kind, e.g. triangles.
assert(array.GetNumberOfValues()%nCells==0)
nCols = array.GetNumberOfValues()//nCells
numpy_cells = vtk_to_numpy(array)
numpy_cells = numpy_cells.reshape((-1,nCols))
Run Code Online (Sandbox Code Playgroud)

的第一列numpy_cells可以删除,因为它只包含每个单元格的点数。但其余列包含您要查找的信息。

为了确定结果,请将输出与收集点 ID 的“传统”方式进行比较:

def getCellIds(polydata):
    cells = polydata.GetPolys()
    ids = []
    idList = vtk.vtkIdList()
    cells.InitTraversal()
    while cells.GetNextCell(idList):
        for i in range(0, idList.GetNumberOfIds()):
            pId = idList.GetId(i)
            ids.append(pId)
    ids = np.array(ids)
    return ids

numpy_cells2 = getCellIds(polydata).reshape((-1,3))

print(numpy_cells[:10,1:])
print(numpy_cells2[:10])
assert(np.array_equal(numpy_cells[:,1:], numpy_cells2))
Run Code Online (Sandbox Code Playgroud)