I have an existing matlab.double([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]) matlab matrix. I would like to turn it into a vtkMatrix4x4 so I can use it as an argument in PokeMatrix to transform a second actor. Is there a function that converts a matlab matrix to vtkMatrix4x4, instead to assigning each individual element in matlab matrix to vtk matrix.
You can use helper functions like these to convert between numpy arrays and 3x3 or 4x4 VTK matrices:
The scripts just copy elements one by one but since matrices are so small, we did not run into any perceivable performance issues. You can get access to large VTK arrays without copying, using helper functions in numpy_support in VTK util package.
@dgobbi Since conversion between vtkMatrix3x3/vtkMatrix4x4 and numpy matrices is needed quite often, would you consider adding such converters to VTK’s numpy_support.py? Could it work similarly to array accessors (direct access to memory) instead of doing element-wise copy?
Conversion is possible with the DeepCopy() methods that were originally written to be used with C arrays. The ndarray.ravel() method returns a flattened view of the numpy array that can be used with DeepCopy:
import numpy as np
m = vtk.vtkMatrix4x4()
# make some numpy arrays
a = np.random.rand(4,4)
b = np.zeros((4,4))
# copy from numpy to vtkMatrix4x4
# copy from vtkMatrix4x4 to numpy
This uses the Python sequence protocol rather than the Python buffer protocol. For a 16-element matrix, however, there can’t be a significant performance difference.
I don’t really do maintenance of the VTK numpy support code. But if somebody submits a patch, I’d be happy to review it.
The vtkDataArray trick can be extended to any VTK class that provides a pointer to its internal data. So it would be possible to implement this for vtkPoints, vtkIdList, vtkLookupTable, etc.
However, vtkMatrix4x4 does not have a public API method that returns a pointer to its elements. If a GetPointer() method or something similar was added to this class, then the wrappers could be modified to make it work with zero-copy read-write access.