Subtract Constant From Every Pixel#
Synopsis#
Subtract a constant from every pixel in an image.
Results#
Code#
C++#
#include "itkImage.h"
#include "itkSubtractImageFilter.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 SubtractImageFilterType = itk::SubtractImageFilter<ImageType, ImageType, ImageType>;
auto subtractConstantFromImageFilter = SubtractImageFilterType::New();
subtractConstantFromImageFilter->SetInput(image);
subtractConstantFromImageFilter->SetConstant2(2);
subtractConstantFromImageFilter->Update();
itk::WriteImage(subtractConstantFromImageFilter->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 SubtractImageFilter : public itk::BinaryGeneratorImageFilter<TInputImage1, TInputImage2, TOutputImage> Pixel-wise subtraction of two images.
Subtract each pixel from image2 from its corresponding pixel in image1:
Output = Input1 - Input2.
This is done using
SetInput1( image1 ); SetInput2( image2 );
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.
Additionally, a constant can be subtracted from every pixel in an image using:
SetInput1( image1 ); SetConstant2( constant );
- Note
The result of AddImageFilter with a negative constant is not necessarily the same as SubtractImageFilter. This would be the case when the PixelType defines an operator-() that is not the inverse of operator+()
- ITK Sphinx Examples: