nibabel
nibabel copied to clipboard
Load from a file pointer instead of filepath string
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.
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?