Convert labels to mask image

I have a labels.nii.gz image with labels 1-4. How can I convert this image into a mask image containing 1s (where labels occur) and 0s with nilearn?

If you just want to binarize the image, then nilearn.image.math_img is a good function to use:

from nilearn import image

img_bin = image.math_img("img > 0", img="labels.nii.gz")
img_bin.to_filename("mask.nii.gz")
1 Like