Flip an Image Over Specified Axes#

Synopsis#

Flip an image over the specified axes. Pixels are swapped over the given axis.

Results#

Input image

Input image#

Output image

Output image#

Code#

Python#

#!/usr/bin/env python

import itk
import argparse

parser = argparse.ArgumentParser(description="Flip An Image Over Specified Axis.")
parser.add_argument("input_image")
parser.add_argument("output_image")
parser.add_argument("axis_to_flip", type=int)
args = parser.parse_args()

PixelType = itk.UC
Dimension = 2

ImageType = itk.Image[PixelType, Dimension]

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

flipFilter = itk.FlipImageFilter[ImageType].New()
flipFilter.SetInput(reader.GetOutput())

if args.axis_to_flip == 0:
    flipAxes = (True, False)
else:
    flipAxes = (False, True)

flipFilter.SetFlipAxes(flipAxes)

writer = itk.ImageFileWriter[ImageType].New()
writer.SetFileName(args.output_image)
writer.SetInput(flipFilter.GetOutput())

writer.Update()

C++#

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

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

  constexpr unsigned Dimension = 2;

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

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

  using FlipImageFilterType = itk::FlipImageFilter<ImageType>;

  auto flipFilter = FlipImageFilterType::New();
  flipFilter->SetInput(input);

  FlipImageFilterType::FlipAxesArrayType flipAxes;
  if (std::stoi(argv[3]) == 0)
  {
    flipAxes[0] = true;
    flipAxes[1] = false;
  }
  else
  {
    flipAxes[0] = false;
    flipAxes[1] = true;
  }

  flipFilter->SetFlipAxes(flipAxes);

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

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TImage>
class FlipImageFilter : public itk::ImageToImageFilter<TImage, TImage>

Flips an image across user specified axes.

FlipImageFilter flips an image across user specified axes. The flip axes are set via method SetFlipAxes( array ) where the input is a FixedArray<bool,ImageDimension>. The image is flipped across axes for which array[i] is true.

In terms of grid coordinates the image is flipped within the LargestPossibleRegion of the input image. As such, the LargestPossibleRegion of the output image is the same as the input.

In terms of geometric coordinates, the output origin is such that the image is flipped with respect to the coordinate axes.

ITK Sphinx Examples:

See itk::FlipImageFilter for additional documentation.