2011-07-13 113 views
7

我有一些VTK-文件,它看起來像這樣:如何將VTK文件讀入Python數據結構?

# 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應該包含邊緣as(FromVerticeIndex,ToVerticeIndex,Weight)-tuples
  • verticesList應該包含頂點爲(x,y,z)-tuples。索引是在邊緣提到的索引

我不知道如何提取這與標準的vtk-python庫。我到目前爲止:

它可能是我的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) 

回答

4

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]