VTK to Matplotlib using Numpy VTK to Matplotlib using Numpy numpy numpy

VTK to Matplotlib using Numpy


I finally figured a way (maybe not the optimal) that does the job. The example here is contour plotting a temperature field extracted from a vtk file:

import matplotlib.pyplot as pltimport matplotlib.cm as cmfrom scipy.interpolate import griddataimport numpy as npimport vtkfrom vtk.util.numpy_support import vtk_to_numpy# load a vtk file as inputreader = vtk.vtkXMLUnstructuredGridReader()reader.SetFileName("my_input_data.vtk")reader.Update()# Get the coordinates of nodes in the meshnodes_vtk_array= reader.GetOutput().GetPoints().GetData()#The "Temperature" field is the third scalar in my vtk filetemperature_vtk_array = reader.GetOutput().GetPointData().GetArray(3)#Get the coordinates of the nodes and their temperaturesnodes_nummpy_array = vtk_to_numpy(nodes_vtk_array)x,y,z= nodes_nummpy_array[:,0] , nodes_nummpy_array[:,1] , nodes_nummpy_array[:,2]temperature_numpy_array = vtk_to_numpy(temperature_vtk_array)T = temperature_numpy_array#Draw contoursnpts = 100xmin, xmax = min(x), max(x)ymin, ymax = min(y), max(y)# define gridxi = np.linspace(xmin, xmax, npts)yi = np.linspace(ymin, ymax, npts)# grid the dataTi = griddata((x, y), T, (xi[None,:], yi[:,None]), method='cubic')  ## CONTOUR: draws the boundaries of the isosurfacesCS = plt.contour(xi,yi,Ti,10,linewidths=3,cmap=cm.jet) ## CONTOUR ANNOTATION: puts a value labelplt.clabel(CS, inline=1,inline_spacing= 3, fontsize=12, colors='k', use_clabeltext=1)plt.colorbar() plt.show() 

enter image description here


I don't know what's you dataset looks like, so here is only some method that you can get the point locations and scalars values:

from vtk import *from vtk.util.numpy_support import vtk_to_numpy# load input datareader = vtk.vtkGenericDataObjectReader()reader.SetFileName(r"C:\Python27\VTKData\Data\uGridEx.vtk")reader.Update()ug  = reader.GetOutput()points = ug.GetPoints()print vtk_to_numpy(points.GetData())print vtk_to_numpy(ug.GetPointData().GetScalars())

it will be a little easy if you can use tvtk:

from tvtk.api import tvtkreader = tvtk.GenericDataObjectReader()reader.file_name = r"C:\Python27\VTKData\Data\uGridEx.vtk"reader.update()ug = reader.outputprint ug.points.data.to_array()print ug.point_data.scalars.to_array()

if you want to do contour plot in matplotib, I think you need a grid, you may need use some VTK class to convert the dataset to a grid, such as vtkProbeFilter.