8

I want to convert a .VTK ASCII polydata file into numpy array of just the coordinates of the points. I first tried this: https://stackoverflow.com/a/11894302 but it stores a (3,3) numpy array where each entry is actually the coordinates of THREE points that make that particular cell (in this case a triangle). However, I don't want the cells, I want the coordinates of each point (without repeatition). Next I tried this: https://stackoverflow.com/a/23359921/6619666 with some modifications. Here is my final code. Instead of numpy array, the values are being stored as a tuple but I am not sure if that tuple represents each point.

import sys

import numpy
import vtk
from vtk.util.numpy_support import vtk_to_numpy

reader = vtk.vtkPolyDataReader()
reader.SetFileName('Filename.vtk')
reader.ReadAllScalarsOn()
reader.ReadAllVectorsOn()
reader.Update()
nodes_vtk_array= reader.GetOutput().GetPoints().GetData()
print nodes_vtk_array

Please give suggestions.

Community
  • 1
  • 1
ashay makim
  • 81
  • 1
  • 2

2 Answers2

8

You can use dataset_adapter from vtk.numpy_interface:

from vtk.numpy_interface import dataset_adapter as dsa

polydata = reader.GetOutput()
numpy_array_of_points = dsa.WrapDataObject(polydata).Points

From Kitware blog:

It is possible to access PointData, CellData, FieldData, Points (subclasses of vtkPointSet only), Polygons (vtkPolyData only) this way.

alkamid
  • 6,970
  • 4
  • 28
  • 39
6

You can get the point coordinates from a polydata object like so:

polydata = reader.GetOutput()
points = polydata.GetPoints()
array = points.GetData()
numpy_nodes = vtk_to_numpy(array)
Drone2537
  • 525
  • 3
  • 12
  • With `vtk-8.1.0` and `type(polydata) == `, this leads to the following exception: `AttributeError: 'NoneType' object has no attribute 'GetData'` – alkamid May 24 '18 at 08:46
  • Try using 'reader.update()' before getting the output of the reader. – Deformyer Aug 08 '18 at 09:44