#include <iomanip>
#include <stdio.h>
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;
}
typedef unsigned short InputPixelType;
typedef unsigned char OutputPixelType;
InputImageType > ScalarImageToHistogramGeneratorType;
typedef ScalarImageToHistogramGeneratorType::HistogramType HistogramType;
CalculatorType;
InputImageType, OutputImageType > FilterType;
ScalarImageToHistogramGeneratorType::Pointer scalarImageToHistogramGenerator
= ScalarImageToHistogramGeneratorType::New();
CalculatorType::Pointer calculator = CalculatorType::New();
FilterType::Pointer filter = FilterType::New();
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
scalarImageToHistogramGenerator->SetNumberOfBins( 128 );
calculator->SetNumberOfThresholds( atoi( argv[4] ) );
const OutputPixelType outsideValue = 0;
const 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();
}
{
std::cerr << "Exception thrown while reading image" << excp << std::endl;
}
scalarImageToHistogramGenerator->Compute();
try
{
calculator->Compute();
}
{
std::cerr << "Exception thrown " << excp << std::endl;
}
const CalculatorType::OutputType &thresholdVector = calculator->GetOutput();
CalculatorType::OutputType::const_iterator itNum = thresholdVector.begin();
std::string outputFileBase = argv[2];
InputPixelType lowerThreshold = 0;
InputPixelType upperThreshold;
for(; itNum < thresholdVector.end(); itNum++)
{
std::cout << "OtsuThreshold["
<< (int)(itNum - thresholdVector.begin())
<< "] = "
CalculatorType::MeasurementType>::PrintType>(*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();
}
{
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();
}
{
std::cerr << "Exception thrown " << excp << std::endl;
}
return EXIT_SUCCESS;
}