Extract Region of Interest in One Image#

Synopsis#

Extract a given Region Of Interest (ROI) in a given image

Results#

Input image

Input image#

Output image

Output image#

Code#

C++#

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRegionOfInterestImageFilter.h"

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

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

  const auto startx = static_cast<itk::IndexValueType>(std::stoi(argv[3]));
  const auto endx = static_cast<itk::IndexValueType>(std::stoi(argv[4]));

  const auto starty = static_cast<itk::IndexValueType>(std::stoi(argv[5]));
  const auto endy = static_cast<itk::IndexValueType>(std::stoi(argv[6]));

  constexpr unsigned int Dimension = 2;

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

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

  ImageType::IndexType start;
  start[0] = startx;
  start[1] = starty;

  ImageType::IndexType end;
  end[0] = endx;
  end[1] = endy;

  ImageType::RegionType region;
  region.SetIndex(start);
  region.SetUpperIndex(end);

  using FilterType = itk::RegionOfInterestImageFilter<ImageType, ImageType>;
  auto filter = FilterType::New();
  filter->SetInput(input);
  filter->SetRegionOfInterest(region);

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

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TInputImage, typename TOutputImage>
class RegionOfInterestImageFilter : public itk::ImageToImageFilter<TInputImage, TOutputImage>

Extract a region of interest from the input image.

This filter produces an output image of the same dimension as the input image. The user specifies the region of the input image that will be contained in the output image. The origin coordinates of the output images will be computed in such a way that if mapped to physical space, the output image will overlay the input image with perfect registration. In other words, a registration process between the output image and the input image will return an identity transform.

If you are interested in changing the dimension of the image, you may want to consider the ExtractImageFilter. For example for extracting a 2D image from a slice of a 3D image.

The region to extract is set using the method SetRegionOfInterest.

See

ExtractImageFilter

ITK Sphinx Examples:

See itk::RegionOfInterestImageFilter for additional documentation.