Rojj
Rojj

Reputation: 1210

Add scalars to vtk file (vtk 3.0 legacy) in Python

I am trying to add a calculated scalar to an existing VTK file.

A simplified version of my code is the following

import vtk
import os
import numpy as np

reader = vtk.vtkDataSetReader()   
reader.SetFileName(vtk_file_name)
reader.ReadAllScalarsOn()
reader.Update()
data = reader.GetOutput() #This contains all data from the VTK
cell_data = data.GetCellData() #This contains just the cells data
scalar_data1 = cell_data.GetArray('scalar1')
scalar_data2 = cell_data.GetArray('scalar2')

scalar1 = np.array([scalar_data1.GetValue(i) for i in range(data.GetNumberOfCells())])
scalar2 = np.array([scalar_data2.GetValue(i) for i in range(data.GetNumberOfCells())])

scalar3 = scalar1 - scalar2

writer = vtk.vtkDataSetWriter()

At this point I assume that I need to add a vtkArray to data by using data.SetCell

The problem is that SetCell asks for a vtkCellArray and I have not managed yet to convert my array scalar3 to a vtkCellArray.

Is this the right approach? Any suggestion?

Upvotes: 2

Views: 2467

Answers (1)

Cory Quammen
Cory Quammen

Reputation: 1263

You actually need to use cell_data.AddArray() to add your array. SetCell() would actually modify the topology of your data set.

Rojj is correct about using vtk.numpy_support to convert back and forth between vtkArrays and numpy arrays. You can use something like the following:

import vtk
from vtk.util import numpy_support
...
scalar3_array = numpy_support.numpy_to_vtk(scalar3)
scalar3_array.SetName('scalar3')
cell_data.AddArray(scalar3)

Upvotes: 2

Related Questions