pythonniftinibabelmatlab-spm

Using nibabel to save nifti in "SPM" style


I have used python to analyse some fMRI data and would now like to save my results as niftis that I can then use in an SPM analysis.

My data scores is an array of float64 of shape (97, 115, 97). I have used the following code to save it:

import nibabel as nib   
import nilearn 

scores_image = nib.Nifti1Image(scores,affine = np.eye(4))
nib.save(scores_image,"scores.nii")

However, when I load the data into SPM I notice that both the origin and the scale are different from what SPM is expecting: Comparison of my scores.nii (upper image) and a standard SPM nifti

Does anyone know which code would automatically save my scores variable with the same origin and size as SPM is expecting?

Update: Here is the header of an SPM image with highlight where it differs from my own image:

comp_img = nib.load('spmT_0014.nii')

print(comp_img.header)
<class 'nibabel.nifti1.Nifti1Header'> object, endian='<'
sizeof_hdr      : 348
data_type       : b''
db_name         : b''
extents         : 0
session_error   : 0
regular         : b'r'                          ## ---> b''
dim_info        : 0
dim             : [  3  97 115  97   1   1   1   1]
intent_p1       : 0.0
intent_p2       : 0.0
intent_p3       : 0.0
intent_code     : none
datatype        : float32
bitpix          : 32
slice_start     : 0
pixdim          : [1. 2. 2. 2. 0. 0. 0. 0.]     ## ---> [1. 1. 1. 1. 1. 1. 1. 1.]
vox_offset      : 0.0
scl_slope       : nan
scl_inter       : nan
slice_end       : 0
slice_code      : unknown
xyzt_units      : 10                            ## ---> 0
cal_max         : 0.0
cal_min         : 0.0
slice_duration  : 0.0
toffset         : 0.0
glmax           : 0
glmin           : 0
descrip         : b''
aux_file        : b''
qform_code      : aligned                       ## ---> unknown
sform_code      : aligned
quatern_b       : 0.0
quatern_c       : 0.0
quatern_d       : 0.0
qoffset_x       : -96.5                         ## ---> 0
qoffset_y       : -132.5                        ## ---> 0
qoffset_z       : -78.5                         ## ---> 0
srow_x          : [  2.    0.    0.  -96.5]     ## ---> [1. 0. 0. 0.]
srow_y          : [   0.     2.     0.  -132.5] ## ---> [0. 1. 0. 0.]
srow_z          : [  0.    0.    2.  -78.5]     ## ---> [0. 0. 1. 0.]
intent_name     : b''
magic           : b'n+1'

Solution

  • I have found a way to do this by using the following code:

    from nilearn import image
    import nibabel as nib
    
    comp_img = nib.load('spmT_0014.nii')
    scores_img = image.new_img_like(comp_img, scores, copy_header=False)
    

    Which gives me the following (upper image is the SPM one and lower image is the one I created):

    Comparison in SPM