SemSegTools.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 accuracy = 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. accuracy /= sumAll;
  88. double prec = 0.0, rec = 0.0, f1score = 0.0, iuScore = 0.0;
  89. // classification
  90. int normConst = classMappingInv.size();
  91. for ( int c = 0; c < classMappingInv.size(); c++ )
  92. {
  93. std::cout << "Class " << classNames.text( classMappingInv[c] ) << ":" << std::endl;
  94. double precBase = 0.0, recBase = 0.0;
  95. // row-wise sum
  96. for ( int r = 0; r < classMappingInv.size(); r++ )
  97. precBase += confMat(r,c);
  98. // column-wise sum
  99. for ( int cc = 0; cc < classMappingInv.size(); cc++ )
  100. recBase += confMat(c,cc);
  101. double precClass = 0, recClass = 0;
  102. if (precBase > 0) precClass = confMat(c,c) / precBase;
  103. if (recBase > 0) recClass = confMat(c,c) / recBase;
  104. std::cout << " Precision: " << precClass << std::endl;
  105. std::cout << " Recall: " << recClass << std::endl;
  106. prec += precClass;
  107. rec += recClass;
  108. if (precBase > 0 && recBase > 0)
  109. iuScore += confMat(c,c) / (precBase+recBase-confMat(c,c));
  110. else
  111. normConst--;
  112. }
  113. prec /= (double)normConst;
  114. rec /= (double)normConst;
  115. iuScore /= (double)normConst;
  116. f1score = 2.0*(prec*rec)/(prec+rec);
  117. // row-wise normalization of confMat
  118. for ( int r = 0 ; r < (int) confMat.rows() ; r++ )
  119. {
  120. double sum = 0.0;
  121. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  122. sum += confMat ( r, c );
  123. if ( std::fabs ( sum ) > 1e-4 )
  124. for ( int c = 0 ; c < (int) confMat.cols() ; c++ )
  125. confMat ( r, c ) /= sum;
  126. }
  127. // printing confusion matrix
  128. short int printWidth = 16;
  129. std::cout.precision(6);
  130. std::cout << std::setw(printWidth) << "";
  131. for (int r = 0; r < (int) confMat.rows(); r++)
  132. {
  133. int cl = classMappingInv[r];
  134. if ( classNames.existsClassno ( cl )
  135. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  136. {
  137. std::string cname = classNames.text ( cl );
  138. std::cout << std::setw(printWidth) << cname.c_str();
  139. }
  140. }
  141. std::cout << std::endl;
  142. for (int r = 0; r < (int) confMat.rows(); r++)
  143. {
  144. int cl = classMappingInv[r];
  145. if ( classNames.existsClassno ( cl )
  146. && ( forbiddenClasses.find ( cl ) == forbiddenClasses.end() ) )
  147. {
  148. std::string cname = classNames.text ( cl );
  149. std::cout << std::setw(printWidth) << cname.c_str();
  150. for (int c = 0; c < (int) confMat.cols(); c++)
  151. std::cout << std::setw(printWidth) << std::fixed << confMat (r, c);
  152. std::cout << std::endl;
  153. }
  154. }
  155. // print classification statistics
  156. std::cout << "\nAccuracy: " << accuracy;
  157. std::cout << "\nPrecision: " << prec;
  158. std::cout << "\nRecall: " << rec;
  159. std::cout << "\nF1Score: " << f1score;
  160. std::cout << "\nIU: " << iuScore;
  161. //std::cout << "\n\nAverage Recognition Rate: " << confMat.trace() / (double)classMappingInv.size();
  162. //std::cout << "\nLower Bound: " << 1.0 /(double)classMappingInv.size();
  163. std::cout << std::endl;
  164. }
  165. void SemSegTools::computeResourceStatistics (
  166. NICE::ResourceStatistics &rs )
  167. {
  168. std::cout << "\nSTATISTICS" << std::endl;
  169. std::cout << "##########\n" << std::endl;
  170. long maxMemory;
  171. double userCPUTime, sysCPUTime;
  172. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  173. std::cout << "Memory (max): " << maxMemory << " KB" << std::endl;
  174. std::cout << "CPU Time (user): " << userCPUTime << " seconds" << std::endl;
  175. std::cout << "CPU Time (sys): " << sysCPUTime << " seconds" << std::endl;
  176. }
  177. void SemSegTools::saveResultsToImageFile(
  178. const Config *conf,
  179. const string &section,
  180. const ColorImage &orig,
  181. const ColorImage &gtruth,
  182. const ColorImage &segment,
  183. const string &file,
  184. string & outStr )
  185. {
  186. std::string resultDir = conf->gS ( section, "resultdir", "." );
  187. std::string outputType = conf->gS ( section, "output_type", "ppm" );
  188. std::string outputPostfix = conf->gS ( section, "output_postfix", "" );
  189. NICE::ColorImage overlaySegment, overlayGTruth;
  190. NICE::Image* origGrey = orig.getChannel(1);
  191. segmentToOverlay( origGrey, segment, overlaySegment );
  192. segmentToOverlay( origGrey, gtruth, overlayGTruth );
  193. std::stringstream out;
  194. out << resultDir << "/" << file << outputPostfix;
  195. #ifdef DEBUG
  196. std::cout << "Writing to file " << out.str() << "_*." << outputType << std::endl;
  197. #endif
  198. orig.write ( out.str() + "_orig." + outputType );
  199. segment.write ( out.str() + "_result." + outputType );
  200. gtruth.write ( out.str() + "_groundtruth." + outputType );
  201. overlaySegment.write ( out.str() + "_overlay_res." + outputType );
  202. overlayGTruth.write ( out.str() + "_overlay_gt." + outputType );
  203. outStr = out.str();
  204. }
  205. void SemSegTools::getDepthVector (
  206. const LabeledSet *Files,
  207. std::vector<int> & depthVec,
  208. const bool run3Dseg )
  209. {
  210. std::string oldName;
  211. int zsize = 0;
  212. bool isInit = false;
  213. for (LabeledSet::const_iterator it = Files->begin(); it != Files->end(); it++)
  214. {
  215. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  216. jt != it->second.end(); jt++)
  217. {
  218. ImageInfo & info = *(*jt);
  219. std::string file = info.img();
  220. std::vector< std::string > list;
  221. StringTools::split ( file, '/', list );
  222. std::string filename = list.back();
  223. uint found = filename.find_last_of ( "_" );
  224. if (run3Dseg && found < filename.size() && found-3 > 0 )
  225. {
  226. std::string curName = filename.substr ( found-3,3 );
  227. if ( !isInit )
  228. {
  229. oldName = curName;
  230. isInit = true;
  231. }
  232. if ( curName.compare ( oldName ) == 0 ) // if strings match up
  233. {
  234. zsize++;
  235. }
  236. else
  237. {
  238. depthVec.push_back ( zsize );
  239. zsize = 1;
  240. oldName = curName;
  241. }
  242. }
  243. else
  244. {
  245. zsize = 1;
  246. depthVec.push_back ( zsize );
  247. }
  248. }
  249. }
  250. depthVec.push_back ( zsize );
  251. }
  252. void SemSegTools::collectTrainingExamples (
  253. const Config * conf,
  254. const std::string & section,
  255. const LabeledSet & train,
  256. const ClassNames & cn,
  257. Examples & examples,
  258. vector<CachedExample *> & imgexamples,
  259. const bool run3Dseg )
  260. {
  261. assert ( train.count() > 0 );
  262. examples.clear();
  263. imgexamples.clear();
  264. vector<int> zsizeVec;
  265. SemSegTools::getDepthVector ( &train, zsizeVec, run3Dseg );
  266. int grid_size_x = conf->gI(section, "grid_size_x", 5 );
  267. int grid_size_y = conf->gI(section, "grid_size_y", 5 );
  268. int grid_size_z = conf->gI(section, "grid_size_z", 5 );
  269. int grid_border_x = conf->gI(section, "grid_border_x", 20 );
  270. int grid_border_y = conf->gI(section, "grid_border_y", 20 );
  271. int grid_border_z = conf->gI(section, "grid_border_z", 20 );
  272. if (!run3Dseg)
  273. {
  274. grid_size_z = 1;
  275. grid_border_z = 0;
  276. }
  277. std::string selection = conf->gS(section, "train_selection" );
  278. set<int> classnoSelection;
  279. cn.getSelection ( selection, classnoSelection );
  280. bool useExcludedAsBG = conf->gB(section, "use_excluded_as_background", false );
  281. int backgroundClassNo = 0;
  282. if ( useExcludedAsBG )
  283. {
  284. backgroundClassNo = cn.classno("various");
  285. assert ( backgroundClassNo >= 0 );
  286. }
  287. int depthCount = 0;
  288. int imgCounter = 0;
  289. vector<std::string> filelist;
  290. NICE::MultiChannelImageT<int> pixelLabels;
  291. for (LabeledSet::const_iterator it = train.begin(); it != train.end(); it++)
  292. {
  293. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  294. jt != it->second.end(); jt++)
  295. {
  296. ImageInfo & info = *(*jt);
  297. std::string file = info.img();
  298. filelist.push_back ( file );
  299. depthCount++;
  300. const LocalizationResult *locResult = info.localization();
  301. // getting groundtruth
  302. NICE::ImageT<int> pL;
  303. pL.resize ( locResult->xsize, locResult->ysize );
  304. pL.set ( 0 );
  305. locResult->calcLabeledImage ( pL, cn.getBackgroundClass() );
  306. pixelLabels.addChannel ( pL );
  307. if ( locResult->size() <= 0 ) {
  308. std::cerr << "WARNING: NO ground truth polygons found for "
  309. << file << " !" << std::endl;
  310. continue;
  311. }
  312. std::cerr << "SemSegTools: Collecting pixel examples from localization info: "
  313. << file << std::endl;
  314. int depthBoundary = 0;
  315. if ( run3Dseg )
  316. {
  317. depthBoundary = zsizeVec[imgCounter];
  318. }
  319. if ( depthCount < depthBoundary ) continue;
  320. int xsize, ysize, zsize;
  321. CachedExample *ce = new CachedExample ( filelist );
  322. ce->getImageSize3 ( xsize, ysize, zsize );
  323. imgexamples.push_back ( ce );
  324. // drawing actual examples
  325. Example pce ( ce, 0, 0, 0 );
  326. for ( int z = 0; z < zsize; z += grid_size_z )
  327. for ( int x = 0 ; x < xsize ; x += grid_size_x )
  328. for ( int y = 0 ; y < ysize ; y += grid_size_y )
  329. if ( ( x >= grid_border_x ) &&
  330. ( y >= grid_border_y ) &&
  331. ( z >= grid_border_z ) &&
  332. ( x < xsize - grid_border_x ) &&
  333. ( y < ysize - grid_border_y ) &&
  334. ( z < zsize - grid_border_z ) )
  335. {
  336. pce.x = x; pce.y = y; pce.z = z;
  337. int classno = pixelLabels.get(x,y,(unsigned int)z);
  338. if ( classnoSelection.find(classno) != classnoSelection.end() )
  339. {
  340. examples.push_back (
  341. pair<int, Example> ( classno, pce ) );
  342. } else if ( useExcludedAsBG )
  343. {
  344. examples.push_back (
  345. pair<int, Example> ( backgroundClassNo, pce ) );
  346. }
  347. }
  348. // prepare for new 3D image
  349. filelist.clear();
  350. pixelLabels.reInit ( 0,0,0 );
  351. depthCount = 0;
  352. imgCounter++;
  353. }
  354. }
  355. std::cerr << "total number of examples: " << (int)examples.size() << std::endl;
  356. }