How can I read a VTK file into a Python datastructure?

Viewed 9027

I have some VTK-files, which look like this:

# 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
[...]

I would like to get two lists out of these VTK-files: edgesList and verticesList:

  • edgesList should contain the edges as (FromVerticeIndex, ToVerticeIndex, Weight)-tuples
  • verticesList should contain the vertices as (x,y,z)-tuples. The index is the index mentioned in edgesList

I have no idea how to extract this with the standard-vtk-python library. I got so far:

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()

Its possible that my python-vtk-code doesn't make sense. I would prefer to use the vtk library and not use any self-written pieces of code.

Here is my self-written piece of code. It works, but it would be better if I could use the vtk library for this:

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 Answers
Related