Subtracting an image and its flipped version (about affines and math computations on images)


I am trying to compute the difference between an image and its left-right flipped version.

In SPM, if I first use ‘reorient’ then ‘imcalc’ to compute the difference, everything works as expected.

Now, I would like to perform the same operations using the Python ecosystem (nibabel, nipy, nilearn…)

I tried to use nilearn.image.math_img, but it refuses to perform a computation with images having different affines (which sort of makes sense). Yet, because in SPM, the left-right flipping is achieved by changing the sign of the XX component of the affine so I cannot use the Python script on flipped images generated by SPM.

I tried to flip the data, using nilearn.image.swap_img_hemispheres, which presumably uses numpy flip to flip the data array. But the result is not satisfactory (the axis of symmetry is a bit shifted from the center when I visualize the image).

Any suggestions?

It would be cool if nilearn’s math_img could perform arithmetic operations between images “in the world space” and take care ‘automagically’ of resampling.

I think that nilearn.image.resample_to_img should enable you to do what you want easily in combination of math_img.

If it works for you, consider doing a pull request to improve the docstring of math_img by adding a note on this (in a “notes” section).

1 Like


To subtract two images, i1 and i2, with different affines:

from nilearn.image import resample_to_img, math_img

math_img("img1 - img2", img1=i1, img2=resample_to_img(i2, i1))

Thank you very much Gael!