[Neuroimaging] Combining binary mask to 3D volume

Christopher Markiewicz markiewicz at stanford.edu
Mon Feb 13 20:52:46 EST 2023

Hi Jacob,

If I'm understanding the problem correctly, you mean you have a 3D image (maybe T1-weighted or similar) and a 3D binary mask, and what you would like is the original image values where the mask is 1 and 0s where the mask is 0.

Assuming that's correct, I might take this approach:

import nibabel as nib
import numpy as np

img = nib.load(img_fname)
mask_img = nib.load(mask_fname)

data = img.get_fdata()
mask = np.asanyarray(mask_img.dataobj) != 0

# Remove data outside the mask
data[~mask] = 0

masked_img = img.__class__(data, img.affine, img.header)

I suspect nilearn has tools that would do this as well. And if your mask is aligned to your original image but not have the same shape and affine, you will need to resample your mask first before you can use the data arrays in this way.


From: Neuroimaging <neuroimaging-bounces+markiewicz=stanford.edu at python.org> on behalf of Jacob Bunyamin via Neuroimaging <neuroimaging at python.org>
Sent: Monday, February 13, 2023 19:50
To: neuroimaging at python.org
Cc: Jacob Bunyamin
Subject: [Neuroimaging] Combining binary mask to 3D volume

Good afternoon,

I am trying to overlay a binary mask to 3D volume and combine them into a single file. Is there any way to do this?

Thank you,

Kind regards,


Jacob Bunyamin
PhD Student

Department of Neuroscience
Central Clinical School, Monash University
99 Commercial Road
Melbourne VIC 3004
E: jacob.bunyamin at monash.edu<mailto:jacob.bunyamin at monash.edu>

More information about the Neuroimaging mailing list