How do I apply a mask / overlay using a nifti segmentation?

I have the two files for every brain - Brain.nii.gz and Mask.nii.gz.

The first file is the full MRI, and the second is just a mask of segmentation of a tumor. I want to overlay the segmentation on the brain and highlight / intensify that area to be able to more clearly see the tumor and export this file / save this.

I have been exploring various options but cannot find how to do it. I have explored nilearn, FSL, NiftiMasker, and more but cannot figure it out.

I am using Python and Colab by the way.

Hi, you may find some of the overlay options in Nilearn to be helpful. See here: Nilearn: Statistical Analysis for NeuroImaging in Python — Machine learning for NeuroImaging


Hi Steven,
Many thanks for the prompt response. The page is really useful but do you know if there is a way I can then export the plots created as its own nifti file?

I am a bit confused, could you describe what you want in this output nifti file? Are you saying that you want to export just the part of Brain.nii.gz that is contained in Mask.nii.gz?

No - you were right in your first response, I want an output file where the mask areas in brain file are intensified / highlighted / contoured etc.

The link you sent is what I want but this just give you a plot and doesn’t allow you to export it / perhaps I don’t know how I can export it.

Keep in mind that a NIFTI file is essentially a 3D (or 4D if time is an axis) matrix with header information. You won’t be able to export a fancy art effect to numerical form.

I just want to increase the intensity / brightness of the pixels where the mask is present. Is there no way I can do that?

In that case, as long as the two images have the same resolution and are in the same space, then you can load the image in nilearn, get the indexes of the mask data, and then index your brain data with the mask data and add some arbitrary value to those points to make them more intense.

mask=nilearn.image.load_img(path_to_mask) will load the image, then I think you can do mask_data = mask.get_fdata() to get the data matrix. Assuming your mask is just binary, you can then find the indexes that of the mask by saying mask_indexes=(mask_data==1). Load your brain data the same way you did the mask, and then add your modifier to your brain data at the mask_indexes.

Thanks Steven, thats exactly the sort of thing I was looking for.

Sorry but can I ask a final question - how do I add the modifier at the indexes?

There is probably a more efficient way to do this, but one way is to loop over coordinates of the mask indexes, and do brain_data[i,j,k]=brain_data[i,j,k] + mod, where i,j,k is a single coordinate of the mask.