Extract multiple 2D slices from a 3D volume.

Hi all.

I can’t solve the image extraction error (invalidRequestedRegionError) if I try to extract 2 different slices using the same ExtractImageFilter from a given volume.
In my program, I want to use a single ExtractImageFilter to dynamically extract individual slices from a 3D DICOM image that I load at the beginning.

The minimal reproducible example is as follows:

#include "itkImage.h"
#include "itkExtractImageFilter.h"

using PixelType = int;
using ImageType = itk::Image<PixelType, 3>;

int main()
{
    // Create empty 3D image
    ImageType::IndexType start;
    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    ImageType::SizeType size;
    size[0] = 512;
    size[1] = 512;
    size[2] = 512;

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

    // Allocate empty image
    auto image = ImageType::New();
    image->SetRegions(region);
    image->Allocate();
    image->Update();

    // Create slice extraction filter
    auto sliceExtractor = itk::ExtractImageFilter<ImageType, ImageType>::New();
    sliceExtractor->SetInput(image);

    // Extract single slice [z = 10].
    start[2] = 10;
    size[2] = 1; 
    ImageType::RegionType inputRegion = image->GetBufferedRegion();
    inputRegion.SetSize(size);
    inputRegion.SetIndex(start);
    sliceExtractor->SetExtractionRegion(inputRegion);
    sliceExtractor->Update();
    auto slice_0 = sliceExtractor->GetOutput();

    // Extract another slice [z = 50].
    start[2] = 50;
    inputRegion.SetSize(size);
    inputRegion.SetIndex(start);
    sliceExtractor->SetExtractionRegion(inputRegion);
    sliceExtractor->Update(); // Error happens here.
    auto slice_1 = sliceExtractor->GetOutput();

    return 0;
}

I’m compiling with VS2022 and using the ITK 5.0.0.

If you add UpdateLargestPossibleRegion before or instead of Update, the error goes away:

  sliceExtractor->UpdateLargestPossibleRegion(); // We need to update the largest region first
  sliceExtractor->Update(); // else error happens here.

The error happens because the new requested region and old largest region have the same size but different starting index (code), so there is no overlap.

I am not sure whether this is a limitation or a bug. @blowekamp might have more background.

1 Like

I thimk you can also do it with sitk with less code

Hope it helps

This is a limitation. This first time Update is called the DataObject’s requested region is automatically update to the largest possible region if not set or zero sized. The UpdateLargestPosslbeRegion method explicitly sets the requested region to the largest possible. I have previously proposed that ITK’s examples should use the UpdateLargestPossibleRegion over the prior as it is more explicit.

For the curious the relevant code is here:

1 Like