[Insight-users] Finding the closest pixel with a specific criteria

David Doria daviddoria at gmail.com
Wed Aug 31 16:00:39 EDT 2011


I would like to find the closest pixel to a query pixel that passes
some kind of test. For example, I would like to find the closest pixel
to (10,10) that is non-zero. Is there an easy way to do this? I wrote
a function that uses a NeighborhoodIterator with a successively larger
radius until a suitable pixel is found. However, this is horribly
slow.

Any suggestions?

Thanks,

David

Here is my method if anyone is interested. (I am aware that as the
radius increases the interior pixels are re-searched. In my case the
radius never gets above 3-ish, so it is not really a problem. I
suppose a ShapedNeighborhoodIterator should be used that is just the
outside border of the square rather than the solid square of the
NeighborhoodIterator).


bool FindClosestNonZeroPixel(MaskImageType::Pointer image,
itk::Index<2> queryPixel, unsigned int radiusValue, itk::Index<2>&
returnPixel)
{
  itk::Index<2> zeroIndex;
  zeroIndex.Fill(0);

  ImageType::SizeType radius;
  radius.Fill(radiusValue);

  itk::ConstNeighborhoodIterator<MaskImageType> iterator(radius,
image, image->GetLargestPossibleRegion());

  while(!iterator.IsAtEnd())
    {
    for(unsigned int i = 0; i < radiusValue*radiusValue; i++)
      {
      ImageType::IndexType index = iterator.GetIndex(i);

      bool inBounds;
      ImageType::PixelType pixel = iterator.GetPixel(i, inBounds);
      if(pixel != 0)
	{
	returnPixel = iterator.GetIndex();
	return true;
	}

      }
    ++iterator;
    }

  return false;
}

itk::Index<2> FindClosestNonZeroPixel(MaskImageType::Pointer image,
itk::Index<2> queryPixel)
{
  // Look in successively bigger neighborhoods
  for(unsigned int radiusValue = 1; radiusValue <
std::max(image->GetLargestPossibleRegion().GetSize()[0],
image->GetLargestPossibleRegion().GetSize()[1]); ++radiusValue)
    {
    std::cout << "Radius: " << radiusValue << std::endl;
    itk::Index<2> closestPixel;
    bool success = FindClosestNonZeroPixel(image, queryPixel,
radiusValue, closestPixel);
    if(success)
      {
      return closestPixel;
      }
    }
  std::cerr << "No non-zero pixel was found!" << std::endl;

  itk::Index<2> zeroIndex;
  zeroIndex.Fill(0);
  return zeroIndex;
}


More information about the Insight-users mailing list