Corina Holom
Corina Holom

Reputation: 13

How to convert binary file to Nifti?

We are sending data from a webpage to a python server with Json and we are trying to make predictions on the medical images. The images are supposed to be saved in .bin format. Would it be possible to convert the binary files into .nii?

Upvotes: 1

Views: 369

Answers (1)

Liviu Iacob
Liviu Iacob

Reputation: 11

Assuming you receive the data in json form, here is an example. In my case, the byte array is sent encoded using base64, but you can omit that part if u send them raw.

SAVING_NIFTI_PATH = r'./medical_file.nii.gz'
data = json.loads(json_response)
base64NiftiBytes = data['NiftiFile'].encode('utf-8')
nifti_bytes = base64.b64decode(base64NiftiBytes)

# save bytes as .nii.gz
with open(SAVING_NIFTI_PATH, 'wb') as f:
    f.write(nifti_bytes)

# load the nifti object
nifti_file = nib.load(SAVING_NIFTI_PATH)

If this is not your use case, there is another method, found here: https://mail.python.org/pipermail/neuroimaging/2017-February/001346.html

# for files that are not gzipped
from io import BytesIO
from nibabel import FileHolder, Nifti1Image
fh = FileHolder(fileobj=BytesIO(input_stream))
img = Nifti1Image.from_filemap({'header': fh, 'image': fh})

# for gzipped files
from gzip import GzipFile
fh = FileHolder(fileobj=GzipFile(fileobj=BytesIO(input_stream)))

Upvotes: 0

Related Questions