Problem when getting the vtkImageData of a reformatted slice shown in Red widget

SUMMARY

  • Operating system: Windows 10
  • Slicer version: 5.0.2
  • Expected behavior: getting the vtkImageData of a reformatted slice shown in Red widget.
  • Actual behavior: the returned vtkImageData is of another volume in the background layer.

DETAIL CONTENT

Hello Prof. Andras and everyone else,

I have a question on how to get the reslice image from a slice node. And all of the following steps were performed by code.

[1] To begin, I have loaded several scalar volumes into 3D Slicer. I suppose their names are in the background-to-foreground order as vol0, vol1, vol2, and vol3.

[2] Next, I have successfully shown a reformatted slice of vol2 as the background layer of the ‘Red’ widget. Please see the attached image for reference.
what_I_see

[3] Now, I want to obtain above reformatted slice as a vtkImageData (not the screenshot) by following code:

sliceLogic = slicer.app.applicationLogic().GetSliceLogicByLayoutName(‘Red’)
sliceLayerLogic = sliceLogic.GetBackgroundLayer()
sliceLayerLogic.SetVolumeNode(vol2)
reslice = sliceLayerLogic.GetReslice()
reslicedImage = vtk.vtkImageData()
reslicedImage.DeepCopy(reslice.GetOutput())
(reslicedImage is then used for exporting PNG file)

However, when executing the code within my scripted module, the returned image is the slice of vol0 (instead of vol2). Meanwhile, if I type code into the Slicer console, the returned image is as expected (slice of vol2).

I can’t figure out what my mistake is. So I would like to ask for your help or advice.

Thank you!

Using the rendering infrastructure to do computation is complicated by the fact that many changes don’t occur until the next render cycle, which is event driven. You should be able to fix this case with the call below added before the DeepCopy. Excluding user input avoids having some other user click initiate an action in the middle of your code.

slicer.app.processEvents(qt.QEventLoop.ExcludeUserInputEvents)

1 Like

Thank Pieper for the solution and advice!
My code can run as expected now.

Sincerely!