nibabel icon indicating copy to clipboard operation
nibabel copied to clipboard

Load from a file pointer instead of filepath string

Open Ouwen opened this issue 3 years ago • 1 comments

I was wondering if there is an easy way for file pointers to be supported when loading nii files instead of string paths. This would allow loading from memory buffers or streaming data over network.

Ouwen avatar Jun 15 '21 18:06 Ouwen

Hi @Ouwen ! Most of the main image classes support a .from_bytes() method that can be used to load data directly into an image. (Image instances conversely also support a .to_bytes() method.)

For example, the following should work (given you have img.nii.gz locally):

>>> import nibabel as nib
>>> img1 = nib.load('img.nii.gz')
>>> img2 = nib.Nifti1Image.from_bytes(img.to_bytes())
>>> np.allclose(img1.dataobj, img2.dataobj)
True

Therefore, if you have a file pointer fp you should be able to just:

>>> img2 = nib.Nifti1Image.from_bytes(fp.read())

Would this functionality address your use case?

rmarkello avatar Jun 15 '21 19:06 rmarkello