# NeighborhoodIterators3.cxx¶

Example source code (NeighborhoodIterators3.cxx):

#include "otbImage.h"
#include "otbImageFileWriter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIterator.h"

// This example illustrates a technique for improving the efficiency of
// neighborhood calculations by eliminating unnecessary bounds checking. As
// described in Section~\ref{sec:NeighborhoodIterators}, the neighborhood
// iterator automatically enables or disables bounds checking based on the
// iteration region in which it is initialized. By splitting our image into
// boundary and non-boundary regions, and then processing each region using a
// different neighborhood iterator, the algorithm will only perform
// bounds-checking on those pixels for which it is actually required.  This
// trick can provide a significant speedup for simple algorithms such as our
// Sobel edge detection, where iteration speed is a critical.
//
// Splitting the image into the necessary regions is an easy task when you use
// the \doxygen{itk}{ImageBoundaryFacesCalculator}.  The face
// calculator is so named because it returns a list of the faces'' of the ND
// dataset.  Faces are those regions whose pixels all lie within a distance $d$
// from the boundary, where $d$ is the radius of the neighborhood stencil used
// for the numerical calculations. In other words, faces are those regions
// where a neighborhood iterator of radius $d$ will always overlap the boundary
// of the image. The face calculator also returns the single \emph{inner}
// region, in which out-of-bounds values are never required and bounds checking
// is not necessary.
//
// The face calculator object is defined in \code{itkNeighborhoodAlgorithm.h}.
// We include this file in addition to those from the previous two examples.

#include "itkSobelOperator.h"
#include "itkNeighborhoodInnerProduct.h"

#include "itkNeighborhoodAlgorithm.h"

int main(int argc, char* argv[])
{
if (argc < 4)
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv << " inputImageFile outputImageFile direction" << std::endl;
return -1;
}

using PixelType  = float;
using ImageType  = otb::Image<PixelType, 2>;

using NeighborhoodIteratorType = itk::ConstNeighborhoodIterator<ImageType>;
using IteratorType             = itk::ImageRegionIterator<ImageType>;

try
{
}
catch (itk::ExceptionObject& err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}

ImageType::Pointer output = ImageType::New();
output->Allocate();

itk::SobelOperator<PixelType, 2> sobelOperator;
sobelOperator.SetDirection(::atoi(argv));
sobelOperator.CreateDirectional();

itk::NeighborhoodInnerProduct<ImageType> innerProduct;

// First we load the input image and create the output image and inner product
// function as in the previous examples.  The image iterators will be created
// in a later step.  Next we create a face calculator object.  An empty list is
// created to hold the regions that will later on be returned by the face
// calculator.

using FaceCalculatorType = itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<ImageType>;

FaceCalculatorType               faceCalculator;
FaceCalculatorType::FaceListType faceList;

// The face calculator function is invoked by passing it an image pointer, an
// image region, and a neighborhood radius.  The image pointer is the same
// image used to initialize the neighborhood iterator, and the image region is
// the region that the algorithm is going to process.  The radius is the radius
// of the iterator.
//
// Notice that in this case the image region is given as the region of the
// \emph{output} image and the image pointer is given as that of the
// \emph{input} image.  This is important if the input and output images differ
// in size, i.e. the input image is larger than the output image.  ITK
// and OTB image
// filters, for example, operate on data from the input image but only generate
// results in the \code{RequestedRegion} of the output image, which may be
// smaller than the full extent of the input.

// The face calculator has returned a list of $2N+1$ regions. The first element
// in the list is always the inner region, which may or may not be important
// depending on the application.  For our purposes it does not matter because
// all regions are processed the same way.  We use an iterator to traverse the
// list of faces.

FaceCalculatorType::FaceListType::iterator fit;

// We now rewrite the main loop of the previous example so that each region in the
// list is processed by a separate iterator.  The iterators \code{it} and
// \code{out} are reinitialized over each region in turn.  Bounds checking is
// automatically enabled for those regions that require it, and disabled for
// the region that does not.

IteratorType             out;
NeighborhoodIteratorType it;

for (fit = faceList.begin(); fit != faceList.end(); ++fit)
{
out = IteratorType(output, *fit);

for (it.GoToBegin(), out.GoToBegin(); !it.IsAtEnd(); ++it, ++out)
{
out.Set(innerProduct(it, sobelOperator));
}
}

// The output is written as before.  Results for this example are the same as
// the previous example.  You may not notice the speedup except on larger
// images.  When moving to 3D and higher dimensions, the effects are greater
// because the volume to surface area ratio is usually larger.  In other
// words, as the number of interior pixels increases relative to the number of
// face pixels, there is a corresponding increase in efficiency from disabling
// bounds checking on interior pixels.

using WritePixelType = unsigned char;
using WriteImageType = otb::Image<WritePixelType, 2>;
using WriterType     = otb::ImageFileWriter<WriteImageType>;

using RescaleFilterType = itk::RescaleIntensityImageFilter<ImageType, WriteImageType>;

RescaleFilterType::Pointer rescaler = RescaleFilterType::New();

rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->SetInput(output);

WriterType::Pointer writer = WriterType::New();
writer->SetFileName(argv);
writer->SetInput(rescaler->GetOutput());
try
{
writer->Update();
}
catch (itk::ExceptionObject& err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}

return EXIT_SUCCESS;
}
{"ft_lang_label":"__label__en","ft_lang_prob":0.73277557,"math_prob":0.93998337,"size":6767,"snap":"2023-40-2023-50","text_gpt3_token_len":1589,"char_repetition_ratio":0.13840012,"word_repetition_ratio":0.03901895,"special_character_ratio":0.23378159,"punctuation_ratio":0.2005277,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96625096,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-10-04T00:49:59Z\",\"WARC-Record-ID\":\"<urn:uuid:af8e98c1-37a8-4c0c-9676-2fe8f58e624c>\",\"Content-Length\":\"39912\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7dc80c73-9eeb-4900-8429-073cf723eaa3>\",\"WARC-Concurrent-To\":\"<urn:uuid:3dada597-b5a2-454c-a2fd-973351a598ff>\",\"WARC-IP-Address\":\"54.36.18.189\",\"WARC-Target-URI\":\"https://www.orfeo-toolbox.org/CookBook/C++/Examples/Iterators/NeighborhoodIterators3.html\",\"WARC-Payload-Digest\":\"sha1:XIN2GOUZAYEZ34ANSJSSU5GJVTFLNXVX\",\"WARC-Block-Digest\":\"sha1:X3ZBB4RZZWAJB3VGM7U2MPHMTDMOZMYA\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233511284.37_warc_CC-MAIN-20231003224357-20231004014357-00318.warc.gz\"}"}