matlab martix to vtkMatrix4x4

Hello,

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.

Any help would be greatly appreciated.
Thanks!

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
import vtk

m = vtk.vtkMatrix4x4()
# make some numpy arrays
a = np.random.rand(4,4)
b = np.zeros((4,4))
# copy from numpy to vtkMatrix4x4
m.DeepCopy(a.ravel())
# copy from vtkMatrix4x4 to numpy
m.DeepCopy(b.ravel(), m)
print(a)
print(b)
print(m)

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.

1 Like

This is great, thank you! I’ll update the utility functions in Slicer accordingly and if they prove to work well then I’ll submit a pull request to VTK, too.

Would it be possible to set up read/write access (not copy) similarly to how VTK data arrays can be read/written using numpy arrays? I don’t have any use case for this, just for my curiosity.

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.

Thanks for the explanation. It’s good to know this.