Search code examples
pythonvtkenthoughtmayavi

How to extract the vertex data from a tvtk PolyData instance?


I am trying to extract the vertex data from a tvtk.PolyData instance. For example:

from numpy import array
from tvtk.api import tvtk
from mayavi.sources.vtk_data_source import VTKDataSource
from mayavi.modules.surface import Surface
from mayavi import mlab

pointArr=array([[0,0,0],[1,0,0],[1,1,0],[0,1,0],[0,1,1],[1,1,1]],dtype="float64")
faceArr=array([[0,1,2,3],[2,3,4,5]])
faces = tvtk.PolyData()
faces.points=pointArr
print faces.points
faces.polys=faceArr
faces.point_data.scalars = pointArr[:,2]
faces.point_data.scalars.name = 'Height'
src = VTKDataSource(data = faces)
mlab.pipeline.surface(src, opacity=1.)
mlab.show()

This prints

vtkPoints (0x9811398)
  Debug: Off
  Modified Time: 838816
  Reference Count: 2
  Registered Events: 
    Registered Observers:
      vtkObserver (0x98112b8)
        Event: 33
        EventName: ModifiedEvent
        Command: 0x9811688
        Priority: 0
        Tag: 1
  Data: 0x9811480
  Data Array Name: Points
  Number Of Points: 6
  Bounds: 
    Xmin,Xmax: (0, 1)
    Ymin,Ymax: (0, 1)
    Zmin,Zmax: (0, 1)

What is happening here? I expected to see the NumPy array:

[[ 0.  0.  0.]
 [ 1.  0.  0.]
 [ 1.  1.  0.]
 [ 0.  1.  0.]
 [ 0.  1.  1.]
 [ 1.  1.  1.]]

Solution

  • The whole point of tvtk is to handle conversions between python objects (including numpy arrays) and VTK object holding classes. If you investigate faces.points, you'll see it's actually a tvtk class instance called Points, but you can easily get back the numpy representation using

    np.array( faces.points )
    

    The different views should not copy memory, so all this is pretty efficient.

    EDIT: naturally tvtk also provides an event-based API and graphical editing elements