Cifti manipulation with nibabel

Hi,
An nibabel question, sorry if doesn’t belong here -

I’ve a cii dtseries file and I’d like to pull only a few brain structures of interest out of it and produce a smaller file with only those brain structures while keeping the format. There is probably an easy way to do that.

Any ideas,
Thanks!

Hi @urielias,

I think this post here might answer your question? :slight_smile:

Best wishes,

Logan

Hi,

I saw this - not quite. It explains how to extract the timeseries data, which I’ve found pretty straightforward. However, unless I’ve missed dearly, it doesn’t explain how to set the header correctly so that data can be saved in a new file - which is what I’m not sure how to do.

If it’s not clear from the question I’ll edit…
And still thanks for the answer

Unfortunately, nothing with CIFTI is easy, but this shouldn’t be too difficult with the CIFTI Axes API.

The rough approach you’ll want is:

# This is a complete representation of the header
axes = [cifti.header.get_axis(i) for i in range(cifti.ndim)]
# You'll want the brain model axis
time_axis, brain_model_axis = axes

# Select the structures you want
structure_names = [...]  # List of structure names
# Iter_structures takes concatenated structures, and returns one at a time
brain_models = [bm for bm in brain_model_axis.iter_structures()
                if bm[0] in structure_names]
# bm = (structure_name, slice object, BrainModelAxis)

# Slice your data object with each model, concatenate time series
new_dataobj = numpy.concatenate(
    [cifti.dataobj[:, bm[1]] for bm in brain_models], axis=1)

# BrainModelAxes can be added together to form a composite axis
new_brain_model_axis = sum(
    (bm[2] for bm in brain_models[1:]), brain_models[0][2])
# And we're done
new_cifti = Cifti2Image(new_dataobj,
                        header=(time_axis, new_brain_model_axis),
                        nifti_header=cifti.nifti_header)

I haven’t tested this, but it shouldn’t be terribly far off.

Thanks! Worked nicely…