testSemanticSegmentation3D.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. if (doCrossVal)
  99. write_results = false;
  100. bool run_3Dseg = conf.gB( "SSContextTree", "run_3dseg", false);
  101. bool postProcessing = conf.gB( "main", "post_process", false);
  102. string output_type = conf.gS ( "debug", "output_type", "ppm" );
  103. string output_postfix = conf.gS ( "debug", "output_postfix", "" );
  104. vector< int > zsizeVec;
  105. semseg->getDepthVector ( testFiles, zsizeVec, run_3Dseg );
  106. int depthCount = 0, idx = 0;
  107. vector< string > filelist;
  108. NICE::MultiChannelImageT<double> segresult;
  109. NICE::MultiChannelImageT<double> gt;
  110. for (LabeledSet::const_iterator it = testFiles->begin(); it != testFiles->end(); it++)
  111. {
  112. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  113. jt != it->second.end(); jt++)
  114. {
  115. ImageInfo & info = *(*jt);
  116. std::string file = info.img();
  117. filelist.push_back ( file );
  118. depthCount++;
  119. NICE::Image lm;
  120. NICE::Image lm_gt;
  121. if ( info.hasLocalizationInfo() )
  122. {
  123. const LocalizationResult *l_gt = info.localization();
  124. lm.resize ( l_gt->xsize, l_gt->ysize );
  125. lm.set ( 0 );
  126. lm_gt.resize ( l_gt->xsize, l_gt->ysize );
  127. lm_gt.set ( 0 );
  128. l_gt->calcLabeledImage ( lm, classNames.getBackgroundClass() );
  129. #ifdef DEBUG
  130. cout << "testSemanticSegmentation3D: Generating Labeled NICE::Image (Ground-Truth)" << endl;
  131. #endif
  132. l_gt->calcLabeledImage ( lm_gt, classNames.getBackgroundClass() );
  133. }
  134. segresult.addChannel ( lm );
  135. gt.addChannel ( lm_gt );
  136. int depthBoundary = 0;
  137. if ( run_3Dseg )
  138. {
  139. depthBoundary = zsizeVec[idx];
  140. }
  141. if ( depthCount < depthBoundary ) continue;
  142. NICE::MultiChannelImage3DT<double> probabilities;
  143. semseg->classify ( filelist, segresult, probabilities );
  144. // save to file
  145. for ( int z = 0; z < segresult.channels(); z++ )
  146. {
  147. std::string fname = StringTools::baseName ( filelist[z], false );
  148. if ( show_results || write_results )
  149. {
  150. NICE::ColorImage orig ( filelist[z] );
  151. NICE::ColorImage rgb;
  152. NICE::ColorImage rgb_gt;
  153. NICE::ColorImage ov_rgb;
  154. NICE::ColorImage ov_rgb_gt;
  155. for ( int y = 0 ; y < orig.height(); y++ )
  156. {
  157. for ( int x = 0 ; x < orig.width(); x++ )
  158. {
  159. lm.setPixel ( x, y, segresult.get ( x, y, ( uint ) z ) );
  160. if ( run_3Dseg )
  161. lm_gt.setPixel ( x, y, gt.get ( x, y, ( uint ) z ) );
  162. }
  163. }
  164. // confusion matrix
  165. NICE::Matrix M ( classNames.getMaxClassno() + 1, classNames.getMaxClassno() + 1 );
  166. M.set ( 0 );
  167. updateMatrix ( lm, lm_gt, M, forbidden_classes );
  168. M_vec.push_back ( M );
  169. classNames.labelToRGB ( lm, rgb );
  170. classNames.labelToRGB ( lm_gt, rgb_gt );
  171. if (postProcessing)
  172. {
  173. // median filter
  174. for (int r = 0; r < 3; r++)
  175. {
  176. NICE::Image postIm(rgb.width(), rgb.height());
  177. NICE::median(*(rgb.getChannel(r)), &postIm, 1);
  178. for (int y = 0; y < rgb.height(); y++)
  179. for (int x = 0; x < rgb.width(); x++)
  180. rgb.setPixel(x,y,r, postIm.getPixelQuick(x,y));
  181. }
  182. }
  183. if ( write_results )
  184. {
  185. segmentToOverlay ( orig.getChannel(1), rgb, ov_rgb );
  186. segmentToOverlay ( orig.getChannel(1), rgb_gt, ov_rgb_gt );
  187. std::stringstream out;
  188. if ( output_postfix.size() > 0 )
  189. out << resultdir << "/" << fname << output_postfix;
  190. else
  191. out << resultdir << "/" << fname;
  192. #ifdef DEBUG
  193. cout << "Writing to file " << out.str() << "_*." << output_type << endl;
  194. #endif
  195. orig.write ( out.str() + "_orig." + output_type );
  196. rgb.write ( out.str() + "_result." + output_type );
  197. rgb_gt.write ( out.str() + "_groundtruth." + output_type );
  198. ov_rgb.write ( out.str() + "_overlay_res." + output_type );
  199. ov_rgb_gt.write ( out.str() + "_overlay_gt." + output_type );
  200. // write Probability maps
  201. NICE::ColorImage prob_map( probabilities.width(), probabilities.height() );
  202. prob_map.set(0,0,0);
  203. int iNumChannels = probabilities.channels();
  204. for ( int idxProbMap = 0; idxProbMap < iNumChannels; idxProbMap++)
  205. {
  206. for ( int y = 0 ; y < probabilities.height(); y++ )
  207. {
  208. for ( int x = 0 ; x < probabilities.width(); x++ )
  209. {
  210. double probVal = probabilities.get( x, y, z, idxProbMap ) * 255.0;
  211. int tmp = round(probVal);
  212. for ( int c = 0 ; c < 3 ; c++ )
  213. prob_map.setPixel( x, y, c, tmp );
  214. }
  215. }
  216. std::stringstream ssFileProbMap;
  217. //ssFileProbMap << out.str() << "_probs." << "c" << idxProbMap << "." << output_type;
  218. ssFileProbMap << out.str() << "_probs." << "c-" << classNames.code( idxProbMap ) << "." << output_type;
  219. //classNames
  220. prob_map.write ( ssFileProbMap.str() );
  221. }
  222. }
  223. }
  224. }
  225. // prepare for new 3d image
  226. filelist.clear();
  227. segresult.reInit(0,0,0);
  228. gt.reInit(0,0,0);
  229. depthCount = 0;
  230. idx++;
  231. }
  232. }
  233. segresult.freeData();
  234. }
  235. /**
  236. test semantic segmentation routines
  237. */
  238. int main ( int argc, char **argv )
  239. {
  240. std::set_terminate ( __gnu_cxx::__verbose_terminate_handler );
  241. Config conf ( argc, argv );
  242. ResourceStatistics rs;
  243. /*---------------CONFIGURATION---------------*/
  244. bool doCrossVal = conf.gB ( "debug", "do_crossval", false );
  245. string resultdir = conf.gS ( "debug", "resultdir", "." );
  246. /*-------------------------------------------*/
  247. #ifdef DEBUG
  248. cerr << "Writing Results to " << resultdir << endl;
  249. #endif
  250. std::vector< NICE::Matrix > M_vec;
  251. MultiDataset md ( &conf );
  252. const ClassNames & classNames = md.getClassNames ( "train" );
  253. set<int> forbidden_classes;
  254. classNames.getSelection ( conf.gS ( "analysis", "forbidden_classes", "" ),
  255. forbidden_classes );
  256. // initialize semantic segmentation method
  257. SemanticSegmentation *semseg = NULL;
  258. // TRAINING AND TESTING
  259. if (!doCrossVal)
  260. {
  261. semseg = new SemSegContextTree3D ( &conf, &classNames );
  262. // STANDARD EVALUATION
  263. cout << "\nTRAINING" << endl;
  264. cout << "########\n" << endl;
  265. semseg->train( &md );
  266. cout << "\nCLASSIFICATION" << endl;
  267. cout << "##############\n" << endl;
  268. const LabeledSet *testFiles = md["test"];
  269. startClassification (semseg, M_vec, conf, testFiles, classNames,
  270. forbidden_classes, resultdir, doCrossVal );
  271. delete semseg;
  272. }
  273. else
  274. {
  275. // CROSS-VALIDATION
  276. for (int cval = 1; cval <= 10; cval++)
  277. {
  278. semseg = new SemSegContextTree3D ( &conf, &classNames );
  279. stringstream ss;
  280. ss << cval;
  281. string cvaltrain = "train_cv" + ss.str();
  282. string cvaltest = "test_cv" + ss.str();
  283. cout << "\nTRAINING " << cval << endl;
  284. cout << "###########\n" << endl;
  285. const LabeledSet *trainFiles = md[cvaltrain];
  286. semseg->train( trainFiles );
  287. cout << "\nCLASSIFICATION " << cval << endl;
  288. cout << "#################\n" << endl;
  289. const LabeledSet *testFiles = md[cvaltest];
  290. startClassification (semseg, M_vec, conf, testFiles, classNames,
  291. forbidden_classes, resultdir, doCrossVal );
  292. delete semseg;
  293. }
  294. }
  295. cout << "\nSTATISTICS" << endl;
  296. cout << "##########\n" << endl;
  297. long maxMemory;
  298. double userCPUTime, sysCPUTime;
  299. rs.getStatistics ( maxMemory, userCPUTime, sysCPUTime );
  300. cout << "Memory (max): " << maxMemory << " KB" << endl;
  301. cout << "CPU Time (user): " << userCPUTime << " seconds" << endl;
  302. cout << "CPU Time (sys): " << sysCPUTime << " seconds" << endl;
  303. cout << "\nPERFORMANCE" << endl;
  304. cout << "###########\n" << endl;
  305. double overall = 0.0;
  306. double sumall = 0.0;
  307. NICE::Matrix M ( classNames.getMaxClassno() + 1, classNames.getMaxClassno() + 1 );
  308. M.set ( 0 );
  309. for ( int s = 0; s < ( int ) M_vec.size(); s++ )
  310. {
  311. NICE::Matrix M_tmp = M_vec[s];
  312. for ( int r = 0; r < ( int ) M_tmp.rows(); r++ )
  313. {
  314. for ( int c = 0; c < ( int ) M_tmp.cols(); c++ )
  315. {
  316. if ( r == c )
  317. overall += M_tmp ( r, c );
  318. sumall += M_tmp ( r, c );
  319. M ( r, c ) += M_tmp ( r, c );
  320. }
  321. }
  322. }
  323. overall /= sumall;
  324. cout << "Confusion Matrix:" << endl;
  325. for (int r = 0; r < (int) M.rows(); r++)
  326. {
  327. for (int c = 0; c < (int) M.cols(); c++)
  328. {
  329. cout << M(r,c) << " ";
  330. }
  331. cout << endl;
  332. }
  333. // metrics for binary classification
  334. double precision, recall, f1score = -1.0;
  335. if (classNames.getMaxClassno()+1 == 2)
  336. {
  337. precision = (double)M(1,1) / (double)(M(1,1)+M(0,1));
  338. recall = (double)M(1,1) / (double)(M(1,1)+M(1,0));
  339. f1score = 2.0*(precision*recall)/(precision+recall);
  340. }
  341. // normalizing M using rows
  342. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  343. {
  344. double sum = 0.0;
  345. for ( int c = 0 ; c < ( int ) M.cols() ; c++ )
  346. sum += M ( r, c );
  347. if ( fabs ( sum ) > 1e-4 )
  348. for ( int c = 0 ; c < ( int ) M.cols() ; c++ )
  349. M ( r, c ) /= sum;
  350. }
  351. double avg_perf = 0.0;
  352. int classes_trained = 0;
  353. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  354. {
  355. if ( ( classNames.existsClassno ( r ) ) && ( forbidden_classes.find ( r ) == forbidden_classes.end() ) )
  356. {
  357. avg_perf += M ( r, r );
  358. double lsum = 0.0;
  359. for ( int r2 = 0; r2 < ( int ) M.rows(); r2++ )
  360. {
  361. lsum += M ( r,r2 );
  362. }
  363. if ( lsum != 0.0 )
  364. {
  365. classes_trained++;
  366. }
  367. }
  368. }
  369. // print results of evaluation
  370. cout << "Overall Recogntion Rate: " << overall << endl;
  371. cout << "Average Recogntion Rate: " << avg_perf / ( classes_trained ) << endl;
  372. cout << "Lower Bound: " << 1.0 / classes_trained << endl;
  373. cout << "Precision: " << precision << endl;
  374. cout << "Recall: " << recall << endl;
  375. cout << "F1Score: " << f1score << endl;
  376. cout <<"\nClasses:" << endl;
  377. for ( int r = 0 ; r < ( int ) M.rows() ; r++ )
  378. {
  379. if ( ( classNames.existsClassno ( r ) ) && ( forbidden_classes.find ( r ) == forbidden_classes.end() ) )
  380. {
  381. std::string classname = classNames.text ( r );
  382. cout << classname.c_str() << ": " << M ( r, r ) << endl;
  383. }
  384. }
  385. return 0;
  386. }