SemSegTools.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 precision = 0.0, recall = 0.0, f1score = 0.0, iuScore = 0.0;
  88. // binary classification
  89. for ( int c = 0; c < classMappingInv.size(); c++ )
  90. {
  91. double precBase = 0.0, recBase = 0.0;
  92. for ( int r = 0; r < classMappingInv.size(); r++ )
  93. precBase += confMat(r,c);
  94. for ( int cc = 0; cc < classMappingInv.size(); cc++ )
  95. recBase += confMat(c,cc);
  96. precision += confMat(c,c) / precBase;
  97. recall += confMat(c,c) / recBase;
  98. iuScore += confMat(c,c) / (precBase+recBase-confMat(c,c));
  99. }
  100. precision /= classMappingInv.size();
  101. recall /= classMappingInv.size();
  102. iuScore /= classMappingInv.size();
  103. f1score = 2.0*(precision*recall)/(precision+recall);
  104. // normalizing confMat using rows
  105. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  106. {
  107. double sum = 0.0;
  108. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  109. sum += confMat ( r, c );
  110. if ( std::fabs ( sum ) > 1e-4 )
  111. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  112. confMat ( r, c ) /= sum;
  113. }
  114. // printing confusion matrix
  115. short int printWidth = 16;
  116. std::cout.precision(6);
  117. std::cout << std::setw(printWidth) << "";
  118. for (int r = 0; r < (int) confMat.rows(); r++)
  119. {
  120. int cl = classMappingInv[r];
  121. if ( classNames.existsClassno ( cl )
  122. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  123. {
  124. std::string cname = classNames.text ( cl );
  125. std::cout << std::setw(printWidth) << cname.c_str();
  126. }
  127. }
  128. std::cout << std::endl;
  129. for (int r = 0; r < (int) confMat.rows(); r++)
  130. {
  131. int cl = classMappingInv[r];
  132. if ( classNames.existsClassno ( cl )
  133. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  134. {
  135. std::string cname = classNames.text ( cl );
  136. std::cout << std::setw(printWidth) << cname.c_str();
  137. for (int c = 0; c < (int) confMat.cols(); c++)
  138. std::cout << std::setw(printWidth) << std::fixed << confMat (r, c);
  139. std::cout << std::endl;
  140. }
  141. }
  142. // print classification statistics
  143. std::cout << "\nAccuracy: " << overallTrue;
  144. std::cout << "\nPrecision: " << precision;
  145. std::cout << "\nRecall: " << recall;
  146. std::cout << "\nF1Score: " << f1score;
  147. std::cout << "\nIU: " << iuScore;
  148. std::cout << "\n\nAverage Recognition Rate: " << confMat.trace() / (double)classMappingInv.size();
  149. //std::cout << "\nLower Bound: " << 1.0 /(double)classMappingInv.size();
  150. std::cout << std::endl;
  151. }
  152. void SemSegTools::computeResourceStatistics (
  153. NICE::ResourceStatistics &rs )
  154. {
  155. std::cout << "\nSTATISTICS" << std::endl;
  156. std::cout << "##########\n" << std::endl;
  157. long maxMemory;
  158. double userCPUTime, sysCPUTime;
  159. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  160. std::cout << "Memory (max): " << maxMemory << " KB" << std::endl;
  161. std::cout << "CPU Time (user): " << userCPUTime << " seconds" << std::endl;
  162. std::cout << "CPU Time (sys): " << sysCPUTime << " seconds" << std::endl;
  163. }
  164. void SemSegTools::saveResultsToImageFile(
  165. const Config *conf,
  166. const string &section,
  167. const ColorImage &orig,
  168. const ColorImage &gtruth,
  169. const ColorImage &segment,
  170. const string &file,
  171. string & outStr )
  172. {
  173. std::string resultDir = conf->gS ( section, "resultdir", "." );
  174. std::string outputType = conf->gS ( section, "output_type", "ppm" );
  175. std::string outputPostfix = conf->gS ( section, "output_postfix", "" );
  176. NICE::ColorImage overlaySegment, overlayGTruth;
  177. NICE::Image* origGrey = orig.getChannel(1);
  178. segmentToOverlay( origGrey, segment, overlaySegment );
  179. segmentToOverlay( origGrey, gtruth, overlayGTruth );
  180. std::stringstream out;
  181. out << resultDir << "/" << file << outputPostfix;
  182. #ifdef DEBUG
  183. std::cout << "Writing to file " << out.str() << "_*." << outputType << std::endl;
  184. #endif
  185. orig.write ( out.str() + "_orig." + outputType );
  186. segment.write ( out.str() + "_result." + outputType );
  187. gtruth.write ( out.str() + "_groundtruth." + outputType );
  188. overlaySegment.write ( out.str() + "_overlay_res." + outputType );
  189. overlayGTruth.write ( out.str() + "_overlay_gt." + outputType );
  190. outStr = out.str();
  191. }
  192. void SemSegTools::collectTrainingExamples (
  193. const Config * conf,
  194. const std::string & section,
  195. const LabeledSet & train,
  196. const ClassNames & cn,
  197. Examples & examples,
  198. vector<CachedExample *> & imgexamples )
  199. {
  200. assert ( train.count() > 0 );
  201. examples.clear();
  202. imgexamples.clear();
  203. int grid_size_x = conf->gI(section, "grid_size_x", 5 );
  204. int grid_size_y = conf->gI(section, "grid_size_y", 5 );
  205. int grid_border_x = conf->gI(section, "grid_border_x", 20 );
  206. int grid_border_y = conf->gI(section, "grid_border_y", 20 );
  207. std::string selection = conf->gS(section, "train_selection" );
  208. set<int> classnoSelection;
  209. cn.getSelection ( selection, classnoSelection );
  210. bool useExcludedAsBG = conf->gB(section, "use_excluded_as_background", false );
  211. int backgroundClassNo = 0;
  212. if ( useExcludedAsBG )
  213. {
  214. backgroundClassNo = cn.classno("various");
  215. assert ( backgroundClassNo >= 0 );
  216. }
  217. LOOP_ALL_S (train)
  218. {
  219. EACH_INFO(image_classno,imgInfo);
  220. std::string imgfn = imgInfo.img();
  221. if ( ! imgInfo.hasLocalizationInfo() ) {
  222. std::cerr << "WARNING: NO localization info found for "
  223. << imgfn << " !" << std::endl;
  224. continue;
  225. }
  226. int xsize, ysize;
  227. CachedExample *ce = new CachedExample ( imgfn );
  228. ce->getImageSize ( xsize, ysize );
  229. imgexamples.push_back ( ce );
  230. const LocalizationResult *locResult = imgInfo.localization();
  231. if ( locResult->size() <= 0 ) {
  232. std::cerr << "WARNING: NO ground truth polygons found for "
  233. << imgfn << " !" << std::endl;
  234. continue;
  235. }
  236. std::cerr << "SemSegTools: Collecting pixel examples from localization info: "
  237. << imgfn << std::endl;
  238. NICE::ImageT<int> pixelLabels (xsize, ysize);
  239. pixelLabels.set(0);
  240. locResult->calcLabeledImage ( pixelLabels, cn.getBackgroundClass() );
  241. #ifdef DEBUG_LOCALIZATION
  242. NICE::Image img (imgfn);
  243. showImage(img);
  244. showImage(pixelLabels);
  245. #endif
  246. Example pce ( ce, 0, 0 );
  247. for ( int x = 0 ; x < xsize ; x += grid_size_x )
  248. for ( int y = 0 ; y < ysize ; y += grid_size_y )
  249. {
  250. if ( (x >= grid_border_x) &&
  251. ( y >= grid_border_y ) && ( x < xsize - grid_border_x ) &&
  252. ( y < ysize - grid_border_x ) )
  253. {
  254. pce.x = x; pce.y = y;
  255. int classno = pixelLabels.getPixel(x,y);
  256. if ( classnoSelection.find(classno) != classnoSelection.end() ) {
  257. examples.push_back ( pair<int, Example> (
  258. classno,
  259. pce // FIXME: offset handling
  260. ) );
  261. } else if ( useExcludedAsBG ) {
  262. examples.push_back ( pair<int, Example> (
  263. backgroundClassNo,
  264. pce // FIXME: offset handling
  265. ) );
  266. }
  267. }
  268. }
  269. }
  270. std::cerr << "total number of examples: " << (int)examples.size() << std::endl;
  271. }