Preprocessing with nilearn for real time fMRI


we are preparing a real time fMRi and are exploring different possibilities for preprocessing. We are considering nilearn because it can do normalisation, detrending and smoothing on numpy arrays, however we would also need also the realignment of incoming fMRI volumes to a reference volume
We tried the nilearn image.resample_img function, thinking it could do the job, but it does not seem to work well for volumen realigment, at least when motion is present - as it was the case in our data; we could still see clear ‘jumps’ in the resampled images. The code is below. What I wanted to ask is whether there is any possibility to use the image.resample_img function for our purpose of realignment. I know there are other options in nipy, using fsl flirt or afni volreg but are either slow or mean that we have to transform the data into different formats (nii, npy) which also takes time and we want to be as quick as we can. Thanks for any input!



import os
import numpy as np
from nilearn import image
from glob import glob
from tqdm import tqdm
reference = ‘…/data/motion_samples_ds/ref/vol0210.nii.gz’
output_dir = ‘…/results/samples_ds_alignment’
input_dir = ‘…/data/motion_samples_ds’

get the single volume images

working_data = glob(os.path.join(input_dir,’*.nii.gz’))

load the reference volume

reference_img = image.load_img(reference)

align the single volume images to the reference volume

for img_file in tqdm(working_data):
nifti_img = image.load_img(img_file)
resampled_img = image.resample_img(nifti_img,
target_affine = reference_img.affine,
target_shape = reference_img.shape,)

resample_img resamples the image, meaning it changes the grid points where voxel values are measured – but still in the same referential, and it does not change the brain’s position in that space.
to do registration or motion correction you will need a different tool (such as the ones you mentioned), as nilearn intervenes later in the image processing pipeline, once these preprocessing steps have already been performed.