从本文开始,将开启ITK之旅!
ITK 是一个开源的跨平台库,为开发人员提供了一套广泛的图像分析软件工具。 ITK 通过极限编程方法开发,建立在经过验证的面向空间的架构上,用于处理、分割和配准二维、三维或更多维的科学图像。
1.函数说明
template<typename TImage> class ImageRandomNonRepeatingIteratorWithIndex : public itk::ImageRandomNonRepeatingConstIteratorWithIndex<TImage>
一个多维图像迭代器,以随机顺序访问区域内的图像像素,不重复。它在很大程度上基于 ImageRandomIterator
类。此迭代器是 itk::ImageRandomNonRepeatingConstIteratorWithIndex
的子类,它添加了写访问功能。
2.代码展示
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "itkImageFileWriter.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
// PNG对应
#include <itkPNGImageIOFactory.h>
int main(int argc, char * argv[])
{
if (argc < 3)
{
std::cerr << "Usage: " << argv[0] << " inputFile outputFile [percent]" << std::endl;
return EXIT_FAILURE;
}
double percent = .1;
if (argc > 3)
{
percent = std::stod(argv[3]); // 如果遇到非法输入,stoi会自动截取最前面的数字,
// 直到遇到不是数字为止所以说如果是浮点数,会截取前面的整数部分
// 如果是非法输入,stod会截取最前面的浮点数,知道遇到不满足浮点数为止
if (percent >= 1.0)
{
percent /= 100.0;
}
}
using ImageType = itk::Image<unsigned char, 2>; //2维uchar类型
using ReaderType = itk::ImageFileReader<ImageType>;
using IteratorType = itk::ImageRandomNonRepeatingIteratorWithIndex<ImageType>;
using WriterType = itk::ImageFileWriter<ImageType>;
// Read the binary file
itk::ObjectFactoryBase::RegisterFactory(itk::PNGImageIOFactory::New());
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
reader->Update();
// At x% of the pixels, add a uniform random value between 0 and 255
IteratorType it(reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion());
it.SetNumberOfSamples(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() * percent);
std::cout << "Number of random samples: " << it.GetNumberOfSamples() << std::endl;
using GeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator;
GeneratorType::Pointer random = GeneratorType::New();
it.GoToBegin();
while (!it.IsAtEnd())
{
it.Set(random->GetUniformVariate(0, 255)); //设置[0,255]像素值
++it;
}
// Write the file
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(argv[2]);
writer->SetInput(reader->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
// Number of random samples: 17510
3.结果展示
参考目录
https://itk.org/ITKExamples/src/Core/Common/AddNoiseToBinaryImage/Documentation.html