我有:
.mha
)文件我试图将标量值映射到网格物体,并且我希望在paraview中可视化结果。
现在,我的输出只有2个不同的标量值,它应该肯定有更多。我知道我的输入数据不是问题,因为我有一个软件可以进行映射,结果很好。我想把它写成一个脚本来自动化它,并开始理解VTK的概念。
In [1]: import vtk
from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy
output_file_name = '/tmp/test.vtk'
input_mesh = 'vtk_file.vtk'
input_mha = 'mha_file.mha'
# Read the MHA file (scalars)
reader = vtk.vtkMetaImageReader()
reader.SetFileName(input_mha)
reader.Update()
vtk_image = reader.GetOutput()
scalar_data = vtk_image.GetPointData().GetScalars()
# Read the VTK file (scalars)
reader = vtk.vtkPolyDataReader()
reader.SetFileName(input_mesh)
reader.Update()
polydata = reader.GetOutput()
In [2]: # Getting the number of triangles
n_cells = polydata.GetNumberOfCells()
# Initializing an array with the right shape
cell_data = np.zeros(n_cells)
# Iterating through the triangles and getting the corresponding scalar value
for i in range(n_cells):
cell = polydata.GetCell(i)
points = cell.GetPoints()
np_pts = np.array([points.GetPoint(i) for i in range(points.GetNumberOfPoints())])
centroid = np_pts.mean(axis=1)
centroid_id = vtk_image.FindPoint(centroid)
value = scalar_data.GetValue(centroid_id)
cell_data[i] = value
polydata.GetCellData().SetScalars(numpy_to_vtk(cell_data))
Out[2]: 0
In [3]: writer = vtk.vtkPolyDataWriter()
writer.SetFileName(output_file_name)
writer.SetInputData(polydata)
writer.SetScalarsName('a_name')
writer.Write()
Out[3]: 1
这个1
作为最终输出必须意味着我做错了...
答案 0 :(得分:0)
事实证明我所做的一切都很好,除了三角形质心计算应该是centroid = np_pts.mean(axis=0)
而不是centroid = np_pts.mean(axis=1)