ANIMA  4.0
animaKMeansClustering.cxx
Go to the documentation of this file.
1 #include <tclap/CmdLine.h>
2 
3 #include <itkScalarImageKmeansImageFilter.h>
5 #include <itkImageRegionIterator.h>
6 
7 int main(int argc, char **argv)
8 {
9  TCLAP::CmdLine cmd("INRIA / IRISA - VisAGeS/Empenn Team", ' ',ANIMA_VERSION);
10 
11  TCLAP::ValueArg<std::string> inArg("i","inputfile","Input image",true,"","input image",cmd);
12  TCLAP::ValueArg<std::string> outArg("o","outputfile","output image",true,"","output image",cmd);
13  TCLAP::ValueArg<unsigned int> numClassArg("c","numclass","Number of classes",false,4,"number of classes",cmd);
14  TCLAP::ValueArg<int> keptClassArg("k","class","Class to keep",false,-1,"class to be kept",cmd);
15  TCLAP::ValueArg<unsigned int> nbpArg("n","ncores","Number of cores (default: all cores)",false,itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads(),"number of cores",cmd);
16 
17  try
18  {
19  cmd.parse(argc,argv);
20  }
21  catch (TCLAP::ArgException& e)
22  {
23  std::cerr << "Error: " << e.error() << "for argument " << e.argId() << std::endl;
24  return EXIT_FAILURE;
25  }
26 
27  std::string refName, resName;
28  refName = inArg.getValue();
29  resName = outArg.getValue();
30 
31  typedef itk::Image <double,3> doubleImageType;
32  typedef itk::ScalarImageKmeansImageFilter <doubleImageType> MainFilterType;
33 
34  MainFilterType::Pointer kmeansFilter = MainFilterType::New();
35  kmeansFilter->SetInput(anima::readImage <doubleImageType> (refName));
36  kmeansFilter->SetUseNonContiguousLabels(false);
37 
38  for (unsigned int i = 0;i < numClassArg.getValue();++i)
39  kmeansFilter->AddClassWithInitialMean(i * 100);
40 
41  kmeansFilter->SetNumberOfWorkUnits(nbpArg.getValue());
42  kmeansFilter->Update();
43 
44  MainFilterType::ParametersType estimatedMeans = kmeansFilter->GetFinalMeans();
45  typedef MainFilterType::OutputImageType OutputImageType;
46 
47  if (keptClassArg.getValue() >= 0)
48  {
49  const unsigned int numberOfClasses = estimatedMeans.Size();
50  unsigned int numLabel = 0;
51 
52  for(unsigned int i = 0 ; i < numberOfClasses ; ++i)
53  {
54  unsigned int numInf = 0;
55 
56  for (unsigned int j = 0;j < numberOfClasses;++j)
57  {
58  if (estimatedMeans[j] < estimatedMeans[i])
59  ++numInf;
60  }
61 
62  if (numInf == keptClassArg.getValue())
63  {
64  numLabel = i;
65  break;
66  }
67  }
68 
69  typedef itk::ImageRegionIterator <OutputImageType> IteratorType;
70  IteratorType outIterator(kmeansFilter->GetOutput(),kmeansFilter->GetOutput()->GetLargestPossibleRegion());
71 
72  while(!outIterator.IsAtEnd())
73  {
74  outIterator.Set((outIterator.Get() == numLabel));
75  ++outIterator;
76  }
77  }
78 
79  anima::writeImage <OutputImageType> (resName,kmeansFilter->GetOutput());
80 
81  return EXIT_SUCCESS;
82 }
int main(int argc, char **argv)