如何将VTK文件读取到Python数据结构中?
我有一些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应该包含边的信息,每条边用一个三元组表示,格式是(起始顶点索引, 结束顶点索引, 权重)
- 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代码不太合理。我更希望使用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)
2 个回答
5
STLreader 是用来读取 STL 文件的工具。如果你有一个 .vtk 文件,并且想要读取网格信息(比如节点、元素及它们的坐标),你需要使用其他的读取工具(可以选择 vtkXMLReader 或者 vtkDataReader,这两者都支持结构化和非结构化网格)。然后你可以使用 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]
2
我不太用Python来操作VTK,但这个读取器应该可以读取那个文件:http://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/GenericDataObjectReader
这里有一个关于如何在Python中使用VTK读取器的例子:http://www.vtk.org/Wiki/VTK/Examples/Python/STLReader