Cast Image to Another Type but Clamp to Output Range#

Synopsis#

Cast an image from one type to another but clamp to the output value range.

Results#

Code#

C++#

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkClampImageFilter.h"

using FloatImageType = itk::Image<float, 2>;
using UnsignedCharImageType = itk::Image<unsigned char, 2>;

static void
CreateImage(FloatImageType * const image);

int
main(int argc, char * argv[])
{
  FloatImageType::Pointer image;

  // No input image argument provided
  if (argc < 2)
  {
    image = FloatImageType::New();
    CreateImage(image);
  }
  else // Input image argument provided
  {
    image = itk::ReadImage<FloatImageType>(argv[1]);
  }

  using ClampFilterType = itk::ClampImageFilter<FloatImageType, UnsignedCharImageType>;
  auto clampFilter = ClampFilterType::New();
  clampFilter->SetInput(image);
  clampFilter->Update();

  return EXIT_SUCCESS;
}

void
CreateImage(FloatImageType * const image)
{
  // Create an image with 2 connected components
  FloatImageType::IndexType corner = { { 0, 0 } };

  FloatImageType::SizeType size;
  unsigned int             NumRows = 200;
  unsigned int             NumCols = 300;
  size[0] = NumRows;
  size[1] = NumCols;

  FloatImageType::RegionType region(corner, size);

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

  // Make a square
  for (unsigned int r = 40; r < 100; ++r)
  {
    for (unsigned int c = 40; c < 100; ++c)
    {
      FloatImageType::IndexType pixelIndex;
      pixelIndex[0] = r;
      pixelIndex[1] = c;

      image->SetPixel(pixelIndex, 15);
    }
  }
}

Classes demonstrated#

template<typename TInputImage, typename TOutputImage>
class ClampImageFilter : public itk::UnaryFunctorImageFilter<TInputImage, TOutputImage, Functor::Clamp<TInputImage::PixelType, TOutputImage::PixelType>>

Casts input pixels to output pixel type and clamps the output pixel values to a specified range.

Default range corresponds to the range supported by the pixel type of the output image.

This filter is templated over the input image type and the output image type.

Author

Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.

See

UnaryFunctorImageFilter

See

CastImageFilter

ITK Sphinx Examples:

See itk::ClampImageFilter for additional documentation.