SemSegTools.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 "core/basics/StringTools.h"
  10. #include "SemSegTools.h"
  11. using namespace OBJREC;
  12. using namespace std;
  13. using namespace NICE;
  14. #undef DEBUG_LOCALIZATION
  15. #undef DEBUG
  16. void SemSegTools::segmentToOverlay (
  17. const NICE::Image *orig,
  18. const NICE::ColorImage & segment,
  19. NICE::ColorImage & result )
  20. {
  21. int xsize = orig->width();
  22. int ysize = orig->height();
  23. result.resize( xsize, ysize );
  24. std::vector< NICE::MatrixT<double> > channelMat;
  25. double alpha = .3;
  26. for (int c = 0; c < 3; c++)
  27. {
  28. NICE::MatrixT<double> chan ( xsize, ysize );
  29. channelMat.push_back( chan );
  30. }
  31. for (int y = 0; y < ysize; y++)
  32. for (int x = 0; x < xsize; x++)
  33. {
  34. uchar val = orig->getPixelQuick(x,y);
  35. for (int c = 0; c < 3; c++)
  36. channelMat[c](x,y) = alpha*(double)val
  37. + (1.0-alpha)*(double)segment.getPixel( x, y, c );
  38. }
  39. for (int y = 0; y < ysize; y++)
  40. for (int x = 0; x < xsize; x++)
  41. for (int c = 0; c < 3; c++)
  42. {
  43. int val = channelMat[c](x,y);
  44. result.setPixel( x, y, c, (uchar)val);
  45. }
  46. }
  47. void SemSegTools::updateConfusionMatrix(
  48. const ImageT<int> &img,
  49. const ImageT<int> &gt,
  50. Matrix &M,
  51. const std::set<int> &forbiddenClasses,
  52. map<int,int> & classMapping )
  53. {
  54. double subsamplex = gt.width() / ( double ) img.width();
  55. double subsampley = gt.height() / ( double ) img.height();
  56. for ( int y = 0 ; y < gt.height() ; y++ )
  57. for ( int x = 0 ; x < gt.width() ; x++ )
  58. {
  59. int xx = ( int ) ( x / subsamplex );
  60. int yy = ( int ) ( y / subsampley );
  61. if ( xx < 0 ) xx = 0;
  62. if ( yy < 0 ) yy = 0;
  63. if ( xx > img.width() - 1 ) xx = img.width() - 1;
  64. if ( yy > img.height() - 1 ) yy = img.height() - 1;
  65. int cimg = img.getPixel ( xx, yy );
  66. int gimg = gt.getPixel ( x, y );
  67. if ( forbiddenClasses.find ( gimg ) == forbiddenClasses.end() )
  68. {
  69. M ( classMapping[gimg], classMapping[cimg] ) ++;
  70. }
  71. }
  72. }
  73. void SemSegTools::computeClassificationStatistics(
  74. Matrix &confMat,
  75. const ClassNames &classNames,
  76. const std::set<int> &forbiddenClasses,
  77. map<int,int> & classMappingInv )
  78. {
  79. std::cout << "\nPERFORMANCE" << std::endl;
  80. std::cout << "###########\n" << std::endl;
  81. double overallTrue = confMat.trace();
  82. double sumAll = 0.0;
  83. // overall recognition rate
  84. for ( int r = 0; r < (int) confMat.rows(); r++ )
  85. for ( int c = 0; c < (int) confMat.cols(); c++ )
  86. sumAll += confMat( r, c );
  87. overallTrue /= sumAll;
  88. double precision = 0.0, recall = 0.0, f1score = 0.0, iuScore = 0.0;
  89. // binary classification
  90. for ( int c = 0; c < classMappingInv.size(); c++ )
  91. {
  92. double precBase = 0.0, recBase = 0.0;
  93. for ( int r = 0; r < classMappingInv.size(); r++ )
  94. precBase += confMat(r,c);
  95. for ( int cc = 0; cc < classMappingInv.size(); cc++ )
  96. recBase += confMat(c,cc);
  97. precision += confMat(c,c) / precBase;
  98. recall += confMat(c,c) / recBase;
  99. iuScore += confMat(c,c) / (precBase+recBase-confMat(c,c));
  100. }
  101. precision /= classMappingInv.size();
  102. recall /= classMappingInv.size();
  103. iuScore /= classMappingInv.size();
  104. f1score = 2.0*(precision*recall)/(precision+recall);
  105. // normalizing confMat using rows
  106. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  107. {
  108. double sum = 0.0;
  109. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  110. sum += confMat ( r, c );
  111. if ( std::fabs ( sum ) > 1e-4 )
  112. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  113. confMat ( r, c ) /= sum;
  114. }
  115. // printing confusion matrix
  116. short int printWidth = 16;
  117. std::cout.precision(6);
  118. std::cout << std::setw(printWidth) << "";
  119. for (int r = 0; r < (int) confMat.rows(); r++)
  120. {
  121. int cl = classMappingInv[r];
  122. if ( classNames.existsClassno ( cl )
  123. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  124. {
  125. std::string cname = classNames.text ( cl );
  126. std::cout << std::setw(printWidth) << cname.c_str();
  127. }
  128. }
  129. std::cout << std::endl;
  130. for (int r = 0; r < (int) confMat.rows(); r++)
  131. {
  132. int cl = classMappingInv[r];
  133. if ( classNames.existsClassno ( cl )
  134. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  135. {
  136. std::string cname = classNames.text ( cl );
  137. std::cout << std::setw(printWidth) << cname.c_str();
  138. for (int c = 0; c < (int) confMat.cols(); c++)
  139. std::cout << std::setw(printWidth) << std::fixed << confMat (r, c);
  140. std::cout << std::endl;
  141. }
  142. }
  143. // print classification statistics
  144. std::cout << "\nAccuracy: " << overallTrue;
  145. std::cout << "\nPrecision: " << precision;
  146. std::cout << "\nRecall: " << recall;
  147. std::cout << "\nF1Score: " << f1score;
  148. std::cout << "\nIU: " << iuScore;
  149. std::cout << "\n\nAverage Recognition Rate: " << confMat.trace() / (double)classMappingInv.size();
  150. //std::cout << "\nLower Bound: " << 1.0 /(double)classMappingInv.size();
  151. std::cout << std::endl;
  152. }
  153. void SemSegTools::computeResourceStatistics (
  154. NICE::ResourceStatistics &rs )
  155. {
  156. std::cout << "\nSTATISTICS" << std::endl;
  157. std::cout << "##########\n" << std::endl;
  158. long maxMemory;
  159. double userCPUTime, sysCPUTime;
  160. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  161. std::cout << "Memory (max): " << maxMemory << " KB" << std::endl;
  162. std::cout << "CPU Time (user): " << userCPUTime << " seconds" << std::endl;
  163. std::cout << "CPU Time (sys): " << sysCPUTime << " seconds" << std::endl;
  164. }
  165. void SemSegTools::saveResultsToImageFile(
  166. const Config *conf,
  167. const string &section,
  168. const ColorImage &orig,
  169. const ColorImage &gtruth,
  170. const ColorImage &segment,
  171. const string &file,
  172. string & outStr )
  173. {
  174. std::string resultDir = conf->gS ( section, "resultdir", "." );
  175. std::string outputType = conf->gS ( section, "output_type", "ppm" );
  176. std::string outputPostfix = conf->gS ( section, "output_postfix", "" );
  177. NICE::ColorImage overlaySegment, overlayGTruth;
  178. NICE::Image* origGrey = orig.getChannel(1);
  179. segmentToOverlay( origGrey, segment, overlaySegment );
  180. segmentToOverlay( origGrey, gtruth, overlayGTruth );
  181. std::stringstream out;
  182. out << resultDir << "/" << file << outputPostfix;
  183. #ifdef DEBUG
  184. std::cout << "Writing to file " << out.str() << "_*." << outputType << std::endl;
  185. #endif
  186. orig.write ( out.str() + "_orig." + outputType );
  187. segment.write ( out.str() + "_result." + outputType );
  188. gtruth.write ( out.str() + "_groundtruth." + outputType );
  189. overlaySegment.write ( out.str() + "_overlay_res." + outputType );
  190. overlayGTruth.write ( out.str() + "_overlay_gt." + outputType );
  191. outStr = out.str();
  192. }
  193. void SemSegTools::getDepthVector (
  194. const LabeledSet *Files,
  195. std::vector<int> & depthVec,
  196. const bool run3Dseg )
  197. {
  198. std::string oldName;
  199. int zsize = 0;
  200. bool isInit = false;
  201. for (LabeledSet::const_iterator it = Files->begin(); it != Files->end(); it++)
  202. {
  203. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  204. jt != it->second.end(); jt++)
  205. {
  206. ImageInfo & info = *(*jt);
  207. std::string file = info.img();
  208. std::vector< std::string > list;
  209. StringTools::split ( file, '/', list );
  210. std::string filename = list.back();
  211. uint found = filename.find_last_of ( "_" );
  212. if (run3Dseg && found < filename.size() && found-3 > 0 )
  213. {
  214. std::string curName = filename.substr ( found-3,3 );
  215. if ( !isInit )
  216. {
  217. oldName = curName;
  218. isInit = true;
  219. }
  220. if ( curName.compare ( oldName ) == 0 ) // if strings match up
  221. {
  222. zsize++;
  223. }
  224. else
  225. {
  226. depthVec.push_back ( zsize );
  227. zsize = 1;
  228. oldName = curName;
  229. }
  230. }
  231. else
  232. {
  233. zsize = 1;
  234. depthVec.push_back ( zsize );
  235. }
  236. }
  237. }
  238. depthVec.push_back ( zsize );
  239. }
  240. void SemSegTools::collectTrainingExamples (
  241. const Config * conf,
  242. const std::string & section,
  243. const LabeledSet & train,
  244. const ClassNames & cn,
  245. Examples & examples,
  246. vector<CachedExample *> & imgexamples,
  247. const bool run3Dseg )
  248. {
  249. assert ( train.count() > 0 );
  250. examples.clear();
  251. imgexamples.clear();
  252. vector<int> zsizeVec;
  253. SemSegTools::getDepthVector ( &train, zsizeVec, run3Dseg );
  254. int grid_size_x = conf->gI(section, "grid_size_x", 5 );
  255. int grid_size_y = conf->gI(section, "grid_size_y", 5 );
  256. int grid_size_z = conf->gI(section, "grid_size_z", 5 );
  257. int grid_border_x = conf->gI(section, "grid_border_x", 20 );
  258. int grid_border_y = conf->gI(section, "grid_border_y", 20 );
  259. int grid_border_z = conf->gI(section, "grid_border_z", 20 );
  260. std::string selection = conf->gS(section, "train_selection" );
  261. set<int> classnoSelection;
  262. cn.getSelection ( selection, classnoSelection );
  263. bool useExcludedAsBG = conf->gB(section, "use_excluded_as_background", false );
  264. int backgroundClassNo = 0;
  265. if ( useExcludedAsBG )
  266. {
  267. backgroundClassNo = cn.classno("various");
  268. assert ( backgroundClassNo >= 0 );
  269. }
  270. int depthCount = 0;
  271. int imgCounter = 0;
  272. vector<std::string> filelist;
  273. NICE::MultiChannelImageT<int> pixelLabels;
  274. for (LabeledSet::const_iterator it = train.begin(); it != train.end(); it++)
  275. {
  276. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  277. jt != it->second.end(); jt++)
  278. {
  279. ImageInfo & info = *(*jt);
  280. std::string file = info.img();
  281. filelist.push_back ( file );
  282. depthCount++;
  283. const LocalizationResult *locResult = info.localization();
  284. // getting groundtruth
  285. NICE::ImageT<int> pL;
  286. pL.resize ( locResult->xsize, locResult->ysize );
  287. pL.set ( 0 );
  288. locResult->calcLabeledImage ( pL, cn.getBackgroundClass() );
  289. pixelLabels.addChannel ( pL );
  290. if ( locResult->size() <= 0 ) {
  291. std::cerr << "WARNING: NO ground truth polygons found for "
  292. << file << " !" << std::endl;
  293. continue;
  294. }
  295. std::cerr << "SemSegTools: Collecting pixel examples from localization info: "
  296. << file << std::endl;
  297. int depthBoundary = 0;
  298. if ( run3Dseg )
  299. {
  300. depthBoundary = zsizeVec[imgCounter];
  301. }
  302. if ( depthCount < depthBoundary ) continue;
  303. int xsize, ysize, zsize;
  304. CachedExample *ce = new CachedExample ( filelist );
  305. ce->getImageSize3 ( xsize, ysize, zsize );
  306. imgexamples.push_back ( ce );
  307. // drawing actual examples
  308. Example pce ( ce, 0, 0, 0 );
  309. for ( int z = 0; z < zsize; z += grid_size_z )
  310. for ( int x = 0 ; x < xsize ; x += grid_size_x )
  311. for ( int y = 0 ; y < ysize ; y += grid_size_y )
  312. if ( ( x >= grid_border_x ) &&
  313. ( y >= grid_border_y ) &&
  314. ( z >= grid_border_z ) &&
  315. ( x < xsize - grid_border_x ) &&
  316. ( y < ysize - grid_border_y ) &&
  317. ( z < zsize - grid_border_z ) )
  318. {
  319. pce.x = x; pce.y = y; pce.z = z;
  320. int classno = pixelLabels.get(x,y,(unsigned int)z);
  321. if ( classnoSelection.find(classno) != classnoSelection.end() )
  322. {
  323. examples.push_back (
  324. pair<int, Example> ( classno, pce ) );
  325. } else if ( useExcludedAsBG )
  326. {
  327. examples.push_back (
  328. pair<int, Example> ( backgroundClassNo, pce ) );
  329. }
  330. }
  331. // prepare for new 3D image
  332. filelist.clear();
  333. pixelLabels.reInit ( 0,0,0 );
  334. depthCount = 0;
  335. imgCounter++;
  336. }
  337. }
  338. std::cerr << "total number of examples: " << (int)examples.size() << std::endl;
  339. }