Iterate Line Through Image Without Write Access#

Synopsis#

Iterate over a line through an image without write access.

Results#

Output:

255
255
255

Code#

C++#

#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkLineConstIterator.h"

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

static void
CreateImage(ImageType::Pointer image);

int
main()
{
  auto image = ImageType::New();
  CreateImage(image);

  ImageType::RegionType region = image->GetLargestPossibleRegion();
  ImageType::IndexType  corner1 = region.GetIndex();
  ImageType::IndexType  corner2;
  corner2[0] = corner1[0] + region.GetSize()[0] - 1;
  corner2[1] = corner1[1] + region.GetSize()[1] - 1;

  itk::LineConstIterator<ImageType> it(image, corner1, corner2);
  it.GoToBegin();
  while (!it.IsAtEnd())
  {
    std::cout << (int)it.Get() << std::endl;
    ++it;
  }

  return EXIT_SUCCESS;
}

void
CreateImage(ImageType::Pointer image)
{
  ImageType::SizeType regionSize;
  regionSize.Fill(3);

  ImageType::IndexType regionIndex;
  regionIndex.Fill(0);

  ImageType::RegionType region;
  region.SetSize(regionSize);
  region.SetIndex(regionIndex);

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

  itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion());

  while (!imageIterator.IsAtEnd())
  {
    imageIterator.Set(255);
    ++imageIterator;
  }
}

Classes demonstrated#

template<typename TImage>
class LineConstIterator

An iterator that walks a Bresenham line through an ND image with read-only access to pixels.

LineConstIterator is an iterator that walks a Bresenham line through an image. The iterator is constructed similar to other image iterators, except instead of specifying a region to traverse, you specify two indices. The interval specified by the two indices is closed. So, a line iterator specified with the same start and end index will visit exactly one pixel.

LineConstIterator<ImageType> it(image, I1, I2);
while (!it.IsAtEnd())
{
   // visits at least 1 pixel
}

Author

Benjamin King, Experimentelle Radiologie, Medizinische Hochschule Hannover.

ITK Sphinx Examples:

Subclassed by itk::LineIterator< TImage >

See itk::LineConstIterator for additional documentation.