Load DICOM files and segmentation file (.nrrd)

Hi guys,

I have to do a python script that must open a DICOM series from a folder and load a segmentation in that same scene. It has a part that loads the series and other that loads a segmentation. Both parts work perfectly when used isolated, but when combined it fails sometimes.

I think it is because it tries to load the .nrrd before the DICOM is completely loaded. I’ve been trying to introduce some comprobations to see if it is loaded completely but it didn’t work.

Here is my complete code:

def main():

    # ----- Load of DICOM series ----------

    loadedNodeIDs = []  # this list will contain the list of all loaded node IDs

    if len(sys.argv) > 1:
        dicomDataDir = sys.argv[1]
        dicomDataDir = r'C:\Users\Sergio\Desktop\Slicer\OriginalDICOM'

    dicomFiles = slicer.util.getFilesInDirectory(dicomDataDir)
    loadablesByPlugin, loadEnabled = DICOMUtils.getLoadablesFromFileLists([dicomFiles])
    loadedNodeIDs = DICOMUtils.loadLoadables(loadablesByPlugin)
    while(not slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")): # Kind of comprobation to see if there is any volume loaded so it doesnt try to load the segmentation so early, I think it crashes if it does so

    # ------ Load of segmentation ----------

    seg = slicer.util.loadSegmentation(r'C:\Users\Sergio\Desktop\Slicer\Python\F0QalYvbzsoZhi.nrrd')
    seg.GetSegmentation().SetConversionParameter("Smoothing factor", "0.30")


It just crashes, does not show any error message, and it crashes less times when the .nrrd is smaller and more when it is bigger.

Does it work well if you use the latest Slicer Preview Release?

No, it doesn’t, I don’t know exactly why. I’ve tried the 4.13-2022-03-19 version and the 4.13-2022-04-01 version, this last one I just downloaded it, even though it says there is a 2022-04-04 one.

I have it working properly for the moment in the last stable version, the 4.11-20210226, but I found another problem. In this version it loads everything ok, but the segmentation does not display in 3D, it appears hidden so you have to go to the segmentEditor and set every segment visible. The code is the same.

Is there any way that I can introduce in my script to set all segments visible?

Thank you for your reply.

Don’t use the latest Slicer Stable Release, it is too old and will be replaced by the latest Slicer Preview Release very soon.

If no Slicer core changes are made then the date of the installer remains the same. So, a few days difference compared to today’s date is completely normal.

sys.sleep(2) just blocks the application for a while, it will not make any difference except slice w down the loading. You can use slicer.app.processEvents() for allowing all modules react to the loading of a new data set.