我有一個包含UNSTRUCTURED POINTS數據集的vtk文件。它有幾個數據集(場,電流,密度)。在Python中讀取ascii vtk文件並將其轉換爲numpy數組
我想在python中加載這個文件,並將每個數據集轉換爲numpy數組,用matplotlib繪製它。這個怎麼做?
我有一個包含UNSTRUCTURED POINTS數據集的vtk文件。它有幾個數據集(場,電流,密度)。在Python中讀取ascii vtk文件並將其轉換爲numpy數組
我想在python中加載這個文件,並將每個數據集轉換爲numpy數組,用matplotlib繪製它。這個怎麼做?
沒有文件的例子,很難給出準確的答案。但從我所瞭解的vtk文件來看,它們可以在4行標題後包含ASCII或二進制數據。
如果VTK的數據是ASCII,然後
np.loadtxt(filename, skiplines=4)
應該工作。再說一遍,如果你有一堆不同的領域,你的文件的結構可能會變得棘手。
如果數據是二進制,你需要使用像
filename.read()
struct.unpack()
或
np.fromfile()
解決方案由vtk_to_numpy函數從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繪製更長的版本可以在這個主題中找到:VTK to Maplotlib using Numpy