我有一个包含 UNSTRUCTURED POINTS 数据集的 vtk 文件。它内部有几个数据集(场、电流、密度)。
我想在 python 中加载这个文件并将每个数据集转换为 numpy 数组以使用 matplotlib 绘制它。这个怎么做?
如果没有您的文件示例,很难给出准确的答案。但是根据我对 vtk 文件的了解,它们可以在 4 行标题之后包含 ASCII 或二进制数据。
如果 vtk 中的数据是 ASCII,那么
np.loadtxt(filename, skiplines=4)
应该管用。同样,如果您有一堆不同的字段,您的文件结构可能会使这变得棘手。
如果数据是二进制的,你需要使用类似的东西
filename.read()
struct.unpack()
或者
np.fromfile()
解决方案由VTK 包中的vtk_to_numpy函数给出。根据网格格式(结构化或非结构化),它与 Vtk 网格阅读器一起使用:在您的情况下, vtkXMLUnstructuredGridReader是一个不错的选择。
示例代码如下所示:
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)
可以在此线程中找到带有 matplotib 绘图的更长版本:VTK to Maplotlib using Numpy