Pad an Image With a Constant#

Synopsis#

Pad an itk::Image with a given constant

Results#

Input image

Input image#

Output image

Output image#

Code#

C++#

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkConstantPadImageFilter.h"

int
main(int argc, char * argv[])
{
  if (argc != 6)
  {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0];
    std::cerr << "<InputFileName> <OutputFileName> <LowerExtendSize> ";
    std::cerr << "<UpperExtendSize> <ConstantValue>";
    std::cerr << std::endl;
    return EXIT_FAILURE;
  }

  constexpr unsigned int Dimension = 2;

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

  const auto input = itk::ReadImage<ImageType>(argv[1]);

  ImageType::SizeType lowerExtendRegion;
  lowerExtendRegion.Fill(std::stoi(argv[3]));

  ImageType::SizeType upperExtendRegion;
  upperExtendRegion.Fill(std::stoi(argv[4]));

  using FilterType = itk::ConstantPadImageFilter<ImageType, ImageType>;
  auto filter = FilterType::New();
  filter->SetInput(input);
  filter->SetPadLowerBound(lowerExtendRegion);
  filter->SetPadUpperBound(upperExtendRegion);
  filter->SetConstant(std::stoi(argv[5]));

  try
  {
    itk::WriteImage(filter->GetOutput(), argv[2]);
  }
  catch (const itk::ExceptionObject & error)
  {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}