Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a .VTK polydata file and converting it into Numpy array

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.

like image 557
ashay makim Avatar asked Jul 21 '16 12:07

ashay makim


2 Answers

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.

like image 112
alkamid Avatar answered Nov 01 '22 11:11

alkamid


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)
like image 36
Drone2537 Avatar answered Nov 01 '22 12:11

Drone2537