pythonarraysnumpyvoxelnifti

convert numpy array to 4D nifti file


I am doing single-voxel simulations on python to generate simulated signals with added noise. Then, I want to convert the resulting numpy array, with the following shape (100, 100) into a nifti file.

Rows represent one simulated signal under different conditions of noise and tensor rotation. Each column represents the correspondent signal intensity for that voxel under those conditions when measured with a specific sampling scheme (100 different directions).

[DWIs array]

1

I am to save this matrix into a nifti file with the following format (10, 10, 1, 100).

[Desired shape]

2

I don’t know how to properly allocate the numpy array (DWIs.shape = (100,100)) to the format I desire (10, 10, 1, 100):

data[…, ] = ?
 
converted_array = np.array(data, dtype=np.float32)
nifti_file = nib.Nifti1Image(converted_array, affine=np.eye(4))
nib.save(nifti_file, os.path.join(path_to_save, 'snr{}'.format(snr), 'full/dwi_sims_snr{}.nii.gz'.format(snr)))

Solution

  • In NumPy you do not need to "allocate" data arrays.

    Suppose you have a 100x100 converted_array. That is

    >>> converted_array.shape
    (100,100)
    >>> converted_array[0]
    [146.4, 72.9, ..., 174.9]
    

    then you can reshape this array as

    >>> nifti_array = converted_array.reshape((10,10,1,100))
    >>> nifti_array[0][0][0]
    [146.4, 72.9, ..., 174.9]