Inverse of Mask to Image#

Synopsis#

Apply the inverse of a mask to an image.

Results#

output.png

output.png#

Code#

C++#

#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkMaskNegatedImageFilter.h"

using ImageType = itk::Image<unsigned char, 2>;

static void
CreateHalfMask(ImageType::Pointer image, ImageType::Pointer mask);
static void
CreateImage(ImageType::Pointer image);

int
main()
{
  auto image = ImageType::New();
  CreateImage(image);

  auto mask = ImageType::New();
  CreateHalfMask(image, mask);

  using MaskNegatedImageFilterType = itk::MaskNegatedImageFilter<ImageType, ImageType>;
  auto maskNegatedImageFilter = MaskNegatedImageFilterType::New();
  maskNegatedImageFilter->SetInput(image);
  maskNegatedImageFilter->SetMaskImage(mask);
  maskNegatedImageFilter->Update();

  itk::WriteImage(maskNegatedImageFilter->GetOutput(), "output.png");

  return EXIT_SUCCESS;
}


void
CreateHalfMask(ImageType::Pointer image, ImageType::Pointer mask)
{
  ImageType::RegionType region = image->GetLargestPossibleRegion();

  mask->SetRegions(region);
  mask->Allocate();

  ImageType::SizeType regionSize = region.GetSize();

  itk::ImageRegionIterator<ImageType> imageIterator(mask, region);

  // Make the left half of the mask white and the right half black
  while (!imageIterator.IsAtEnd())
  {
    if (static_cast<unsigned int>(imageIterator.GetIndex()[0]) > regionSize[0] / 2)
    {
      imageIterator.Set(0);
    }
    else
    {
      imageIterator.Set(1);
    }

    ++imageIterator;
  }
}

void
CreateImage(ImageType::Pointer image)
{
  ImageType::IndexType start;
  start.Fill(0);

  ImageType::SizeType size;
  size.Fill(100);

  ImageType::RegionType region(start, size);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(122);
}

Classes demonstrated#

template<typename TInputImage, typename TMaskImage, typename TOutputImage = TInputImage>
class MaskNegatedImageFilter : public itk::BinaryGeneratorImageFilter<TInputImage, TMaskImage, TOutputImage>

Mask an image with the negation (or logical compliment) of a mask.

This class is templated over the types of the input image type, the mask image type and the type of the output image. Numeric conversions (castings) are done by the C++ defaults.

The pixel type of the input 2 image must have a valid definition of the operator!=. This condition is required because internally this filter will perform the operation

if pixel_from_mask_image != mask_value
     pixel_output_image = output_value
else
     pixel_output_image = pixel_input_image

The pixel from the input 1 is cast to the pixel type of the output image.

Note that the input and the mask images must be of the same size.

Warning

Only pixel value with mask_value ( defaults to 0 ) will be preserved.

See

MaskImageFilter

ITK Sphinx Examples:

See itk::MaskNegatedImageFilter for additional documentation.