Tracking cursor movements to access voxel values

HI Kyle, thank you for helping us on this (I work with Leo).

I’m posting in case other people can benefit from our attempt - I believe we managed to get it working by simply moving the computationally-expensive calls outside the mouse movement loop. The console is now printing reasonable values for voxels at coordinates:

This is our current code:

import numpy as np

ras = [0, 0, 0]
volumeNode = slicer.util.getNode("MRHead")
# Apply that transform to get volume's RAS coordinates
transform_ras_to_volume_ras = vtk.vtkGeneralTransform()
slicer.vtkMRMLTransformNode.GetTransformBetweenNodes(None, volumeNode.GetParentTransformNode(), transform_ras_to_volume_ras)
# Get volume as slicer array
a = arrayFromVolume(volumeNode)

def onMouseMoved(observer,eventid):
    # Get point coordinate in RAS
    ras = [0, 0, 0]
    crosshairNode.GetCursorPositionRAS(ras)
    point_volume_ras = transform_ras_to_volume_ras.TransformPoint(ras[0:3])
    # Get voxel coordinates from physical coordinates
    volume_ras_to_ijk = vtk.vtkMatrix4x4()
    volumeNode.GetRASToIJKMatrix(volume_ras_to_ijk)
    point_ijk = [0, 0, 0, 1]
    volume_ras_to_ijk.MultiplyPoint(np.append(point_volume_ras, 1.0), point_ijk)
    point_ijk = [ int(round(c)) for c in point_ijk[0:3] ]
    # Get markup's position
    x, y, z = point_ijk[0], point_ijk[1], point_ijk[2]
    value = a[z,y,x]
    print(value)

crosshairNode=slicer.util.getNode("Crosshair")
observerId = crosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, onMouseMoved)
2 Likes