如何将VTK文件读入Python数据结构?
我有一些VTK文件,如下所示:如何将VTK文件读入Python数据结构?,python,vtk,Python,Vtk,我有一些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文件中
# 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应将边包含为(从VerticIndex到VerticIndex,权重)-元组
- verticesList应该包含顶点作为(x,y,z)-元组。索引是edgesList中提到的索引
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)
重新导入
def READVTKTROGRAPH(文件名):
“”“VTK文件的规范:
http://www.vtk.org/VTK/img/file-formats.pdf -第4页“
f=打开(文件名)
行=f.读行()
f、 关闭()
垂直列表=[]
edgeList=[]
lineNr=0
pattern=re.compile(“([\d]+)([\d]+)([\d]+)”)
当“点”不在直线[lineNr]中时:
lineNr+=1
当“行”不在行[lineNr]中时:
lineNr+=1
m=图案。匹配(线条[lineNr])
如果m!=无:
x=浮动(m组(1))
y=浮动(m组(2))
z=浮动(m组(3))
垂直列表追加((x,y,z))
而lineNr
我没有将VTK与Python一起使用,但是这个阅读器应该能够读取该文件:
下面是一个如何在Python中使用VTK读取器的示例:
适用于读取STL文件。如果您有一个.vtk文件,并且希望读取网格信息(节点、元素及其坐标),则必须使用另一个读取器(或者,两者都包含结构化和非结构化网格支持)。然后使用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]