How to get image mask in simpleitk?

I’m trying to set and get a mask on an image using simpleitk in Python. I’m setting the mask like this:

image: sitk.Image
mask: npt.NDArray
masked_image = sitk.Mask(image, sitk.GetImageFromArray(mask))

I can’t work out how to access the mask on masked_image once I’ve set it though. Can anyone help?

I am not sure what you mean by “set and get a mask on an image” perhaps an example of you expected behavior would clarify.

Perhaps this would help.

image = sitk.ReadImage("negative_positive.mha", sitk.sitkFloat32)

# create a mask image of 0, and 1 where the "image" is negative
mask = image<0

# assign 0 to all negative values in the input mask
image[mask] = 0

As an analogy from Python, numpy has masked arrays where the data is stored alongside a boolean array that is the same shape as the data and indicates whether a particular element of the array is masked or not.

I’m assuming that masks work in a similar way in (Simple)ITK, but perhaps they do not? If they do work in the same way, I’m looking for a way to get the mask (ie. array or Image of 0/1 values) I think I am setting on my image when calling sitk.Mask(image, mask).

Hello @dstansby,

Your assumption is incorrect. A mask image in ITK/SimpleITK is simply another independent image with integer values (in SimpleITK binary masks returned by filters are limited to {0,1} though in ITK they can be represented by any two integer values).

The MaskImageFilter and Mask operation apply a given mask to an image with the output being the original pixel value if the value in the mask is different from maskingValue, otherwise it is set to outsideValue. See code below:

import SimpleITK as sitk

image_size = [256,256]
image = sitk.GaussianSource(size=image_size, sigma=[10,20], mean=[128,128])

mask = sitk.Image(image_size, sitk.sitkUInt8) # initialized as all zeros
mask[100:140,100:140] = 1

# values in the mask different from maskingValue are copied over, all other values are set to outsideValue
masked_image = sitk.Mask(image, mask, maskingValue=0, outsideValue=20)

sitk.Show(image, "image")
sitk.Show(mask*255, "mask") # multiplying by 255 so that the mask is immediately visible, just convenience
sitk.Show(masked_image, "masked image")

Hopefully this clarified things.

3 Likes

Tha makes sense, thanks a lot for the explanation :slight_smile:

2 Likes