How to visualize a '.npy' fMRI data file by nilearn?

Hey, thank you for reading about my problem. I am trying to visualize my fMRI data after the masking process. (which has been processed in ‘numpy’ format), and I want to visualize the result by Nilearn. But I find that Nilearn can only read or process ‘nii.gz’ format files. I have not found any related guild in the guide book. So anyone who can help me with this question?

Thank you so much.

Hi @DavisMeee and welcome to neurostars!

Presumably, you saved the data as a .npy right? What kind of object was saved to this .npy file? You should be able to get the file back in it’s original form after loading it with numpy.load(/path/to/file.npy).


Hey @Steven thank you for your answering!

I loaded it with the ‘np.load’ function and then tried to use ‘nilearn.plotting.plot_stat_map’ and ‘nilearn.plotting.view_img_on_surf’ to visualize my data. But none of them worked. The feedback told me that I have got a ‘TypeError: Data given cannot be loaded because it is not compatible with nibabel format.’

So I thought that the numpy file might not be compatible with nibabel or nilearn. And here’s my real problem. :slight_smile:


How were the data saved to .npy? Can you share an example file?

The pseudo-code probably like this:

x = nibabel.load('xxx.nii.gz').get_fdata
output = x[1,:,:,:]    # for one-time data

Having read the nii.gz file with ‘nb.load’ function, I use ‘’ for a masked data slice (which is [1,x,y,z]).

Hi @DavisMeee,

A few issues here:

Usually time is represented on the last axis, so it (X,Y,Z,T).

If you want to save a file as a nilearn-compatible image, you should turn your data into an image with something like

my_img=nilearn.image.new_img_like(ref_niimg, data),

where ref_niimg could be your original unsliced image and data is the array you want to make an image out of, and then save it out with my_img.to_filename('/path/to/out.nii.gz').


1 Like

Hey @Steven :

Oh, this might be the reason. I will try this now.
Thank you so much!


If you’re just looking for to save a single volume, you can use:

img = nb.load("xxx.nii.gz")
vol0 = img.slicer[:, :, :, 0]
1 Like