testSemanticSegmentation3D.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Beispielhafter Aufruf: BUILD_x86_64/progs/testSemanticSegmentation -config <CONFIGFILE>
  2. /**
  3. * @file testSemanticSegmentation.cpp
  4. * @brief test semantic segmentation routines for 3d images and 2d images
  5. * @author Erik Rodner, Björn Fröhlich, Sven Sickert
  6. * @date 03/20/2008
  7. */
  8. #ifdef NICE_USELIB_OPENMP
  9. #include <omp.h>
  10. #endif
  11. #include "core/basics/Config.h"
  12. #include "core/basics/StringTools.h"
  13. #include "vislearning/baselib/ICETools.h"
  14. #include "core/image/MultiChannelImage3DT.h"
  15. #include "semseg/semseg/SemSegContextTree3D.h"
  16. #include "core/basics/ResourceStatistics.h"
  17. #include "core/image/Morph.h"
  18. #include <fstream>
  19. #include <vector>
  20. #undef DEBUG
  21. using namespace OBJREC;
  22. using namespace NICE;
  23. using namespace std;
  24. void segmentToOverlay ( const NICE::Image *orig, const NICE::ColorImage & segment,
  25. NICE::ColorImage & result )
  26. {
  27. int xsize = orig->width();
  28. int ysize = orig->height();
  29. result.resize( xsize, ysize );
  30. vector< NICE::MatrixT<double> > channelMat;
  31. double alpha = .5;
  32. for (int c = 0; c < 3; c++)
  33. {
  34. NICE::MatrixT<double> chan ( xsize, ysize );
  35. channelMat.push_back( chan );
  36. }
  37. for (int y = 0; y < ysize; y++)
  38. {
  39. for (int x = 0; x < xsize; x++)
  40. {
  41. uchar val = orig->getPixelQuick(x,y);
  42. for (int c = 0; c < 3; c++)
  43. channelMat[c](x,y) = (double)val + alpha*(double)segment.getPixel( x, y, c );
  44. }
  45. }
  46. for (int c = 0; c < 3; c++)
  47. {
  48. channelMat[c] /= channelMat[c].Max();
  49. channelMat[c] *= 255;
  50. }
  51. for (int y = 0; y < ysize; y++)
  52. {
  53. for (int x = 0; x < xsize; x++)
  54. {
  55. for (int c = 0; c < 3; c++)
  56. {
  57. int val = channelMat[c](x,y);
  58. result.setPixel( x, y, c, (uchar)val);
  59. }
  60. }
  61. }
  62. }
  63. void updateMatrix ( const NICE::Image & img,
  64. const NICE::Image & gt,
  65. NICE::Matrix & M,
  66. const set<int> & forbidden_classes )
  67. {
  68. double subsamplex = gt.width() / ( double ) img.width();
  69. double subsampley = gt.height() / ( double ) img.height();
  70. for ( int y = 0 ; y < gt.height() ; y++ )
  71. for ( int x = 0 ; x < gt.width() ; x++ )
  72. {
  73. int xx = ( int ) ( x / subsamplex );
  74. int yy = ( int ) ( y / subsampley );
  75. if ( xx < 0 ) xx = 0;
  76. if ( yy < 0 ) yy = 0;
  77. if ( xx > img.width() - 1 ) xx = img.width() - 1;
  78. if ( yy > img.height() - 1 ) yy = img.height() - 1;
  79. int cimg = img.getPixel ( xx, yy );
  80. int gimg = gt.getPixel ( x, y );
  81. if ( forbidden_classes.find ( gimg ) == forbidden_classes.end() )
  82. {
  83. M ( gimg, cimg ) ++;
  84. }
  85. }
  86. }
  87. void startClassification (SemanticSegmentation *semseg,
  88. std::vector< NICE::Matrix > & M_vec,
  89. const Config & conf,
  90. const LabeledSet* testFiles,
  91. const ClassNames & classNames,
  92. const set<int> & forbidden_classes,
  93. const string & resultdir,
  94. const bool doCrossVal)
  95. {
  96. bool show_results = conf.gB ( "debug", "show_results", false );
  97. bool write_results = conf.gB ( "debug", "write_results", false );
  98. bool writeProbMaps = conf.gB ( "debug", "write_prob_maps", false );
  99. if (doCrossVal)
  100. write_results = false;
  101. bool run_3Dseg = conf.gB( "SSContextTree", "run_3dseg", false);
  102. bool postProcessing = conf.gB( "main", "post_process", false);
  103. string output_type = conf.gS ( "debug", "output_type", "ppm" );
  104. string output_postfix = conf.gS ( "debug", "output_postfix", "" );
  105. vector< int > zsizeVec;
  106. semseg->getDepthVector ( testFiles, zsizeVec, run_3Dseg );
  107. int depthCount = 0, idx = 0;
  108. vector< string > filelist;
  109. NICE::MultiChannelImageT<double> segresult;
  110. NICE::MultiChannelImageT<double> gt;
  111. for (LabeledSet::const_iterator it = testFiles->begin(); it != testFiles->end(); it++)
  112. {
  113. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  114. jt != it->second.end(); jt++)
  115. {
  116. ImageInfo & info = *(*jt);
  117. std::string file = info.img();
  118. filelist.push_back ( file );
  119. depthCount++;
  120. NICE::Image lm;
  121. NICE::Image lm_gt;
  122. if ( info.hasLocalizationInfo() )
  123. {
  124. const LocalizationResult *l_gt = info.localization();
  125. lm.resize ( l_gt->xsize, l_gt->ysize );
  126. lm.set ( 0 );
  127. lm_gt.resize ( l_gt->xsize, l_gt->ysize );
  128. lm_gt.set ( 0 );
  129. l_gt->calcLabeledImage ( lm, classNames.getBackgroundClass() );
  130. #ifdef DEBUG
  131. cout << "testSemanticSegmentation3D: Generating Labeled NICE::Image (Ground-Truth)" << endl;
  132. #endif
  133. l_gt->calcLabeledImage ( lm_gt, classNames.getBackgroundClass() );
  134. }
  135. segresult.addChannel ( lm );
  136. gt.addChannel ( lm_gt );
  137. int depthBoundary = 0;
  138. if ( run_3Dseg )
  139. {
  140. depthBoundary = zsizeVec[idx];
  141. }
  142. if ( depthCount < depthBoundary ) continue;
  143. NICE::MultiChannelImage3DT<double> probabilities;
  144. semseg->classify ( filelist, segresult, probabilities );
  145. // save to file
  146. for ( int z = 0; z < segresult.channels(); z++ )
  147. {
  148. std::string fname = StringTools::baseName ( filelist[z], false );
  149. if ( show_results || write_results )
  150. {
  151. NICE::ColorImage orig ( filelist[z] );
  152. NICE::ColorImage rgb;
  153. NICE::ColorImage rgb_gt;
  154. NICE::ColorImage ov_rgb;
  155. NICE::ColorImage ov_rgb_gt;
  156. for ( int y = 0 ; y < orig.height(); y++ )
  157. {
  158. for ( int x = 0 ; x < orig.width(); x++ )
  159. {
  160. lm.setPixel ( x, y, segresult.get ( x, y, ( uint ) z ) );
  161. if ( run_3Dseg )
  162. lm_gt.setPixel ( x, y, gt.get ( x, y, ( uint ) z ) );
  163. }
  164. }
  165. // confusion matrix
  166. NICE::Matrix M ( classNames.getMaxClassno() + 1, classNames.getMaxClassno() + 1 );
  167. M.set ( 0 );
  168. updateMatrix ( lm, lm_gt, M, forbidden_classes );
  169. M_vec.push_back ( M );
  170. classNames.labelToRGB ( lm, rgb );
  171. classNames.labelToRGB ( lm_gt, rgb_gt );
  172. if (postProcessing)
  173. {
  174. // median filter
  175. for (int r = 0; r < 3; r++)
  176. {
  177. NICE::Image postIm(rgb.width(), rgb.height());
  178. NICE::median(*(rgb.getChannel(r)), &postIm, 1);
  179. for (int y = 0; y < rgb.height(); y++)
  180. for (int x = 0; x < rgb.width(); x++)
  181. rgb.setPixel(x,y,r, postIm.getPixelQuick(x,y));
  182. }
  183. }
  184. if ( write_results )
  185. {
  186. segmentToOverlay ( orig.getChannel(1), rgb, ov_rgb );
  187. segmentToOverlay ( orig.getChannel(1), rgb_gt, ov_rgb_gt );
  188. std::stringstream out;
  189. if ( output_postfix.size() > 0 )
  190. out << resultdir << "/" << fname << output_postfix;
  191. else
  192. out << resultdir << "/" << fname;
  193. #ifdef DEBUG
  194. cout << "Writing to file " << out.str() << "_*." << output_type << endl;
  195. #endif
  196. orig.write ( out.str() + "_orig." + output_type );
  197. rgb.write ( out.str() + "_result." + output_type );
  198. rgb_gt.write ( out.str() + "_groundtruth." + output_type );
  199. ov_rgb.write ( out.str() + "_overlay_res." + output_type );
  200. ov_rgb_gt.write ( out.str() + "_overlay_gt." + output_type );
  201. // write Probability maps
  202. if (writeProbMaps)
  203. {
  204. NICE::ColorImage prob_map( probabilities.width(), probabilities.height() );
  205. prob_map.set(0,0,0);
  206. int iNumChannels = probabilities.channels();
  207. for ( int idxProbMap = 0; idxProbMap < iNumChannels; idxProbMap++)
  208. {
  209. for ( int y = 0 ; y < probabilities.height(); y++ )
  210. {
  211. for ( int x = 0 ; x < probabilities.width(); x++ )
  212. {
  213. double probVal = probabilities.get( x, y, z, idxProbMap ) * 255.0;
  214. int tmp = round(probVal);
  215. for ( int c = 0 ; c < 3 ; c++ )
  216. prob_map.setPixel( x, y, c, tmp );
  217. }
  218. }
  219. std::stringstream ssFileProbMap;
  220. //ssFileProbMap << out.str() << "_probs." << "c" << idxProbMap << "." << output_type;
  221. ssFileProbMap << out.str() << "_probs." << "c-" << classNames.code( idxProbMap ) << "." << output_type;
  222. //classNames
  223. prob_map.write ( ssFileProbMap.str() );
  224. }
  225. }
  226. }
  227. }
  228. }
  229. // prepare for new 3d image
  230. filelist.clear();
  231. segresult.reInit(0,0,0);
  232. gt.reInit(0,0,0);
  233. depthCount = 0;
  234. idx++;
  235. }
  236. }
  237. segresult.freeData();
  238. }
  239. /**
  240. test semantic segmentation routines
  241. */
  242. int main ( int argc, char **argv )
  243. {
  244. std::set_terminate ( __gnu_cxx::__verbose_terminate_handler );
  245. Config conf ( argc, argv );
  246. ResourceStatistics rs;
  247. /*---------------CONFIGURATION---------------*/
  248. bool doCrossVal = conf.gB ( "debug", "do_crossval", false );
  249. string resultdir = conf.gS ( "debug", "resultdir", "." );
  250. /*-------------------------------------------*/
  251. #ifdef DEBUG
  252. cerr << "Writing Results to " << resultdir << endl;
  253. #endif
  254. std::vector< NICE::Matrix > M_vec;
  255. MultiDataset md ( &conf );
  256. const ClassNames & classNames = md.getClassNames ( "train" );
  257. set<int> forbidden_classes;
  258. classNames.getSelection ( conf.gS ( "analysis", "forbidden_classes", "" ),
  259. forbidden_classes );
  260. // initialize semantic segmentation method
  261. SemanticSegmentation *semseg = NULL;
  262. // TRAINING AND TESTING
  263. if (!doCrossVal)
  264. {
  265. semseg = new SemSegContextTree3D ( &conf, &classNames );
  266. // STANDARD EVALUATION
  267. cout << "\nTRAINING" << endl;
  268. cout << "########\n" << endl;
  269. semseg->train( &md );
  270. cout << "\nCLASSIFICATION" << endl;
  271. cout << "##############\n" << endl;
  272. const LabeledSet *testFiles = md["test"];
  273. startClassification (semseg, M_vec, conf, testFiles, classNames,
  274. forbidden_classes, resultdir, doCrossVal );
  275. delete semseg;
  276. }
  277. else
  278. {
  279. // CROSS-VALIDATION
  280. for (int cval = 1; cval <= 10; cval++)
  281. {
  282. semseg = new SemSegContextTree3D ( &conf, &classNames );
  283. stringstream ss;
  284. ss << cval;
  285. string cvaltrain = "train_cv" + ss.str();
  286. string cvaltest = "test_cv" + ss.str();
  287. cout << "\nTRAINING " << cval << endl;
  288. cout << "###########\n" << endl;
  289. const LabeledSet *trainFiles = md[cvaltrain];
  290. semseg->train( trainFiles );
  291. cout << "\nCLASSIFICATION " << cval << endl;
  292. cout << "#################\n" << endl;
  293. const LabeledSet *testFiles = md[cvaltest];
  294. startClassification (semseg, M_vec, conf, testFiles, classNames,
  295. forbidden_classes, resultdir, doCrossVal );
  296. delete semseg;
  297. }
  298. }
  299. cout << "\nSTATISTICS" << endl;
  300. cout << "##########\n" << endl;
  301. long maxMemory;
  302. double userCPUTime, sysCPUTime;
  303. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  304. cout << "Memory (max): " << maxMemory << " KB" << endl;
  305. cout << "CPU Time (user): " << userCPUTime << " seconds" << endl;
  306. cout << "CPU Time (sys): " << sysCPUTime << " seconds" << endl;
  307. cout << "\nPERFORMANCE" << endl;
  308. cout << "###########\n" << endl;
  309. double overall = 0.0;
  310. double sumall = 0.0;
  311. NICE::Matrix M ( classNames.getMaxClassno() + 1, classNames.getMaxClassno() + 1 );
  312. M.set ( 0 );
  313. for ( int s = 0; s < ( int ) M_vec.size(); s++ )
  314. {
  315. NICE::Matrix M_tmp = M_vec[s];
  316. for ( int r = 0; r < ( int ) M_tmp.rows(); r++ )
  317. {
  318. for ( int c = 0; c < ( int ) M_tmp.cols(); c++ )
  319. {
  320. if ( r == c )
  321. overall += M_tmp ( r, c );
  322. sumall += M_tmp ( r, c );
  323. M ( r, c ) += M_tmp ( r, c );
  324. }
  325. }
  326. }
  327. overall /= sumall;
  328. cout << "Confusion Matrix:" << endl;
  329. for (int r = 0; r < (int) M.rows(); r++)
  330. {
  331. for (int c = 0; c < (int) M.cols(); c++)
  332. {
  333. cout << M(r,c) << " ";
  334. }
  335. cout << endl;
  336. }
  337. // metrics for binary classification
  338. double precision, recall, f1score = -1.0;
  339. if (classNames.getMaxClassno()+1 == 2)
  340. {
  341. precision = (double)M(1,1) / (double)(M(1,1)+M(0,1));
  342. recall = (double)M(1,1) / (double)(M(1,1)+M(1,0));
  343. f1score = 2.0*(precision*recall)/(precision+recall);
  344. }
  345. // normalizing M using rows
  346. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  347. {
  348. double sum = 0.0;
  349. for ( int c = 0 ; c < ( int ) M.cols() ; c++ )
  350. sum += M ( r, c );
  351. if ( fabs ( sum ) > 1e-4 )
  352. for ( int c = 0 ; c < ( int ) M.cols() ; c++ )
  353. M ( r, c ) /= sum;
  354. }
  355. double avg_perf = 0.0;
  356. int classes_trained = 0;
  357. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  358. {
  359. if ( ( classNames.existsClassno ( r ) ) && ( forbidden_classes.find ( r ) == forbidden_classes.end() ) )
  360. {
  361. avg_perf += M ( r, r );
  362. double lsum = 0.0;
  363. for ( int r2 = 0; r2 < ( int ) M.rows(); r2++ )
  364. {
  365. lsum += M ( r,r2 );
  366. }
  367. if ( lsum != 0.0 )
  368. {
  369. classes_trained++;
  370. }
  371. }
  372. }
  373. // print results of evaluation
  374. cout << "Overall Recogntion Rate: " << overall << endl;
  375. cout << "Average Recogntion Rate: " << avg_perf / ( classes_trained ) << endl;
  376. cout << "Lower Bound: " << 1.0 / classes_trained << endl;
  377. cout << "Precision: " << precision << endl;
  378. cout << "Recall: " << recall << endl;
  379. cout << "F1Score: " << f1score << endl;
  380. cout <<"\nClasses:" << endl;
  381. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  382. {
  383. if ( ( classNames.existsClassno ( r ) ) && ( forbidden_classes.find ( r ) == forbidden_classes.end() ) )
  384. {
  385. std::string classname = classNames.text ( r );
  386. cout << classname.c_str() << ": " << M ( r, r ) << endl;
  387. }
  388. }
  389. return 0;
  390. }