8

我有一些 VTK 文件,如下所示:

# vtk DataFile Version 1.0
Line representation of vtk
ASCII
DATASET POLYDATA
POINTS 30 FLOAT
234 462 35
233 463 35
231 464 35
232 464 35
229 465 35
[...]
LINES 120 360
2 0 1
2 0 1
2 1 0
2 1 3
2 1 0
2 1 3
2 2 5
2 2 3
[...]

我想从这些 VTK 文件中获取两个列表:edgesList 和 verticesList:

  • edgesList 应该包含边作为 (FromVerticeIndex, ToVerticeIndex, Weight)-tuples
  • verticesList 应包含作为 (x,y,z) 元组的顶点。索引是edgesList中提到的索引

我不知道如何使用标准 vtk-python 库来提取它。我到目前为止:

import sys, vtk

filename = "/home/graphs/g000231.vtk"

reader = vtk.vtkSTLReader()
reader.SetFileName(filename)
reader.Update()

idList = vtk.vtkIdList() 

polyDataOutput = reader.GetOutput()
print polyDataOutput.GetPoints().GetData()

我的 python-vtk-code 可能没有意义。我更喜欢使用 vtk 库,而不是使用任何自己编写的代码。

这是我自己编写的一段代码。它可以工作,但如果我可以为此使用 vtk 库会更好:

import re
def readVTKtoGraph(filename):
    """ Specification of VTK-files:
        http://www.vtk.org/VTK/img/file-formats.pdf - page 4 """
    f = open(filename)
    lines = f.readlines()
    f.close()

    verticeList = []
    edgeList = []

    lineNr = 0
    pattern = re.compile('([\d]+) ([\d]+) ([\d]+)')
    while "POINTS" not in lines[lineNr]:
        lineNr += 1

    while "LINES" not in lines[lineNr]:
        lineNr += 1
        m = pattern.match(lines[lineNr])
        if m != None:
            x = float(m.group(1))
            y = float(m.group(2))
            z = float(m.group(3))
            verticeList.append((x,y,z))

    while lineNr < len(lines)-1:
        lineNr += 1
        m = pattern.match(lines[lineNr])
        nrOfPoints = m.group(1)
        vertice1 = int(m.group(2))
        vertice2 = int(m.group(3))
        gewicht = 1.0
        edgeList.append((vertice1, vertice2, gewicht))
    return (verticeList, edgeList)
4

2 回答 2

5

STLreader适用于读取 STL 文件。如果您有一个 .vtk 文件并希望读取网格信息(节点、元素及其坐标),则必须使用另一个阅读器(vtkXMLReadervtkDataReader都包含结构化和非结构化网格支持)。然后使用 VTK 包中的vtk_to_numpy函数。

示例代码如下所示:

from vtk import *
from vtk.util.numpy_support import vtk_to_numpy

# load a vtk file as input
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_input_data.vtk")
reader.Update()

#Grab a scalar from the vtk file
my_vtk_array = reader.GetOutput().GetPointData().GetArray("my_scalar_name")

#Get the coordinates of the nodes and the scalar values
nodes_nummpy_array = vtk_to_numpy(nodes_vtk_array)
my_numpy_array = vtk_to_numpy(my_vtk_array )

x,y,z= nodes_nummpy_array[:,0] , 
       nodes_nummpy_array[:,1] , 
       nodes_nummpy_array[:,2]
于 2014-05-04T21:35:59.353 回答
2

我不将 VTK 与 Python 一起使用,但该读者应该能够读取该文件: http ://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/GenericDataObjectReader

以下是如何在 Python 中使用 VTK 阅读器的示例: http ://www.vtk.org/Wiki/VTK/Examples/Python/STLReader

于 2011-12-12T00:34:07.163 回答