我有一些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)元组
- 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)