[英]Reading ascii vtk file in python and converting it to numpy array
我有一個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繪圖的較長版本: 使用Numpy的VTK到Maplotlib
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.