SemSegTools.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /**
  2. * @file SemSegTools.cpp
  3. * @brief tools for semantic segmentation
  4. * @author Erik Rodner, Sven Sickert
  5. * @date 03/19/2009
  6. */
  7. #include <iostream>
  8. #include <iomanip>
  9. #include "SemSegTools.h"
  10. using namespace OBJREC;
  11. using namespace std;
  12. using namespace NICE;
  13. #undef DEBUG_LOCALIZATION
  14. #undef DEBUG
  15. void SemSegTools::segmentToOverlay (
  16. const NICE::Image *orig,
  17. const NICE::ColorImage & segment,
  18. NICE::ColorImage & result )
  19. {
  20. int xsize = orig->width();
  21. int ysize = orig->height();
  22. result.resize( xsize, ysize );
  23. std::vector< NICE::MatrixT<double> > channelMat;
  24. double alpha = .3;
  25. for (int c = 0; c < 3; c++)
  26. {
  27. NICE::MatrixT<double> chan ( xsize, ysize );
  28. channelMat.push_back( chan );
  29. }
  30. for (int y = 0; y < ysize; y++)
  31. for (int x = 0; x < xsize; x++)
  32. {
  33. uchar val = orig->getPixelQuick(x,y);
  34. for (int c = 0; c < 3; c++)
  35. channelMat[c](x,y) = alpha*(double)val
  36. + (1.0-alpha)*(double)segment.getPixel( x, y, c );
  37. }
  38. for (int y = 0; y < ysize; y++)
  39. for (int x = 0; x < xsize; x++)
  40. for (int c = 0; c < 3; c++)
  41. {
  42. int val = channelMat[c](x,y);
  43. result.setPixel( x, y, c, (uchar)val);
  44. }
  45. }
  46. void SemSegTools::updateConfusionMatrix(
  47. const ImageT<int> &img,
  48. const ImageT<int> &gt,
  49. Matrix &M,
  50. const std::set<int> &forbiddenClasses,
  51. map<int,int> & classMapping )
  52. {
  53. double subsamplex = gt.width() / ( double ) img.width();
  54. double subsampley = gt.height() / ( double ) img.height();
  55. for ( int y = 0 ; y < gt.height() ; y++ )
  56. for ( int x = 0 ; x < gt.width() ; x++ )
  57. {
  58. int xx = ( int ) ( x / subsamplex );
  59. int yy = ( int ) ( y / subsampley );
  60. if ( xx < 0 ) xx = 0;
  61. if ( yy < 0 ) yy = 0;
  62. if ( xx > img.width() - 1 ) xx = img.width() - 1;
  63. if ( yy > img.height() - 1 ) yy = img.height() - 1;
  64. int cimg = img.getPixel ( xx, yy );
  65. int gimg = gt.getPixel ( x, y );
  66. if ( forbiddenClasses.find ( gimg ) == forbiddenClasses.end() )
  67. {
  68. M ( classMapping[gimg], classMapping[cimg] ) ++;
  69. }
  70. }
  71. }
  72. void SemSegTools::computeClassificationStatistics(
  73. Matrix &confMat,
  74. const ClassNames &classNames,
  75. const std::set<int> &forbiddenClasses,
  76. map<int,int> & classMappingInv )
  77. {
  78. std::cout << "\nPERFORMANCE" << std::endl;
  79. std::cout << "###########\n" << std::endl;
  80. double overallTrue = confMat.trace();
  81. double sumAll = 0.0;
  82. // overall recognition rate
  83. for ( int r = 0; r < (int) confMat.rows(); r++ )
  84. for ( int c = 0; c < (int) confMat.cols(); c++ )
  85. sumAll += confMat( r, c );
  86. overallTrue /= sumAll;
  87. double truePos = (double)confMat(1,1);
  88. //double trueNeg = (double)confMat(0,0);
  89. double falsePos = (double)confMat(0,1);
  90. double falseNeg = (double)confMat(1,0);
  91. // binary classification metrics
  92. if ( classMappingInv.size() == 2 )
  93. {
  94. double precision = truePos / (truePos+falsePos);
  95. double recall = truePos / (truePos+falseNeg);
  96. double f1score = 2.0*(precision*recall)/(precision+recall);
  97. std::cout << "Precision: " << precision;
  98. std::cout << "\nRecall: " << recall;
  99. std::cout << "\nF1Score: " << f1score << "\n\n";
  100. }
  101. // normalizing confMat using rows
  102. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  103. {
  104. double sum = 0.0;
  105. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  106. sum += confMat ( r, c );
  107. if ( std::fabs ( sum ) > 1e-4 )
  108. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  109. confMat ( r, c ) /= sum;
  110. }
  111. // printing confusion matrix
  112. short int printWidth = 16;
  113. std::cout.precision(6);
  114. std::cout << std::setw(printWidth) << "";
  115. for (int r = 0; r < (int) confMat.rows(); r++)
  116. {
  117. int cl = classMappingInv[r];
  118. if ( classNames.existsClassno ( cl )
  119. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  120. {
  121. std::string cname = classNames.text ( cl );
  122. std::cout << std::setw(printWidth) << cname.c_str();
  123. }
  124. }
  125. std::cout << std::endl;
  126. for (int r = 0; r < (int) confMat.rows(); r++)
  127. {
  128. int cl = classMappingInv[r];
  129. if ( classNames.existsClassno ( cl )
  130. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  131. {
  132. std::string cname = classNames.text ( cl );
  133. std::cout << std::setw(printWidth) << cname.c_str();
  134. for (int c = 0; c < (int) confMat.cols(); c++)
  135. std::cout << std::setw(printWidth) << std::fixed << confMat (r, c);
  136. std::cout << std::endl;
  137. }
  138. }
  139. // print classification statistics
  140. std::cout << "\nOverall Recognition Rate: " << overallTrue;
  141. std::cout << "\nAverage Recognition Rate: " << confMat.trace() / (double)classMappingInv.size();
  142. std::cout << "\nLower Bound: " << 1.0 /(double)classMappingInv.size();
  143. std::cout << std::endl;
  144. }
  145. void SemSegTools::computeResourceStatistics (
  146. NICE::ResourceStatistics &rs )
  147. {
  148. std::cout << "\nSTATISTICS" << std::endl;
  149. std::cout << "##########\n" << std::endl;
  150. long maxMemory;
  151. double userCPUTime, sysCPUTime;
  152. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  153. std::cout << "Memory (max): " << maxMemory << " KB" << std::endl;
  154. std::cout << "CPU Time (user): " << userCPUTime << " seconds" << std::endl;
  155. std::cout << "CPU Time (sys): " << sysCPUTime << " seconds" << std::endl;
  156. }
  157. void SemSegTools::saveResultsToImageFile(
  158. const Config *conf,
  159. const string &section,
  160. const ColorImage &orig,
  161. const ColorImage &gtruth,
  162. const ColorImage &segment,
  163. const string &file,
  164. string & outStr )
  165. {
  166. std::string resultDir = conf->gS ( section, "resultdir", "." );
  167. std::string outputType = conf->gS ( section, "output_type", "ppm" );
  168. std::string outputPostfix = conf->gS ( section, "output_postfix", "" );
  169. NICE::ColorImage overlaySegment, overlayGTruth;
  170. NICE::Image* origGrey = orig.getChannel(1);
  171. segmentToOverlay( origGrey, segment, overlaySegment );
  172. segmentToOverlay( origGrey, gtruth, overlayGTruth );
  173. std::stringstream out;
  174. out << resultDir << "/" << file << outputPostfix;
  175. #ifdef DEBUG
  176. std::cout << "Writing to file " << out.str() << "_*." << outputType << std::endl;
  177. #endif
  178. orig.write ( out.str() + "_orig." + outputType );
  179. segment.write ( out.str() + "_result." + outputType );
  180. gtruth.write ( out.str() + "_groundtruth." + outputType );
  181. overlaySegment.write ( out.str() + "_overlay_res." + outputType );
  182. overlayGTruth.write ( out.str() + "_overlay_gt." + outputType );
  183. outStr = out.str();
  184. }
  185. void SemSegTools::collectTrainingExamples (
  186. const Config * conf,
  187. const std::string & section,
  188. const LabeledSet & train,
  189. const ClassNames & cn,
  190. Examples & examples,
  191. vector<CachedExample *> & imgexamples )
  192. {
  193. assert ( train.count() > 0 );
  194. examples.clear();
  195. imgexamples.clear();
  196. int grid_size_x = conf->gI(section, "grid_size_x", 5 );
  197. int grid_size_y = conf->gI(section, "grid_size_y", 5 );
  198. int grid_border_x = conf->gI(section, "grid_border_x", 20 );
  199. int grid_border_y = conf->gI(section, "grid_border_y", 20 );
  200. std::string selection = conf->gS(section, "train_selection" );
  201. set<int> classnoSelection;
  202. cn.getSelection ( selection, classnoSelection );
  203. bool useExcludedAsBG = conf->gB(section, "use_excluded_as_background", false );
  204. int backgroundClassNo = 0;
  205. if ( useExcludedAsBG )
  206. {
  207. backgroundClassNo = cn.classno("various");
  208. assert ( backgroundClassNo >= 0 );
  209. }
  210. LOOP_ALL_S (train)
  211. {
  212. EACH_INFO(image_classno,imgInfo);
  213. std::string imgfn = imgInfo.img();
  214. if ( ! imgInfo.hasLocalizationInfo() ) {
  215. std::cerr << "WARNING: NO localization info found for "
  216. << imgfn << " !" << std::endl;
  217. continue;
  218. }
  219. int xsize, ysize;
  220. CachedExample *ce = new CachedExample ( imgfn );
  221. ce->getImageSize ( xsize, ysize );
  222. imgexamples.push_back ( ce );
  223. const LocalizationResult *locResult = imgInfo.localization();
  224. if ( locResult->size() <= 0 ) {
  225. std::cerr << "WARNING: NO ground truth polygons found for "
  226. << imgfn << " !" << std::endl;
  227. continue;
  228. }
  229. std::cerr << "SemSegTools: Collecting pixel examples from localization info: "
  230. << imgfn << std::endl;
  231. NICE::Image pixelLabels (xsize, ysize);
  232. pixelLabels.set(0);
  233. locResult->calcLabeledImage ( pixelLabels, cn.getBackgroundClass() );
  234. #ifdef DEBUG_LOCALIZATION
  235. NICE::Image img (imgfn);
  236. showImage(img);
  237. showImage(pixelLabels);
  238. #endif
  239. Example pce ( ce, 0, 0 );
  240. for ( int x = 0 ; x < xsize ; x += grid_size_x )
  241. for ( int y = 0 ; y < ysize ; y += grid_size_y )
  242. {
  243. if ( (x >= grid_border_x) &&
  244. ( y >= grid_border_y ) && ( x < xsize - grid_border_x ) &&
  245. ( y < ysize - grid_border_x ) )
  246. {
  247. pce.x = x; pce.y = y;
  248. int classno = pixelLabels.getPixel(x,y);
  249. if ( classnoSelection.find(classno) != classnoSelection.end() ) {
  250. examples.push_back ( pair<int, Example> (
  251. classno,
  252. pce // FIXME: offset handling
  253. ) );
  254. } else if ( useExcludedAsBG ) {
  255. examples.push_back ( pair<int, Example> (
  256. backgroundClassNo,
  257. pce // FIXME: offset handling
  258. ) );
  259. }
  260. }
  261. }
  262. }
  263. std::cerr << "total number of examples: " << (int)examples.size() << std::endl;
  264. }