int main( int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0];
std::cerr << " inputScalarImage outputLabeledImage nonContiguousLabels";
std::cerr << " numberOfClasses mean1 mean2... meanN " << std::endl;
return EXIT_FAILURE;
}
const char * inputImageFileName = argv[1];
using PixelType = signed short;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputImageFileName );
KMeansFilterType::Pointer kmeansFilter = KMeansFilterType::New();
kmeansFilter->SetInput( reader->GetOutput() );
const unsigned int numberOfInitialClasses = std::stoi( argv[4] );
const unsigned int useNonContiguousLabels = std::stoi( argv[3] );
kmeansFilter->SetUseNonContiguousLabels( useNonContiguousLabels );
constexpr unsigned int argoffset = 5;
if( static_cast<unsigned int>(argc) <
numberOfInitialClasses + argoffset )
{
std::cerr << "Error: " << std::endl;
std::cerr << numberOfInitialClasses << " classes has been specified ";
std::cerr << "but no enough means have been provided in the command ";
std::cerr << "line arguments " << std::endl;
return EXIT_FAILURE;
}
for( unsigned k=0; k < numberOfInitialClasses; k++ )
{
const double userProvidedInitialMean = std::stod( argv[k+argoffset] );
kmeansFilter->AddClassWithInitialMean( userProvidedInitialMean );
}
const char * outputImageFileName = argv[2];
using OutputImageType = KMeansFilterType::OutputImageType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( kmeansFilter->GetOutput() );
writer->SetFileName( outputImageFileName );
try
{
writer->Update();
}
{
std::cerr << "Problem encountered while writing ";
std::cerr << " image file : " << argv[2] << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
KMeansFilterType::ParametersType estimatedMeans =
kmeansFilter->GetFinalMeans();
const unsigned int numberOfClasses = estimatedMeans.Size();
for ( unsigned int i = 0; i < numberOfClasses; ++i )
{
std::cout << "cluster[" << i << "] ";
std::cout << " estimated mean : " << estimatedMeans[i] << std::endl;
}
return EXIT_SUCCESS;
}