#include <iomanip>
#include <cstdio>
int
main(int argc, char * argv[])
{
if (argc < 5)
{
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImageFile outputImageFileBase ";
std::cerr << " outputImageFileExtension numberOfThresholdsToCalculate "
<< std::endl;
return EXIT_FAILURE;
}
using InputPixelType = unsigned short;
using OutputPixelType = unsigned char;
using ScalarImageToHistogramGeneratorType =
using HistogramType = ScalarImageToHistogramGeneratorType::HistogramType;
using FilterType =
scalarImageToHistogramGenerator =
scalarImageToHistogramGenerator->SetNumberOfBins(128);
calculator->SetNumberOfThresholds(std::stoi(argv[4]));
calculator->SetReturnBinMidpoint(true);
constexpr OutputPixelType outsideValue = 0;
constexpr OutputPixelType insideValue = 255;
filter->SetOutsideValue(outsideValue);
filter->SetInsideValue(insideValue);
reader->SetFileName(argv[1]);
scalarImageToHistogramGenerator->SetInput(reader->GetOutput());
calculator->SetInputHistogram(scalarImageToHistogramGenerator->GetOutput());
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
try
{
reader->Update();
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception thrown while reading image" << excp << std::endl;
}
scalarImageToHistogramGenerator->Compute();
try
{
calculator->Compute();
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception thrown " << excp << std::endl;
}
const CalculatorType::OutputType & thresholdVector =
calculator->GetOutput();
std::string outputFileBase = argv[2];
InputPixelType upperThreshold;
for (auto itNum = thresholdVector.begin(); itNum != thresholdVector.end();
++itNum)
{
std::cout
<< "OtsuThreshold[" << static_cast<int>(itNum - thresholdVector.begin())
<< "] = "
<< static_cast<
*itNum)
<< std::endl;
upperThreshold = static_cast<InputPixelType>(*itNum);
filter->SetLowerThreshold(lowerThreshold);
filter->SetUpperThreshold(upperThreshold);
lowerThreshold = upperThreshold;
std::ostringstream outputFilename;
outputFilename << outputFileBase << std::setfill('0') << std::setw(3)
<< (itNum - thresholdVector.begin()) << "." << argv[3];
writer->SetFileName(outputFilename.str());
try
{
writer->Update();
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception thrown " << excp << std::endl;
}
}
filter->SetLowerThreshold(lowerThreshold);
filter->SetUpperThreshold(upperThreshold);
std::ostringstream outputFilename2;
outputFilename2 << outputFileBase << std::setfill('0') << std::setw(3)
<< thresholdVector.size() << "." << argv[3];
writer->SetFileName(outputFilename2.str());
try
{
writer->Update();
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << "Exception thrown " << excp << std::endl;
}
return EXIT_SUCCESS;
}