Import Numpy File in as image volume

I have been working with trying to compress files down to NPY and NPZ files to save binary labelmaps for some of my data. Is there a way to import them into slicer? Every time I try the load data option with it, it doesn’t seem to want to load into the scene?

NPY/NPZ file format is not widely supported outside numpy and I’m not sure if there is a standardized way of specifying essential metadata. In contrast, existing standard medical image computing file formats don’t have these issues. Since we already have more file formats than we need, it would be better not to introduce new ones. You can of course use NPY/NPZ for temporary, application-specific storage and we may consider adding readers/writers for these files if there is a standard way of using them for medical image storage.

Instead of saving as NPY/NPZ, it is possible to ITK to save the image in a file format supported by Slicer.

For example

$ python -m pip install --upgrade pip
$ python -m pip install itk
$ python
>>> [... generate numpy array `arr`]
>>> import itk
>>> image = itk.GetImageFromArray(arr)
>>> itk.imwrite(image, 'image.nrrd')

Hope this helps,
Matt

2 Likes

Numpy authors introduced numpy format without asking us anything. And people unaware of ITK and Slicer have been saving images in .npy format for years now. It would be convenient if Slicer was able to open them.

Implementing npy format support in C++ ITK would be a lot of work. Supporting NPY/NPZ file format via Python would be easy - use numpy to load .npy file, then convert it into an ITK image via itk.GetImageFromArray(arr) or itk.GetImageViewFromArray(arr). I know that Slicer defers file opening to ITK. How hard would it be to add this Python loader to Slicer?

It’s very easy to add a custom reader/writer plugin to Slicer. It’s just a hidden scripted module that registers a subclass something like this. Adding NPY/NPZ in a similar way would be great.

But we also want to support at least the direction and spacing info as metadata. We’ve been discussing using xarray and/or zarr for these probably in ngff. I know @thewtex has been working on that and I think it is a good direction for Slicer but we haven’t gotten too serious yet. Here’s and example zarr reader for ngff.

1 Like