ITK对图像处理中,为了提高代码运行效率,通过迭代器Iterator可以实现对时间的优化。
在ITK的官方文档中也有明确的说明:

针对此说明,本次使用对图像获取最大值最小值的方式,来实验和测试其效率。
/*
*其中,imgSlice为输入的2d图像
*ImageType的定义为:using InputPixelType = short;
*using ImageType = itk::Image;
*返回的最大最小值为: w_ScalarMax, w_ScalarMin;
*/
//计算最大最小值ImageType::SizeType size = imgSlice->GetLargestPossibleRegion().GetSize();ImageType::PixelType pixelValue, w_ScalarMax, w_ScalarMin;for (int i = 0; i < size[0]; i++) {for (int j = 0; j < size[1]; j++) {ImageType::IndexType pixelIndex;pixelIndex[0] = i;pixelIndex[1] = j;pixelValue = imgSlice->GetPixel(pixelIndex);if (i == 0 && j == 0) {w_ScalarMax = w_ScalarMin = pixelValue;}else {if (pixelValue > w_ScalarMax) {w_ScalarMax = pixelValue;}if (pixelValue < w_ScalarMin) {w_ScalarMin = pixelValue;}}}}
以上代码是使用for循环进行求其。
/*
*其中,imgSlice为输入的2d图像
*ImageType的定义为:using InputPixelType = short;
*using ImageType = itk::Image;
*返回的最大最小值为: w_ScalarMax, w_ScalarMin;
*/ImageType::PixelType w_ScalarMax1, w_ScalarMin1;typedef itk::ImageRegionIterator< ImageType > IteratorTypeFilter;IteratorTypeFilter iteratorFilter(imgSlice.GetPointer(), imgSlice.GetPointer()->GetRequestedRegion());iteratorFilter.GoToBegin();while (!iteratorFilter.IsAtEnd()){if (iteratorFilter.Value() > w_ScalarMax1) {w_ScalarMax1 = iteratorFilter.Value();}if (iteratorFilter.Value() < w_ScalarMin1) {w_ScalarMin1 = iteratorFilter.Value();}++iteratorFilter;}
以上是使用迭代器的代码实现。
为了对比其效果,做了时间测试:
测试图像:512*512
测试次数:15次(由于单次时间在1ms附件,无法使用定时器直接对比,因此将以上代码循环15次来对比时间)
时间对比:

使用迭代器的方式,可以明显提高代码的时间效率。