Compute Gradient Magnitude of Grayscale Image#

Synopsis#

This example demonstrates how to compute the magnitude of the gradient of an image.

Results#

Input image

Input image#

Output image

Output image#

Code#

C++#

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkGradientMagnitudeImageFilter.h"

int
main(int argc, char * argv[])
{
  // Verify command line arguments
  if (argc != 3)
  {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << " <InputImage> <OutputImage" << std::endl;
    return EXIT_FAILURE;
  }

  const char * inputFileName = argv[1];
  const char * outputFileName = argv[2];

  constexpr unsigned int Dimension = 2;

  using InputPixelType = unsigned char;
  using InputImageType = itk::Image<InputPixelType, Dimension>;

  using OutputPixelType = float;
  using OutputImageType = itk::Image<OutputPixelType, Dimension>;

  const auto input = itk::ReadImage<InputImageType>(inputFileName);

  // Create and setup a gradient filter
  using FilterType = itk::GradientMagnitudeImageFilter<InputImageType, OutputImageType>;

  auto gradientFilter = FilterType::New();
  gradientFilter->SetInput(input);

  try
  {
    itk::WriteImage(gradientFilter->GetOutput(), outputFileName);
  }
  catch (const itk::ExceptionObject & error)
  {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TInputImage, typename TOutputImage>
class GradientMagnitudeImageFilter : public itk::ImageToImageFilter<TInputImage, TOutputImage>

Computes the gradient magnitude of an image region at each pixel.

See

Image

See

Neighborhood

See

NeighborhoodOperator

See

NeighborhoodIterator

ITK Sphinx Examples:

See itk::GradientMagnitudeImageFilter for additional documentation.