VTK Polygons and other cells as vtkCellArray in Python

After hours of googling and playing with iPython, I finally figured out the way to access polygons or other cells in VTK files using Python.

The Python binding of vtk library seems missing a very important function for users to access cells/polygons in Python, as mentioned in a VTK mailing list post back to 2002 and another post in 2011.

A workaround I just found out is as follows. Suppose you have a VTK file called test.vtk containing the following data.

# vtk DataFile Version 2.0
Cube example
ASCII

DATASET POLYDATA
POINTS 8 float
0.0 0.0 0.0
1.0 0.0 0.0
1.0 1.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
1.0 0.0 1.0
1.0 1.0 1.0
0.0 1.0 1.0

POLYGONS 3 12
3 0 1 2 
3 4 5 6
3 7 4 2

Now I use interactions on iPython to demonstrate the accessing to POLYGONS.

First, we prepare the accessing.
In [1]: import vtk

In [2]: Reader = vtk.vtkDataSetReader()

In [3]: Reader.SetFileName('test.vtk')

In [4]: Reader.Update()

In [5]: Data = Reader.GetOutput()

In [6]: CellArray = Data.GetPolys()

In [7]: Polygons = CellArray.GetData()

Now check the number of cells/polygons and number of points in cells/polygons
In [8]: CellArray.GetNumberOfCells()
Out[8]: 3L

In [9]: Polygons.GetNumberOfTuples()
Out[9]: 12L

All cells/polygons can be accessed like this:
In [10]: for i in xrange(0,  Polygons.GetNumberOfTuples()):
   ....:         print Polygons.GetValue(i)
   ....: 
3
0
1
2
3
4
5
6
3
7
4
2
Please note that the numbers (3's here) indicating sizes of cells (i.e., the numbers at the beginning of every line in Cell/Polygon segment in a VTK file) are also retrieved and printed.

If all your cells/polygons are of the same size, e.g., all triangles, here is an easy way.
In [11]: for i in xrange(0,  CellArray.GetNumberOfCells()):
   ....:         print [Polygons.GetValue(j) for j in xrange(i*3+1, i*3+4) ]
   ....: 
[0L, 1L, 2L]
[3L, 4L, 5L]
[6L, 3L, 7L]

1 comment:

Raymond Wood said...

I am self-studying VTK. Your VTK polygon example is a rarity among the many obtuse VTK examples to be found on the Internet. It meets Einstein's Rule of Elegant Simplicity --- "Make everything as simple as possible, but not simpler".