python - 在 python 中从 VTK 文件中检索面和点

标签 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)

这是因为 numpy_nodes 包含所有点的 x、y、z 坐标,但我无法检索将此模型的各个方面与相应点相关联的列表。

我试过:

facets= polydata.GetPolys()
array = facets.GetData()
numpy_nodes = vtk_to_numpy(array)

但是 numpy_nodes 只是一个一维数组,我希望它是一个二维数组(大小为 3 * 面数),其中第一个维度包含面对应点的数量(如.ply 文件)。

欢迎就如何进行提出任何建议

最佳答案

你快到了。为了允许不同类型的单元格(三角形、四边形等),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), 
               ...
              ]

如果所有多边形都属于同一类型,即所有 in_i==n,只需 reshape 一维数组以获得可解释的内容:

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))

可以删除 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))

关于python - 在 python 中从 VTK 文件中检索面和点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201888/

相关文章:

c++ - VTK的ProjectionTransformMatrix和OpenGL的GL_PROJECTION有什么区别?

python - 如何使用Python ast模块的NodeTransformer类

python - 为什么我会收到此错误 : AttributeError: 'LocalStack' object has no attribute '__ident_func__' in SQLAlchemy

python - 在 ipython 中交换 2 个映射 2D 数组的值,

python - 切片 numpy 数组时出现意外的形状

python - 使用 Python 根据列表值对矩阵列进行排序

c++ - 在 vtkXYPlotActor 中绘制网格线

python - VTK : how to read grid cells' lenth, 宽度和高度?

python - 使用 Xpath、Python 从网站提取信息

python - 混合数值和分类数据观测值之间成对距离计算的有效实现