I have received multiple Nifti-Images of a single fMRI session, where each volume scan has been saved into a single 3D-Nifti-file. These where named, say, 'foobar_001.nii', ..., 'foobar_187.nii'. I want to merge those and have written the following for-loop to do so.
import numpy as np
import nibabel as ni
def merge_nii_files (sfile, ns):
# This will load the first image for header information
img = ni.load(sfile % (3, ns))
dshape = list(img.shape)
data = np.empty(dshape, dtype=img.get_data_dtype())
header = img.header
equal_header_test = True
# Now load all the rest of the images
for n, i in enumerate(ns):
img = ni.load(sfile % (3,i))
equal_header_test = equal_header_test and img.header == header
data[...,n] = np.array(img.dataobj)
imgs = ni.Nifti1Image(data, img.affine, header=header)
if not equal_header_test:
print("WARNING: Not all headers were equal!")
nii_files = "example_%0*d.nii"
images = merge_nii_files(nii_files, range(1,187))
No, I did not miss anything. The above works.