在python中读取ascii vtk文件并将其转换为numpy数组
我有一个包含非结构化点数据集的vtk文件。它内部有多个数据集(场、电流、密度)在python中读取ascii vtk文件并将其转换为numpy数组,python,numpy,vtk,Python,Numpy,Vtk,我有一个包含非结构化点数据集的vtk文件。它内部有多个数据集(场、电流、密度) 我想用python加载这个文件,并将每个数据集转换为numpy数组,以使用matplotlib进行打印。如何做到这一点?如果没有文件示例,很难给出准确的答案。但从我对vtk文件的了解来看,它们可以在4行标题后包含ASCII或二进制数据 如果vtk中的数据是ASCII,则 np.loadtxt(filename, skiplines=4) 应该有用。同样,如果您有一堆不同的字段,那么文件的结构可能会使这个问题变得棘手
我想用python加载这个文件,并将每个数据集转换为numpy数组,以使用matplotlib进行打印。如何做到这一点?如果没有文件示例,很难给出准确的答案。但从我对vtk文件的了解来看,它们可以在4行标题后包含ASCII或二进制数据 如果vtk中的数据是ASCII,则
np.loadtxt(filename, skiplines=4)
应该有用。同样,如果您有一堆不同的字段,那么文件的结构可能会使这个问题变得棘手
如果数据是二进制的,则需要使用
filename.read()
struct.unpack()
或
解决方案由vtk软件包中的函数提供。它随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绘图的较长版本:
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)