can't iterate over simple image

I have a 3d boolean image and would like to compute the number of non zero voxels.

I wrote this simple code that is supposed to iterate over the whole image and update a counter variable.

using BoolImageType = itk::Image<bool, 3U>;
double computeVolumeFromBinaryImage(const BoolImageType::Pointer& a_Image)
{
	itk::ImageConstIterator<BoolImageType> it(a_Image, a_Image->GetRequestedRegion());
	it.GoToBegin();
	std::size_t numVoxels = 0;
	while (!it.IsAtEnd())
	{
		if (it.Get())
			numVoxels++;
		++it;
	}
	auto size = a_Image->GetSpacing();
	double voxelVolume = size[0] * size[1] * size[2];
	return voxelVolume * numVoxels;
}

But I get the following compiler error:
error C2675: unary '++' : 'itk::ImageConstIterator<BoolImageType>' does not define this operator or a conversion to a type acceptable to the predefined operator
This error points to ++it;

I get the same error if I remove the custom typedef.
I’m using visual studio if that helps.

Any idea ?

OK so after reading the documentation more in details I found out that itk::ImageConstIterator does not provide any means of moving the iterator. Same goes for itk::ImageIterator.

I was confused by the first documentation page that pops in google when searching for itk image iterator.
https://itk.org/Doxygen/html/ImageIteratorsPage.html
The code samples there, even though they do not represent full programs somehow indicates the use of ImageIterator with the ++ operator.

replacing itk::ImageConstIterator with ImageRegionConstIterator solved my issue.

this piece of code works for me:

using BoolImageType = itk::Image<bool, 3U>;
double computeVolumeFromBinaryImage(const BoolImageType::Pointer& a_Image)
{
	itk::ImageRegionConstIterator<BoolImageType> it(a_Image, a_Image->GetLargestPossibleRegion());
	std::size_t numVoxels = 0;
	for (it = it.Begin(); !it.IsAtEnd(); ++it)
	{
		if (it.Get())
			numVoxels++;
	}
	auto size = a_Image->GetSpacing();
	double voxelVolume = size[0] * size[1] * size[2];
	return voxelVolume * numVoxels;
}
3 Likes

Thanks for following up your post with the solution!

The only thing worse than an orphan open question is when the author comes back and say “nevermind, fixed it” and gives no details.

I'm doing my part

2 Likes