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?

2 Answers 2

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() 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.