What’s the preferred way to iterate over an vtkIdTypeArray in Python? There is NewIterator, but I don’t know how to use it.
This may help you ForLoop.
Thabks Ronald for all your work with vtkbool
The iterator returned by NewIterator
was designed for use from C++, it’s not usable from Python.
Probably the easiest way to deal with VTK arrays from Python is via numpy.
The numpy.asarray()
function creates an array that is a “view” of the same memory buffer used by the VTK array:
from vtkmodules.vtkCommonCore import vtkIdTypeArray
import numpy as np
ids = vtkIdTypeArray()
ids.InsertNextValue(10)
ids.InsertNextValue(3)
# use numpy array as a "view" of a VTK array
np.asarray(ids)
# returns array([10, 3], dtype=int64)
# use numpy to modify the values in a VTK array
a = np.asarray(ids)
a *= 2
print([ids.GetValue(0), ids.GetValue(1)])
[20, 6]
There is a danger to this method, however: if the VTK array’s memory buffer is reallocated (for example, when the the array is resized), then the numpy array ends up with a dangling pointer. So the numpy array can only safely be used within a short scope where it is guaranteed that no resizing will occur.
You can also construct a new numpy array from a VTK array, which is safer if you plan to keep the numpy array arround for a while:
from vtkmodules.vtkCommonCore import vtkPoints
import numpy as np
points = vtkPoints()
points.InsertNextPoint(0,1,2)
points.InsertNextPoint(0,1,5)
a = np.array(points.GetData())
print(a)
# [[0. 1. 2.]
# [0. 1. 5.]]
In the past there has been discussion of Python iterators for VTK arrays (I’m too lazy to search for a link). The idea was to have two iterators: one that would iterate over the tuples in the array, and one that would iterate over the values (i.e. iterate over the flattened array).
It’s also worth mentioning that you can create a memoryview from a VTK array:
from vtkmodules.vtkCommonCore import vtkIdTypeArray
ids = vtkIdTypeArray()
ids.InsertNextValue(10)
ids.InsertNextValue(3)
memoryview(ids).tolist()
[10, 3]