Bug: slicer.util.loadVolume does not accept pathlib Path (only string)

My slicer is version 5.2.1

This runs successfully:

slicer.util.loadVolume(str(pathlib.Path(segmentation_dir_path) / "img_0.nii.gz"))

With the following message:

Loaded volume from file: /home/redacted/redacted/redacted/redacted/redacted/redacted/redacted/Public_Patient0/img_0.nii.gz. Dimensions: 200x249x292. Number of components: 1. Pixel type: float.

"Volume" Reader has successfully read the file "/home/redacted/redacted/redacted/redacted/redacted/redacted/redacted/Public_Patient0/img_0.nii.gz" "[0.20s]"

This crashes:

slicer.util.loadVolume(pathlib.Path(segmentation_dir_path) / "img_0.nii.gz")

With the following stacktrace:

Traceback (most recent call last):
  File "/home/redacted/redacted/redacted/Main/Main.py", line 325, in onLoadSegmentationDirectory
    slicer.util.loadVolume(segmentation_dir_path / "img_0.nii.gz")
  File "/opt/Slicer-5.2.1-linux-amd64/bin/Python/slicer/util.py", line 937, in loadVolume
    return loadNodeFromFile(filename, filetype, properties, returnNode)
  File "/opt/Slicer-5.2.1-linux-amd64/bin/Python/slicer/util.py", line 699, in loadNodeFromFile
    raise RuntimeError(errorMessage)
RuntimeError: Failed to load node from file: /home/redacted/redacted/redacted/redacted/redacted/redacted/redacted/Public_Patient0/img_0.nii.gz
Error: Loading  -  load failed.

By crash do you mean that the application actually crashed, or just the image was not loaded?

pathlib.Path objects are not supported yet in Slicer’s Python API. It would require much more work for Slicer developers to support it than for users to add the str(), so it has not been high on the priority list. I’ve added an issue to keep track of this request:

Would you consider contributing to Slicer by adding pathlib.Path support to the methods that you are using, for example for loadVolume?

1 Like

The image was just not loaded (ie, the entire program did NOT crash), sorry for not being clear.

I’ve submitted a pull requested with the change to support pathlib.Path (more generally, it will assume the str method of the object will return the path). I’ve done this for both loadNodeFromFile and loadNodesFromFile (loadVolume calls loadNodeFromFile).

Here is the link to the mentioned pull request: