Search code examples
pythonnumpymemory-managementsimpleitknumpy-memmap

SimpleITK reading a slice of an image


Good day to all.

I happen to have a very large .mha file on my HDD (9.7 Gb) which is a 3D image of a brain. I know this image's shape and for the needs of a report, I would like to extract a slice of it, in order to get a 2D image that I can save as a .png.

The problem is that my 16 Gb RAM computer does not allow me to load the complete image and therefore I would like to know if there is a way to extract a 2D slice of this image without loading the whole image in RAM. For smaller images, I used sitk.GetArrayFromImage(sitk.ReadImage(fileName)) and fed it to pyplot.imshow() but this implies to load the whole image which I want to avoid.

I thought for a time to use numpy.memmap in order to create a temporary .npy file in which I could store the whole array and then get a slice of it but I am having trouble allocating the array from image to it using sitk.GetArrayFromImage(sitk.ReadImage(fileName)).

Does anyone has an idea on how to do it?

Thanks in advance !


Solution

  • With SimpleITK you can read the header of an image, to get it's size information (and other meta-data). Then you can tell the ImageFileReader to only read in a sub-section of the image.

    The following example demonstrates how to do it:

    https://simpleitk.readthedocs.io/en/master/link_AdvancedImageReading_docs.html

    The key is calling ImageFileReader's ReadImageInformation method first. That gets all the header info. Then calling SetExtractIndex and SetExtractSize to specify the sub-region to load before calling Execute to read the image.