Skip to content

Data Handling (Python)

mario.senden edited this page Mar 2, 2021 · 3 revisions

It is recommended to use NiBabel for reading and writing NIfTI files.

Loading Data

Data can be loaded using the NiBabel load function. Below is an example on how to load a NIFTI file called prf_data.nii and extract functional data. Note that the header and affine information is extracted from the NIFTI as these are important for saving results later on.

import nibabel as nib
import numpy as np

NIFTI = nib.load('prf_data.nii')
header = NIFTI.header
affine = NIFTI.affine
data = np.array(NIFTI.dataobj)
data = np.transpose(data, (3, 0, 1, 2))

Saving Results

Data can be saved using the NiBabel save function. Below is an example on how to save pRF mapping results to NIFTI files.

header["dim"][0] = 3
header["dim"][4] = 1

for key, value in results.items():
    results_nii = nib.Nifti1Image(value, affine, header)
    nib.save(results_nii, "%s.nii.gz" % key)