Create GridTransform from 3d motion field


I am developing a motion estimation module based on an existing library ; the result of the estimate is 3d vector field of type numpy array (shape = (width, height, depth, 3)) plus other fields (origin, spacing, …).

If I save the motion result from my program (nifti format) and open it as Transformation from slicer it works great: the visualization and the registration of motion are great!

My problem comes in the automatic conversion, in the module, of the estimated motion into a GridTransform. Several utils approach the solution (slicer.util.addVolumeFromArray, slicer.util.loadTransform) but nothing that I can’t use for my case. Would there be an equivalent to slicer.util.addVolumeFromArray for GridTransforms (like slicer.util.addGridTransformFromArray) ?

I tried to manually convert motion field and create GridTransform without success:

# found here
def numpyToVTK(data):
    data_type = vtk.VTK_FLOAT
    shape = data.shape
    flat_data_array = data.flatten()
    vtk_data = vtk.util.numpy_support.numpy_to_vtk(num_array=flat_data_array, deep=True, array_type=data_type)
    img = vtk.vtkImageData()
    img.SetDimensions(shape[0], shape[1], shape[2])
    return img

motionNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLGridTransformNode")
motionVtk = numpyToVTK(motionData)

Can anyone help me ? Thanks

Here are a couple examples of creating grid transforms in python. Yes, a utility function could be helpful so if you want to try abstracting this code a PR would be great.