Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

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() 
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.