Thomas Möbius Thomas Möbius - 2 months ago 18
Python Question

Copy header when merging multiple MRI images using nibabel

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[0]))
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))

As you can see, I would like to make sure that the header information are copied, too. My question: Is this 'header=header' really enough? I am asking because imgs has a 4-tuple shape, but the header I am using comes from a 3-tuple shape. I am not too familiar with the internals of nibabel or the Nifti file format. Did I miss anything, i.e., do I need to copy anything else?


No, I did not miss anything. The above works.