Translate Image#

Synopsis#

Translate one itk::Image

Results#

Input image

Input image#

Output image

Output image#

Code#

C++#

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTranslationTransform.h"
#include "itkResampleImageFilter.h"

int
main(int argc, char * argv[])
{
  if (argc != 5)
  {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0];
    std::cerr << " <InputFileName> <OutputFileName> <translation X> <translation Y>";
    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>;

  const auto input = itk::ReadImage<ImageType>(inputFileName);

  using TransformType = itk::TranslationTransform<double, Dimension>;

  TransformType::OutputVectorType vector;
  vector[0] = std::stod(argv[3]);
  vector[1] = std::stod(argv[4]);

  auto translation = TransformType::New();
  translation->Translate(vector);

  using ResampleImageFilterType = itk::ResampleImageFilter<ImageType, ImageType>;
  auto resampleFilter = ResampleImageFilterType::New();
  resampleFilter->SetTransform(translation.GetPointer());
  resampleFilter->SetInput(input);
  resampleFilter->SetSize(input->GetLargestPossibleRegion().GetSize());

  try
  {
    itk::WriteImage(resampleFilter->GetOutput(), outputFileName);
  }
  catch (const itk::ExceptionObject & error)
  {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TParametersValueType = double, unsigned int NDimensions = 3>
class TranslationTransform : public itk::Transform<TParametersValueType, NDimensions, NDimensions>

Translation transformation of a vector space (e.g. space coordinates)

The same functionality could be obtained by using the Affine transform, but with a large difference in performance.

ITK Sphinx Examples:

See itk::TranslationTransform for additional documentation.