evaluateCompleteBoWPipeline.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /**
  2. * @file evaluateCompleteBoWPipeline.cpp
  3. * @brief A complete BoW pipeline: feature extraction, codebook creation, vector quantization, classifier training, evaluation on separate test set
  4. * @author Alexander Freytag
  5. * @date 10-05-2013
  6. */
  7. //STL
  8. #include <iostream>
  9. #include <limits>
  10. //core -- basic stuff
  11. #include <core/basics/Config.h>
  12. #include <core/basics/ResourceStatistics.h>
  13. #include <core/basics/Timer.h>
  14. #include <core/image/Convert.h>
  15. #include <core/vector/VectorT.h>
  16. //vislearning -- basic stuff
  17. #include <vislearning/baselib/Globals.h>
  18. #include <vislearning/baselib/ICETools.h>
  19. #include <vislearning/cbaselib/MultiDataset.h>
  20. #include <vislearning/cbaselib/Example.h>
  21. #include <vislearning/cbaselib/ClassificationResult.h>
  22. #include <vislearning/cbaselib/ClassificationResults.h>
  23. //
  24. // vislearning -- classifier
  25. #include <vislearning/classifier/classifierbase/VecClassifier.h>
  26. #include <vislearning/classifier/genericClassifierSelection.h>
  27. //
  28. // vislearning -- BoW codebooks
  29. #include "vislearning/features/simplefeatures/CodebookPrototypes.h"
  30. #include "vislearning/features/simplefeatures/BoWFeatureConverter.h"
  31. //
  32. // vislearning -- local features
  33. #include <vislearning/features/localfeatures/GenericLFSelection.h>
  34. //
  35. // vislearning -- clustering methods
  36. #include <vislearning/math/cluster/GenericClusterAlgorithmSelection.h>
  37. //
  38. using namespace std;
  39. using namespace NICE;
  40. using namespace OBJREC;
  41. /**
  42. a complete BoW pipeline
  43. possibly, we can make use of objrec/progs/testClassifier.cpp
  44. */
  45. int main( int argc, char **argv )
  46. {
  47. std::set_terminate( __gnu_cxx::__verbose_terminate_handler );
  48. Config * conf = new Config ( argc, argv );
  49. const bool writeClassificationResults = conf->gB( "main", "writeClassificationResults", true );
  50. const std::string resultsfile = conf->gS( "main", "resultsfile", "/tmp/results.txt" );
  51. ResourceStatistics rs;
  52. // ========================================================================
  53. // TRAINING STEP
  54. // ========================================================================
  55. MultiDataset md( conf );
  56. const LabeledSet *trainFiles = md["train"];
  57. //**********************************************
  58. //
  59. // FEATURE EXTRACTION FOR TRAINING IMAGES
  60. //
  61. //**********************************************
  62. std::cerr << "FEATURE EXTRACTION FOR TRAINING IMAGES" << std::endl;
  63. OBJREC::LocalFeatureRepresentation * featureExtractor = OBJREC::GenericLFSelection::selectLocalFeatureRep ( conf, "features", OBJREC::GenericLFSelection::TRAINING );
  64. //collect features in a single data structure
  65. NICE::VVector featuresFromAllTrainingImages;
  66. featuresFromAllTrainingImages.clear();
  67. //determine how many training images we actually use to easily allocate the correct amount of memory afterwards
  68. int numberOfTrainingImages ( 0 );
  69. for(LabeledSet::const_iterator classIt = trainFiles->begin() ; classIt != trainFiles->end() ; classIt++)
  70. {
  71. numberOfTrainingImages += classIt->second.size();
  72. std::cerr << "number of examples for this class: " << classIt->second.size() << std::endl;
  73. }
  74. //okay, this is redundant - but I see no way to do it more easy right now...
  75. std::vector<NICE::VVector> featuresOfImages ( numberOfTrainingImages );
  76. //this again is somehow redundant, but we need the labels lateron for easy access - change this to a better solution :)
  77. NICE::VectorT<int> labelsTrain ( numberOfTrainingImages, 0 );
  78. //TODO replace the nasty makro by a suitable for-loop to make it omp-ready (parallelization)
  79. int imgCnt ( 0 );
  80. // the corresponding nasty makro: LOOP_ALL_S( *trainFiles )
  81. for(LabeledSet::const_iterator classIt = trainFiles->begin() ; classIt != trainFiles->end() ; classIt++)
  82. {
  83. for ( std::vector<ImageInfo *>::const_iterator imgIt = classIt->second.begin();
  84. imgIt != classIt->second.end();
  85. imgIt++, imgCnt++
  86. )
  87. {
  88. // the corresponding nasty makro: EACH_INFO( classno, info );
  89. int classno ( classIt->first );
  90. const ImageInfo imgInfo = *(*imgIt);
  91. std::string filename = imgInfo.img();
  92. NICE::ColorImage img( filename );
  93. //compute features
  94. //variables to store feature information
  95. NICE::VVector features;
  96. NICE::VVector positions;
  97. Globals::setCurrentImgFN ( filename );
  98. featureExtractor->extractFeatures ( img, features, positions );
  99. //normalization :)
  100. for ( NICE::VVector::iterator i = features.begin();
  101. i != features.end();
  102. i++)
  103. {
  104. i->normalizeL1();
  105. }
  106. //collect them all in a larger data structure
  107. featuresFromAllTrainingImages.append( features );
  108. //and store it as well in the data struct that additionally keeps the information which features belong to which image
  109. //TODO this can be made more clever!
  110. // featuresOfImages.push_back( features );
  111. featuresOfImages[imgCnt] = features;
  112. labelsTrain[imgCnt] = classno;
  113. }
  114. }
  115. //**********************************************
  116. //
  117. // CODEBOOK CREATION
  118. //
  119. //**********************************************
  120. std::cerr << "CODEBOOK CREATION" << std::endl;
  121. OBJREC::ClusterAlgorithm * clusterAlgo = OBJREC::GenericClusterAlgorithmSelection::selectClusterAlgo ( conf );
  122. NICE::VVector prototypes;
  123. std::vector<double> weights;
  124. std::vector<int> assignments;
  125. std::cerr << "call cluster of cluster algo " << std::endl;
  126. clusterAlgo->cluster( featuresFromAllTrainingImages, prototypes, weights, assignments );
  127. std::cerr << "create new codebook with the computed prototypes" << std::endl;
  128. OBJREC::CodebookPrototypes * codebook = new OBJREC::CodebookPrototypes ( prototypes );
  129. //**********************************************
  130. //
  131. // VECTOR QUANTIZATION OF
  132. // FEATURES OF TRAINING IMAGES
  133. //
  134. //**********************************************
  135. OBJREC::BoWFeatureConverter * bowConverter = new OBJREC::BoWFeatureConverter ( conf, codebook );
  136. OBJREC::LabeledSetVector trainSet;
  137. NICE::VVector histograms ( featuresOfImages.size() /* number of vectors*/, 0 /* dimension of vectors*/ ); //the internal vectors will be resized within calcHistogram
  138. NICE::VVector::iterator histogramIt = histograms.begin();
  139. NICE::VectorT<int>::const_iterator labelsIt = labelsTrain.begin();
  140. for (std::vector<NICE::VVector>::const_iterator imgIt = featuresOfImages.begin(); imgIt != featuresOfImages.end(); imgIt++, histogramIt++, labelsIt++)
  141. {
  142. bowConverter->calcHistogram ( *imgIt, *histogramIt );
  143. bowConverter->normalizeHistogram ( *histogramIt );
  144. //NOTE perhaps we should use add_reference here
  145. trainSet.add( *labelsIt, *histogramIt );
  146. }
  147. //**********************************************
  148. //
  149. // CLASSIFIER TRAINING
  150. //
  151. //**********************************************
  152. std::string classifierType = conf->gS( "main", "classifierType", "GPHIK" );
  153. OBJREC::VecClassifier * classifier = OBJREC::GenericClassifierSelection::selectVecClassifier( conf, classifierType );
  154. //TODO integrate GP-HIK-NICE into vislearning and add it into genericClassifierSelection
  155. //this method adds the training data to the temporary knowledge of our classifier
  156. classifier->teach( trainSet );
  157. //now the actual training step starts (e.g., parameter estimation, ... )
  158. classifier->finishTeaching();
  159. // ========================================================================
  160. // TEST STEP
  161. // ========================================================================
  162. const LabeledSet *testFiles = md["test"];
  163. delete featureExtractor;
  164. featureExtractor = OBJREC::GenericLFSelection::selectLocalFeatureRep ( conf, "features", OBJREC::GenericLFSelection::TESTING );
  165. NICE::Matrix confusionMat ( trainFiles->size() /* number of classes in training */, testFiles->size() /* number of classes for testing*/, 0.0 );
  166. NICE::Timer t;
  167. ClassificationResults results;
  168. LOOP_ALL_S( *testFiles )
  169. {
  170. EACH_INFO( classno, info );
  171. std::string filename = info.img();
  172. //**********************************************
  173. //
  174. // FEATURE EXTRACTION FOR TEST IMAGES
  175. //
  176. //**********************************************
  177. NICE::ColorImage img( filename );
  178. //compute features
  179. //variables to store feature information
  180. NICE::VVector features;
  181. NICE::VVector positions;
  182. Globals::setCurrentImgFN ( filename );
  183. featureExtractor->extractFeatures ( img, features, positions );
  184. //normalization :)
  185. for ( NICE::VVector::iterator i = features.begin();
  186. i != features.end();
  187. i++)
  188. {
  189. i->normalizeL1();
  190. }
  191. //**********************************************
  192. //
  193. // VECTOR QUANTIZATION OF
  194. // FEATURES OF TEST IMAGES
  195. //
  196. //**********************************************
  197. NICE::Vector histogramOfCurrentImg;
  198. bowConverter->calcHistogram ( features, histogramOfCurrentImg );
  199. bowConverter->normalizeHistogram ( histogramOfCurrentImg );
  200. //**********************************************
  201. //
  202. // CLASSIFIER EVALUATION
  203. //
  204. //**********************************************
  205. uint classno_groundtruth = classno;
  206. t.start();
  207. ClassificationResult r = classifier->classify ( histogramOfCurrentImg );
  208. t.stop();
  209. uint classno_estimated = r.classno;
  210. r.classno_groundtruth = classno_groundtruth;
  211. //if we like to store the classification results for external post processing, uncomment this
  212. if ( writeClassificationResults )
  213. {
  214. results.push_back( r );
  215. }
  216. confusionMat( classno_estimated, classno_groundtruth ) += 1;
  217. }
  218. confusionMat.normalizeColumnsL1();
  219. std::cerr << confusionMat << std::endl;
  220. std::cerr << "average recognition rate: " << confusionMat.trace()/confusionMat.rows() << std::endl;
  221. if ( writeClassificationResults )
  222. {
  223. double avgRecogResults ( results.getAverageRecognitionRate () );
  224. std::cerr << "average recognition rate according to classificationResults: " << avgRecogResults << std::endl;
  225. results.writeWEKA ( resultsfile, 0 );
  226. }
  227. return 0;
  228. }