2

I have a vtk file that contains UNSTRUCTURED POINTS datasets. It has several datasets inside (fields, currents, densities).

I would like to load this file in python and convert every dataset to the numpy array to plot it with matplotlib. How to do this?

Sleepyhead
  • 1,009
  • 1
  • 10
  • 27

2 Answers2

4

Without having an example of your file, it's hard to give a precise answer. But from what I know about vtk files, they can contain either ASCII or binary data after a 4 line header.

If the data in the vtk is ASCII, then

np.loadtxt(filename, skiplines=4)

should work. Again, the structure of your file could make this tricky if you have a bunch of different fields.

If the data is in binary, you will need to use something like

filename.read()
struct.unpack()

or

np.fromfile() 
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
captain_M
  • 287
  • 2
  • 10
1

The solution is given by vtk_to_numpy function from the VTK package. It is used along a Vtk grid reader depending on the grid format (structured or unstructured): vtkXMLUnstructuredGridReader is a good choice in your case.

A sample code would look like:

from vtk import *
from vtk.util.numpy_support import vtk_to_numpy

# load a vtk file as input
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_input_data.vtk")
reader.Update()

#The "Temperature" field is the third scalar in my vtk file
temperature_vtk_array = reader.GetOutput().GetPointData().GetArray(3)

#Get the coordinates of the nodes and their temperatures
nodes_nummpy_array = vtk_to_numpy(nodes_vtk_array)
temperature_numpy_array = vtk_to_numpy(temperature_vtk_array)

x,y,z= nodes_nummpy_array[:,0] , 
       nodes_nummpy_array[:,1] , 
       nodes_nummpy_array[:,2]


(...continue with matplotlib)

A longer version with matplotib plotting can be found in this thread: VTK to Maplotlib using Numpy

Community
  • 1
  • 1
SAAD
  • 759
  • 1
  • 9
  • 23