Iterate Region In Image With Access To Current Index With Write Access

Synopsis

Iterate over a region of an image with efficient access to the current index (with write access).

Results

../../../../_images/Yinyang3.png

Yinyang.png

../../../../_images/IterateRegionWithAccessToIndexWithWriteAccess.png

Yinyang.png In VTK Window With Index Access

Output:

Indices:
Index: [0, 0] value: ?
Index: [1, 0] value: ?
Index: [2, 0] value: ?
Index: [3, 0] value: ?
Index: [4, 0] value: ?
Index: [0, 1] value: ?
Index: [1, 1] value: ?
Index: [2, 1] value: ?
Index: [3, 1] value: ?
Index: [4, 1] value: ?
Index: [0, 2] value: ?
Index: [1, 2] value: ?
Index: [2, 2] value: ?
Index: [3, 2] value: ?
Index: [4, 2] value: ?
Index: [0, 3] value: ?
Index: [1, 3] value: ?
Index: [2, 3] value: ?
Index: [3, 3] value: ?
Index: [4, 3] value: ?

Code

C++

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIteratorWithIndex.h"

#ifdef ENABLE_QUICKVIEW
#  include "QuickView.h"
#endif

int
main(int argc, char * argv[])
{
  if (argc < 2)
  {
    std::cerr << "Required: filename" << std::endl;
    return EXIT_FAILURE;
  }

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

  using ReaderType = itk::ImageFileReader<ImageType>;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(argv[1]);
  reader->Update();

  ImageType::Pointer image = reader->GetOutput();

  ImageType::SizeType regionSize;
  regionSize[0] = 5;
  regionSize[1] = 4;

  ImageType::IndexType regionIndex;
  regionIndex[0] = 0;
  regionIndex[1] = 0;

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

  itk::ImageRegionIteratorWithIndex<ImageType> imageIterator(image, region);

  while (!imageIterator.IsAtEnd())
  {
    std::cout << "Index: " << imageIterator.GetIndex() << " value: " << imageIterator.Get() << std::endl;

    // Set the current pixel to white
    imageIterator.Set(255);

    ++imageIterator;
  }

#ifdef ENABLE_QUICKVIEW
  // Visualize
  QuickView viewer;
  viewer.AddImage<ImageType>(image);
  viewer.Visualize();
#endif

  return EXIT_SUCCESS;
}

Classes demonstrated