I was looking for how to load my own numpy-based transform into a Slicer Grid Transform, and found that this was the closest post on here. After getting something to work, I thought I’d share my example code below.

- You may have to change your directionmatrix to account for differences in coordinates systems (as discussed in other posts on this topic).
- The warpfile is a .npy file holding a numpy array with my transform. This had shape (256, 256, 256, 3) for me.
- All my volumes were 256x256x256, so its hardcoded in, but you should change it according to your needs.

I hope this is helpful for others and will save them the time I spent figuring this out. Also, please feel free to offer corrections if you notice something odd. I’m just beginning to code in Slicer, so there is probably a better way to go about this.

Cheers

```
import numpy as np
import vtk.util.numpy_support
def loadCustomTransform(warpfile):
#create a blank Grid Transform to load into
warpnode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLGridTransformNode')
transformGrid = warpnode.GetTransformFromParent()
displacementGrid = transformGrid.GetDisplacementGrid()
displacementGrid.SetDimensions((256,256,256))
directionmatrix = np.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 1, 0],[0, 0, 0, 1]])
directionVTKmatrix = createVTK4x4matrix(directionmatrix)
transformGrid.SetGridDirectionMatrix(directionVTKmatrix)
#load a numpy file holding your deformation vector field.
#This had shape (256, 256, 256, 3) for me
warpdata = np.load(warpfile)
#process your numpy file so that it works for Slicer
warpdata_reshaped = warpdata.reshape((256*256*256, 3))
vtkwarpdata = vtk.util.numpy_support.numpy_to_vtk(warpdata_reshaped)
#Plug in your own deformation vector field and Voila!
#The warpnode now has your custom data
displacementGrid.GetPointData().SetScalars(vtkwarpdata)
transformGrid.SetDisplacementGridData(displacementGrid)
warpnode.SetAndObserveTransformFromParent(transformGrid)
def createVTK4x4matrix(numpyarray):
#a helper function to change numpy arrays into 4x4 VTK matrices
vtkmatrix = vtk.vtkMatrix4x4()
for i in np.arange(4):
for j in np.arange(4):
vtkmatrix.SetElement(i,j, numpyarray[i,j])
return vtkmatrix
```