Apply A Filter Only To A Specified Region Of An Image

Synopsis

The key of using SetRequestedRegion to tell a filter to only operate on a specified ImageRegion is to call SetRequestedRegion on the filters GetOutput(). That is, to tell the DerivativeImageFilter to only operate on a small region, you must do

derivativeFilter->GetOutput()->SetRequestedRegion(smallRegion);
derivativeFilter->Update();

Results

Code

C++

#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkDerivativeImageFilter.h"

int
main(int, char *[])
{
  constexpr unsigned int Dimension = 2;
  using PixelType = float;

  using ImageType = itk::Image<PixelType, Dimension>;

  ImageType::SizeType smallSize;
  smallSize.Fill(10);

  ImageType::IndexType index;
  index.Fill(0);

  ImageType::RegionType region(index, smallSize);

  ImageType::SizeType bigSize;
  bigSize.Fill(10000);

  using RandomSourceType = itk::RandomImageSource<ImageType>;
  RandomSourceType::Pointer randomImageSource = RandomSourceType::New();
  randomImageSource->SetNumberOfWorkUnits(1); // to produce non-random results
  randomImageSource->SetSize(bigSize);
  randomImageSource->GetOutput()->SetRequestedRegion(smallSize);

  std::cout << "Created random image." << std::endl;

  using DerivativeImageFilterType = itk::DerivativeImageFilter<ImageType, ImageType>;

  DerivativeImageFilterType::Pointer derivativeFilter = DerivativeImageFilterType::New();
  derivativeFilter->SetInput(randomImageSource->GetOutput());
  derivativeFilter->SetDirection(0); // "x" axis
  derivativeFilter->GetOutput()->SetRequestedRegion(smallSize);
  derivativeFilter->Update();

  std::cout << "Computed derivative." << std::endl;

  return EXIT_SUCCESS;
}

Python

#!/usr/bin/env python

Dimension = 2
PixelType = itk.F
ImageType = itk.Image[PixelType, Dimension]

smallSize = itk.Size[Dimension]()
smallSize.Fill(10)

index = itk.Index[Dimension]()
index.Fill(0)

region = itk.ImageRegion[Dimension]()
region.SetIndex(index)
region.SetSize(smallSize)

bigSize = itk.Size[Dimension]()
bigSize.Fill(10)

RandomSourceType = itk.RandomImageSource[ImageType]
randomImageSource = RandomSourceType.New()
randomImageSource.SetNumberOfThreads(1)  # to produce non-random results
randomImageSource.SetSize(bigSize)
randomImageSource.GetOutput().SetRequestedRegion(region)

print("Created random image.")

DerivativeImageFilterType = itk.DerivativeImageFilter[ImageType, ImageType]

derivativeFilter = DerivativeImageFilterType.New()
derivativeFilter.SetInput(randomImageSource.GetOutput())
derivativeFilter.SetDirection(0)  # "x" axis
derivativeFilter.GetOutput().SetRequestedRegion(region)
derivativeFilter.Update()

print("Computed derivative.")

Classes demonstrated