Add Constant to Every Pixel#

Synopsis#

Add a constant to every pixel in an image.

Results#

Yinyang.png

Yinyang.png#

output.png

output.png#

Code#

C++#

#include "itkImage.h"
#include "itkAddImageFilter.h"
#include "itkImageFileWriter.h"

using ImageType = itk::Image<unsigned char, 2>;
static void
CreateImage(ImageType::Pointer image);

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

  using AddImageFilterType = itk::AddImageFilter<ImageType, ImageType, ImageType>;
  auto addImageFilter = AddImageFilterType::New();
  addImageFilter->SetInput(image);
  addImageFilter->SetConstant2(2);
  addImageFilter->Update();

  itk::WriteImage(addImageFilter->GetOutput(), "output.png");

  return EXIT_SUCCESS;
}

void
CreateImage(ImageType::Pointer image)
{
  ImageType::IndexType start;
  start.Fill(0);

  ImageType::SizeType size;
  size.Fill(100);

  ImageType::RegionType region;
  region.SetSize(size);
  region.SetIndex(start);

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

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

  while (!imageIterator.IsAtEnd())
  {
    if (imageIterator.GetIndex()[0] < 70)
    {
      imageIterator.Set(255);
    }
    else
    {
      imageIterator.Set(0);
    }

    ++imageIterator;
  }
}

Classes demonstrated#

template<typename TInputImage1, typename TInputImage2 = TInputImage1, typename TOutputImage = TInputImage1>
class AddImageFilter : public itk::BinaryGeneratorImageFilter<TInputImage1, TInputImage2, TOutputImage>

Pixel-wise addition of two images.

This class is templated over the types of the two input images and the type of the output image. Numeric conversions (castings) are done by the C++ defaults.

The pixel type of the input 1 image must have a valid definition of the operator+ with a pixel type of the image 2. This condition is required because internally this filter will perform the operation

pixel_from_image_1 + pixel_from_image_2

Additionally the type resulting from the sum, will be cast to the pixel type of the output image.

The total operation over one pixel will be

output_pixel = static_cast<OutputPixelType>( input1_pixel + input2_pixel )

For example, this filter could be used directly for adding images whose pixels are vectors of the same dimension, and to store the resulting vector in an output image of vector pixels.

The images to be added are set using the methods:

SetInput1( image1 );
SetInput2( image2 );

Additionally, this filter can be used to add a constant to every pixel of an image by using

SetInput1( image1 );
SetConstant2( constant );

Warning

No numeric overflow checking is performed in this filter.

ITK Sphinx Examples:

See itk::AddImageFilter for additional documentation.