You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python VTK包获取VTK文件中cell_data的fielddata值

如何获取VTK结构化网格文件中的CELL_DATA字段值?

问题背景

我有一个结构化网格VTK文件,内容如下:

# vtk DataFile Version 5.1
vtk output
ASCII
DATASET STRUCTURED_GRID
DIMENSIONS 3 2 3
POINTS 18 double
0 0 0 1 0 0 2 0 0 
0 -0 0 1 -2.4492935983e-16 0 2 -4.8985871966e-16 0 
0 0 2 1 0 2 2 0 2 
0 -0 2 1 -2.4492935983e-16 2 2 -4.8985871966e-16 2 
0 0 4 1 0 4 2 0 4 
0 -0 4 1 -2.4492935983e-16 4 2 -4.8985871966e-16 4 

CELL_DATA 4
FIELD FieldData 1
uniform 1 4 double
0.15915494309 0.15915494309 0.053051647697 0.053051647697 

需要提取其中CELL_DATA下名为uniform的字段值:[0.15915494309, 0.15915494309, 0.053051647697, 0.053051647697]。

已编写部分Python代码,但卡在获取目标值的环节:

import vtk

filename = 'myfile.vtk'

reader = vtk.vtkGenericDataObjectReader()
reader.SetFileName(filename)
reader.ReadAllFieldsOn()
reader.Update()
#... not sure what goes here

尝试过reader.GetOutput().GetFieldData()但没有效果,请问如何获取该fielddata值?

解决方案

你需要针对CELL_DATA而非全局FieldData来提取字段,完整代码如下:

import vtk

filename = 'myfile.vtk'

reader = vtk.vtkGenericDataObjectReader()
reader.SetFileName(filename)
reader.ReadAllFieldsOn()
reader.Update()

# 获取输出的结构化网格对象
grid = reader.GetOutput()

# 获取CELL_DATA对应的字段集合
cell_data = grid.GetCellData()

# 根据名称获取uniform字段的vtk数组
uniform_array = cell_data.GetArray('uniform')

# 将vtk数组转换为Python列表
uniform_values = [uniform_array.GetValue(i) for i in range(uniform_array.GetNumberOfValues())]

# 输出结果
print(uniform_values)

关键步骤说明

  • 目标字段属于CELL_DATA,因此需要先获取结构化网格对象,再调用GetCellData()获取单元格数据集合,而不是直接使用GetFieldData()(后者对应全局字段)。
  • 通过GetArray('uniform')根据字段名称提取对应的vtk数组对象。
  • 遍历vtk数组的每个元素,转换为Python列表,方便后续处理。

内容的提问来源于stack exchange,提问作者Jon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:25:05