evaluateCompleteBoWPipeline.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/baselib/ProgressBar.h>
  20. #include <vislearning/cbaselib/MultiDataset.h>
  21. #include <vislearning/cbaselib/Example.h>
  22. #include <vislearning/cbaselib/ClassificationResult.h>
  23. #include <vislearning/cbaselib/ClassificationResults.h>
  24. //
  25. // vislearning -- classifier
  26. #include <vislearning/classifier/classifierbase/VecClassifier.h>
  27. #include <vislearning/classifier/genericClassifierSelection.h>
  28. //
  29. // vislearning -- BoW codebooks
  30. #include "vislearning/features/simplefeatures/CodebookPrototypes.h"
  31. #include "vislearning/features/simplefeatures/BoWFeatureConverter.h"
  32. //
  33. // vislearning -- local features
  34. #include <vislearning/features/localfeatures/GenericLFSelection.h>
  35. //
  36. // vislearning -- clustering methods
  37. #include <vislearning/math/cluster/GenericClusterAlgorithmSelection.h>
  38. //
  39. using namespace std;
  40. using namespace NICE;
  41. using namespace OBJREC;
  42. /**
  43. a complete BoW pipeline
  44. possibly, we can make use of objrec/progs/testClassifier.cpp
  45. */
  46. int main( int argc, char **argv )
  47. {
  48. std::set_terminate( __gnu_cxx::__verbose_terminate_handler );
  49. Config * conf = new Config ( argc, argv );
  50. const bool writeClassificationResults = conf->gB( "main", "writeClassificationResults", true );
  51. const std::string resultsfile = conf->gS( "main", "resultsfile", "/tmp/results.txt" );
  52. ResourceStatistics rs;
  53. // ========================================================================
  54. // TRAINING STEP
  55. // ========================================================================
  56. MultiDataset md( conf );
  57. const LabeledSet *trainFiles = md["train"];
  58. //**********************************************
  59. //
  60. // FEATURE EXTRACTION FOR TRAINING IMAGES
  61. //
  62. //**********************************************
  63. std::cerr << "FEATURE EXTRACTION FOR TRAINING IMAGES" << std::endl;
  64. OBJREC::LocalFeatureRepresentation * featureExtractor = OBJREC::GenericLFSelection::selectLocalFeatureRep ( conf, "features", OBJREC::GenericLFSelection::TRAINING );
  65. //collect features in a single data structure
  66. NICE::VVector featuresFromAllTrainingImages;
  67. featuresFromAllTrainingImages.clear();
  68. //determine how many training images we actually use to easily allocate the correct amount of memory afterwards
  69. int numberOfTrainingImages ( 0 );
  70. for(LabeledSet::const_iterator classIt = trainFiles->begin() ; classIt != trainFiles->end() ; classIt++)
  71. {
  72. numberOfTrainingImages += classIt->second.size();
  73. std::cerr << "number of examples for this class: " << classIt->second.size() << std::endl;
  74. }
  75. //okay, this is redundant - but I see no way to do it more easy right now...
  76. std::vector<NICE::VVector> featuresOfImages ( numberOfTrainingImages );
  77. //this again is somehow redundant, but we need the labels lateron for easy access - change this to a better solution :)
  78. NICE::VectorT<int> labelsTrain ( numberOfTrainingImages, 0 );
  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. //this method adds the training data to the temporary knowledge of our classifier
  155. classifier->teach( trainSet );
  156. //now the actual training step starts (e.g., parameter estimation, ... )
  157. classifier->finishTeaching();
  158. // ========================================================================
  159. // TEST STEP
  160. // ========================================================================
  161. const LabeledSet *testFiles = md["test"];
  162. delete featureExtractor;
  163. featureExtractor = OBJREC::GenericLFSelection::selectLocalFeatureRep ( conf, "features", OBJREC::GenericLFSelection::TESTING );
  164. NICE::Matrix confusionMat ( testFiles->size() /* number of classes for testing*/, trainFiles->size() /* number of classes in training */, 0.0 );
  165. NICE::Timer t;
  166. ClassificationResults results;
  167. ProgressBar pbClasses;
  168. // the corresponding nasty makro: LOOP_ALL_S( *testFiles )
  169. for(LabeledSet::const_iterator classIt = testFiles->begin() ; classIt != testFiles->end() ; classIt++)
  170. {
  171. std::cerr <<" \n\nOverall update bar: " << std::endl;
  172. pbClasses.update ( testFiles->size() );
  173. std::cerr << "\nStart next class " << std::endl;
  174. ProgressBar pbClassExamples;
  175. for ( std::vector<ImageInfo *>::const_iterator imgIt = classIt->second.begin();
  176. imgIt != classIt->second.end();
  177. imgIt++, imgCnt++
  178. )
  179. {
  180. pbClassExamples.update ( classIt->second.size() );
  181. // the corresponding nasty makro: EACH_INFO( classno, info );
  182. int classno ( classIt->first );
  183. const ImageInfo imgInfo = *(*imgIt);
  184. std::string filename = imgInfo.img();
  185. //**********************************************
  186. //
  187. // FEATURE EXTRACTION FOR TEST IMAGES
  188. //
  189. //**********************************************
  190. NICE::ColorImage img( filename );
  191. //compute features
  192. //variables to store feature information
  193. NICE::VVector features;
  194. NICE::VVector positions;
  195. Globals::setCurrentImgFN ( filename );
  196. featureExtractor->extractFeatures ( img, features, positions );
  197. //normalization :)
  198. for ( NICE::VVector::iterator i = features.begin();
  199. i != features.end();
  200. i++)
  201. {
  202. i->normalizeL1();
  203. }
  204. //**********************************************
  205. //
  206. // VECTOR QUANTIZATION OF
  207. // FEATURES OF TEST IMAGES
  208. //
  209. //**********************************************
  210. NICE::Vector histogramOfCurrentImg;
  211. bowConverter->calcHistogram ( features, histogramOfCurrentImg );
  212. bowConverter->normalizeHistogram ( histogramOfCurrentImg );
  213. //**********************************************
  214. //
  215. // CLASSIFIER EVALUATION
  216. //
  217. //**********************************************
  218. uint classno_groundtruth = classno;
  219. t.start();
  220. ClassificationResult r = classifier->classify ( histogramOfCurrentImg );
  221. t.stop();
  222. uint classno_estimated = r.classno;
  223. r.classno_groundtruth = classno_groundtruth;
  224. //if we like to store the classification results for external post processing, uncomment this
  225. if ( writeClassificationResults )
  226. {
  227. results.push_back( r );
  228. }
  229. confusionMat( classno_groundtruth, classno_estimated ) += 1;
  230. }
  231. }
  232. confusionMat.normalizeRowsL1();
  233. std::cerr << confusionMat << std::endl;
  234. std::cerr << "average recognition rate: " << confusionMat.trace()/confusionMat.rows() << std::endl;
  235. if ( writeClassificationResults )
  236. {
  237. double avgRecogResults ( results.getAverageRecognitionRate () );
  238. std::cerr << "average recognition rate according to classificationResults: " << avgRecogResults << std::endl;
  239. results.writeWEKA ( resultsfile, 0 );
  240. }
  241. return 0;
  242. }