Question about transform to the segmentation model

I would like to use python script to move the segmentation model which is imported by a STL model.

I try to use these code to finish it.

Script repository — 3D Slicer documentation

Script repository — 3D Slicer documentation

I combine them together, but it is not work.

# Create a 4x4 transformation matrix as numpy array
transformNode = ...
transformMatrixNP = np.array(
  [[0.92979,-0.26946,-0.25075,52.64097],
  [0.03835, 0.74845, -0.66209, -46.12696],
  [0.36608, 0.60599, 0.70623, -0.48185],
  [0, 0, 0, 1]])

# Update matrix in transform node
transformNode.SetAndObserveMatrixTransformToParent(slicer.util.vtkMatrixFromArray(transformMatrixNP)
slicer.mrmlScene.AddNode(transformNode)
rcm_1.SetAndObserveTransformNodeID(transformNode.GetID())

I would like to know the problem of my code and how to improve it.
Is it have any other way to do the automatic transform on segmentation model?

The 2nd line of your code is not functional python code. The ... needs to be replaced with wherever you are getting the transform node from. Simplest is to create it. Assuming your model node is named rcm_1, the following code should work.

import numpy as np # need to import numpy before np.array will work
transformNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLTransformNode', 'myNewTransformNode')
transformMatrixNP = np.array(
  [[0.92979,-0.26946,-0.25075,52.64097],
  [0.03835, 0.74845, -0.66209, -46.12696],
  [0.36608, 0.60599, 0.70623, -0.48185],
  [0, 0, 0, 1]])
# Change transformation matrix in the transform node
transformNode.SetAndObserveMatrixTransformToParent(slicer.util.vtkMatrixFromArray(transformMatrixNP))
# Apply transformation to the model in rcm_1
rcm_1.SetAndObserveTransformNodeID(transformNode.GetID())

You mentioned that your segmentation is an imported STL model and this code will work for that. Note that in Slicer, not just models, but also segmentations, images, and markups can all have transforms applied.

Hopefully this code helps you get started.

2 Likes

It works well :grinning:.
Thanks you so much.

1 Like