Threshold An Image

Synopsis

Threshold an image using itk::ThresholdImageFilter

Results

Input image

Input image

Output image

Output image

Code

C++

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkThresholdImageFilter.h"

int
main(int argc, char * argv[])
{
  if (argc != 5)
  {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0];
    std::cerr << " <InputFileName> <OutputFileName> <Lower Threshold> <Upper Threshold>";
    std::cerr << std::endl;
    return EXIT_FAILURE;
  }

  const char * inputFileName = argv[1];
  const char * outputFileName = argv[2];

  constexpr unsigned int Dimension = 2;

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

  using ReaderType = itk::ImageFileReader<ImageType>;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(inputFileName);

  unsigned char lowerThreshold = std::stoi(argv[3]);
  unsigned char upperThreshold = std::stoi(argv[4]);

  using FilterType = itk::ThresholdImageFilter<ImageType>;
  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(reader->GetOutput());
  filter->ThresholdOutside(lowerThreshold, upperThreshold);
  filter->SetOutsideValue(0);

  using WriterType = itk::ImageFileWriter<ImageType>;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outputFileName);
  writer->SetInput(filter->GetOutput());
  try
  {
    writer->Update();
  }
  catch (itk::ExceptionObject & error)
  {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Python

#!/usr/bin/env python
import itk

if len(sys.argv) != 5:
    print("Usage: " + sys.argv[0] + " <inputImage> <outputImage> "
          "<lowerThreshold> <upperThreshold>")
    sys.exit(1)

inputImage = sys.argv[1]
outputImage = sys.argv[2]
lowerThreshold = int(sys.argv[3])
upperThreshold = int(sys.argv[4])

PixelType = itk.UC
Dimension = 2

ImageType = itk.Image[PixelType, Dimension]

reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(inputImage)

thresholdFilter = itk.ThresholdImageFilter[ImageType].New()

thresholdFilter.SetInput(reader.GetOutput())
thresholdFilter.ThresholdOutside(lowerThreshold, upperThreshold)
thresholdFilter.SetOutsideValue(0)

writer = itk.ImageFileWriter[ImageType].New()
writer.SetFileName(outputImage)
writer.SetInput(thresholdFilter.GetOutput())

writer.Update()

Classes demonstrated