Mathematical operation on "time" dimensions

Hi everyone, sorry for the very basic question but I am fairly new to the world of neuroimaging in python.
I am using nilearn to build a couple of custom functions for my personal use, and I cannot find out how one can perform mathematical operation on multiple images on the 4th dimension.
I will try to explain me better with an example.
I have a list of filename called list_of_files, I can open all the files in list_of_files using imgs = image.load_img(list_of_files). Now, I can binarize all the images at once with something like bin_imgs = image.math_img('img > 1', img = imgs) and then obtain the mean value in all voxels over all images with freq = image.mean_img(bin_imgs).
However, let’s say that I want to sum values at each voxels over all images and then divide it for some number, how could I do it ? If I try something on the line arbitrary_operation_over_time = image.math_img('sum(img)/10', img = imgs) and plot the resulting image, it is quite evident that this does not work. I could go for something like image.math_img("(img1 + img2 + img3)/10", img1 = one_image, img2 = another_image, img3 = a_third_image)but I am looking for a solution which will work for an arbitrary number of images.

Any tip is appreciated


I am afraid that this is a situation where nilearn.image.math_img is hitting its limitations. The simplest way is probably to extract the underlying data and work on it as a numpy array, then convert back to a niftiimage.

I would do something like:

from nilearn import image
imgs = image.concat_imgs(list_of_files)
data = imgs.get_data()
import numpy as np
summed_data = np.sum(data, axis=-1)
new_img = image.new_img_like(imgs, summed_data)

Hi Gael,
and than you for your answer.
Indeed I found out that it can be done within nilearn nilearn.image.math_img.
nilearn.image_math can take numpy function using np as alias, so the following works fine:
imgs = image.load_img(list_of_files)
arbitrary_operation_over_t = image.math_img("np.sum(img, -1)/" + str(10), img = imgs_bin)
Where when calling np.sum(img, -1) we’re asking to sum over the last dimension of the array.
Btw: I followed a workshop you directed couple of years ago at Karolinska Institutet and it was awesome.

1 Like

Indeed, that’s a better solution. I had forgotten that it worked.

I am glad that you liked the workshop. It seems that it payed its fruits: you end up using the software better than me, and I love it!