SemanticSegmentation.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /**
  2. * @file SemanticSegmentation.cpp
  3. * @brief abstract interface for semantic segmentation algorithms
  4. * @author Erik Rodner, Alexander Freytag, Sven Sickert
  5. * @date 03/19/2009
  6. */
  7. #include "SemanticSegmentation.h"
  8. #include <core/basics/StringTools.h>
  9. #include <vislearning/baselib/Preprocess.h>
  10. #include <vislearning/baselib/Globals.h>
  11. #include <iostream>
  12. using namespace OBJREC;
  13. using namespace std;
  14. using namespace NICE;
  15. ///////////////////// ///////////////////// /////////////////////
  16. // CONSTRUCTORS / DESTRUCTORS
  17. ///////////////////// ///////////////////// /////////////////////
  18. SemanticSegmentation::SemanticSegmentation ( )
  19. : iterationCountSuffix(1)
  20. {
  21. this->imagetype = IMAGETYPE_RGB;
  22. this->classNames = new ClassNames();
  23. }
  24. SemanticSegmentation::SemanticSegmentation ( const Config *conf,
  25. const ClassNames *classNames )
  26. : iterationCountSuffix(1)
  27. {
  28. ///////////
  29. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  30. ///////////
  31. ///////////
  32. // here comes the new code part different from the empty constructor
  33. ///////////
  34. this->classNames = classNames;
  35. this->initFromConfig( conf );
  36. }
  37. SemanticSegmentation::~SemanticSegmentation()
  38. {
  39. }
  40. void SemanticSegmentation::initFromConfig(const Config* conf, const string& s_confSection)
  41. {
  42. std::string imagetype_s = conf->gS ( "main", "imagetype", "rgb" );
  43. coarseMode = conf->gB( "main", "coarse_mode", false );
  44. if ( imagetype_s == "rgb" )
  45. imagetype = IMAGETYPE_RGB;
  46. else if ( imagetype_s == "gray" )
  47. imagetype = IMAGETYPE_GRAY;
  48. else {
  49. fprintf ( stderr, "SemanticSegmentation:: unknown image type option\n" );
  50. exit ( -1 );
  51. }
  52. // dangerous!!!
  53. Preprocess::Init ( conf );
  54. }
  55. ///////////////////// ///////////////////// /////////////////////
  56. // SEGMENTATION STUFF
  57. ///////////////////// ///////////////////// /////////////////////
  58. void SemanticSegmentation::semanticseg ( const std::string & filename,
  59. NICE::ImageT<int> & segresult,
  60. NICE::MultiChannelImageT<double> & probabilities )
  61. {
  62. Globals::setCurrentImgFN ( filename );
  63. CachedExample *ce;
  64. if ( imagetype == IMAGETYPE_RGB )
  65. {
  66. NICE::ColorImage img = Preprocess::ReadImgAdvRGB ( filename );
  67. ce = new CachedExample ( img );
  68. } else {
  69. NICE::Image img = Preprocess::ReadImgAdv ( filename );
  70. ce = new CachedExample ( img );
  71. }
  72. #ifdef DEBUG_PRINTS
  73. fprintf ( stderr, "Starting Semantic Segmentation !\n" );
  74. #endif
  75. this->semanticseg ( ce, segresult, probabilities );
  76. delete ce;
  77. }
  78. void SemanticSegmentation::classify ( const std::vector<std::string> & filelist,
  79. NICE::MultiChannelImageT<int> & segresult,
  80. NICE::MultiChannelImage3DT<double> & probabilities )
  81. {
  82. for ( int it = 0; it < ( int ) filelist.size(); it++ )
  83. {
  84. NICE::MultiChannelImageT<double> probs;
  85. NICE::ImageT<int> res ( segresult.width(), segresult.height() );
  86. this->semanticseg( filelist[it], res, probs );
  87. probabilities.addChannel( probs );
  88. segresult.addChannel( res );
  89. }
  90. }
  91. ///////////////////// ///////////////////// /////////////////////
  92. // DATA CONVERSION
  93. ///////////////////// ///////////////////// /////////////////////
  94. void SemanticSegmentation::convertLSetToSparseExamples ( Examples &examples, LabeledSetVector &lvec )
  95. {
  96. #ifdef DEBUG_PRINTS
  97. cout << "SemSegRegionBased::convertLSetToExamples starts" << endl;
  98. #endif
  99. for ( map< int, vector<NICE::Vector *> >::iterator iter = lvec.begin(); iter != lvec.end(); ++iter )
  100. {
  101. for ( int j = 0; j < ( int ) iter->second.size(); j++ )
  102. {
  103. Vector &tmp = * ( iter->second[j] );
  104. int dim = tmp.size();
  105. SparseVector *vec = new SparseVector ( dim );
  106. for ( int j = 0; j < dim; j++ )
  107. {
  108. if ( tmp[j] != 0.0 )
  109. {
  110. ( *vec ) [j] = tmp[j];
  111. }
  112. }
  113. Example ex;
  114. ex.svec = vec;
  115. examples.push_back ( pair<int, Example> ( iter->first, ex ) );
  116. }
  117. }
  118. lvec.clear();
  119. #ifdef DEBUG_PRINTS
  120. cout << "SemSegRegionBased::convertLSetToExamples finished" << endl;
  121. #endif
  122. }
  123. void SemanticSegmentation::convertLSetToExamples ( Examples &examples, LabeledSetVector &lvec, const bool & removeOldDataPointer )
  124. {
  125. #ifdef DEBUG_PRINTS
  126. cout << "SemSegRegionBased::convertLSetToExamples starts" << endl;
  127. #endif
  128. for ( map< int, vector<NICE::Vector *> >::iterator iter = lvec.begin(); iter != lvec.end(); ++iter )
  129. {
  130. for ( int j = 0; j < (int)iter->second.size(); j++ )
  131. {
  132. NICE::Vector *vec = new NICE::Vector ( * ( iter->second[j] ) );
  133. Example ex ( vec );
  134. examples.push_back ( pair<int, Example> ( iter->first, ex ) );
  135. }
  136. }
  137. if (!removeOldDataPointer)
  138. {
  139. //NOTE this is only useful, if our classifier does NOT need the data explicitely
  140. lvec.clear();
  141. }
  142. else
  143. {
  144. lvec.removePointersToDataWithoutDeletion();
  145. //after setting all the pointers to NULL, we can savely clear the LSet without deleting the previously
  146. //stored features, which might be needed somewhere else, e.g., in the VCNearestNeighbour
  147. lvec.clear();
  148. }
  149. #ifdef DEBUG_PRINTS
  150. cout << "SemSegRegionBased::convertLSetToExamples finished" << endl;
  151. #endif
  152. }
  153. void SemanticSegmentation::convertExamplesToLSet ( Examples &examples, LabeledSetVector &lvec )
  154. {
  155. #ifdef DEBUG_PRINTS
  156. cout << "SemSegRegionBased::convertExamplesToLSet starts" << endl;
  157. #endif
  158. lvec.clear();
  159. for ( int i = 0; i < ( int ) examples.size(); i++ )
  160. {
  161. if ( examples[i].second.vec != NULL )
  162. {
  163. lvec.add ( examples[i].first, *examples[i].second.vec );
  164. delete examples[i].second.vec;
  165. examples[i].second.vec = NULL;
  166. }
  167. else
  168. {
  169. if ( examples[i].second.svec != NULL )
  170. {
  171. NICE::Vector v;
  172. examples[i].second.svec->convertToVectorT(v);
  173. lvec.add ( examples[i].first, v );
  174. delete examples[i].second.svec;
  175. examples[i].second.svec = NULL;
  176. }
  177. else
  178. {
  179. throw ( "no features for LabeledSet" );
  180. }
  181. }
  182. }
  183. examples.clear();
  184. #ifdef DEBUG_PRINTS
  185. cout << "SemSegRegionBased::convertExamplesToLSet finished" << endl;
  186. #endif
  187. }
  188. void SemanticSegmentation::convertExamplesToVVector ( VVector &feats, Examples &examples, vector<int> &label )
  189. {
  190. #ifdef DEBUG_PRINTS
  191. cout << "SemSegRegionBased::convertExamplesToVVector starts" << endl;
  192. #endif
  193. feats.clear();
  194. label.clear();
  195. for ( int i = 0; i < ( int ) examples.size(); i++ )
  196. {
  197. label.push_back ( examples[i].first );
  198. feats.push_back ( *examples[i].second.vec );
  199. delete examples[i].second.vec;
  200. examples[i].second.vec = NULL;
  201. }
  202. examples.clear();
  203. #ifdef DEBUG_PRINTS
  204. cout << "SemSegRegionBased::convertExamplesToVVector finished" << endl;
  205. #endif
  206. }
  207. void SemanticSegmentation::convertVVectorToExamples ( VVector &feats, Examples &examples, vector<int> &label )
  208. {
  209. #ifdef DEBUG_PRINTS
  210. cout << "SemSegRegionBased::convertVVectorToExamples starts" << endl;
  211. #endif
  212. for ( int i = 0; i < ( int ) feats.size(); i++ )
  213. {
  214. NICE::Vector *v = new NICE::Vector ( feats[i] );
  215. Example ex ( v );
  216. ex.position = 0; //TODO: hier mal was besseres überlegen, damit Klassifikator wieder Bildspezifisch lernt
  217. examples.push_back ( pair<int, Example> ( label[i], ex ) );
  218. feats[i].clear();
  219. }
  220. feats.clear();
  221. label.clear();
  222. #ifdef DEBUG_PRINTS
  223. cout << "SemSegRegionBased::convertVVectorToExamples finished" << endl;
  224. #endif
  225. }
  226. void SemanticSegmentation::setIterationCountSuffix( const int & _iterationCountSuffix)
  227. {
  228. this->iterationCountSuffix = _iterationCountSuffix;
  229. }
  230. void SemanticSegmentation::setClassNames ( const OBJREC::ClassNames * _classNames )
  231. {
  232. this->classNames = _classNames;
  233. }
  234. void SemanticSegmentation::getDepthVector ( const LabeledSet *Files,
  235. vector<int> & depthVec,
  236. const bool run3Dseg )
  237. {
  238. std::string oldName;
  239. int zsize = 0;
  240. bool isInit = false;
  241. for (LabeledSet::const_iterator it = Files->begin(); it != Files->end(); it++)
  242. {
  243. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  244. jt != it->second.end(); jt++)
  245. {
  246. ImageInfo & info = *(*jt);
  247. std::string file = info.img();
  248. std::vector< std::string > list;
  249. StringTools::split ( file, '/', list );
  250. std::string filename = list.back();
  251. uint found = filename.find_last_of ( "_" );
  252. if (run3Dseg && found < filename.size() && found-3 > 0 )
  253. {
  254. std::string curName = filename.substr ( found-3,3 );
  255. if ( !isInit )
  256. {
  257. oldName = curName;
  258. isInit = true;
  259. }
  260. if ( curName.compare ( oldName ) == 0 ) // if strings match up
  261. {
  262. zsize++;
  263. }
  264. else
  265. {
  266. depthVec.push_back ( zsize );
  267. zsize = 1;
  268. oldName = curName;
  269. }
  270. }
  271. else
  272. {
  273. zsize = 1;
  274. depthVec.push_back ( zsize );
  275. }
  276. }
  277. }
  278. depthVec.push_back ( zsize );
  279. }
  280. void SemanticSegmentation::make3DImage ( const std::vector<std::string> & filelist,
  281. NICE::MultiChannelImage3DT<double> & imgData )
  282. {
  283. bool isInit = false;
  284. for ( int it = 0; it < ( int ) filelist.size(); it++ )
  285. {
  286. if ( imagetype == IMAGETYPE_RGB )
  287. {
  288. NICE::ColorImage img;
  289. try
  290. {
  291. img.read ( filelist[it] );
  292. }
  293. catch ( ImageException iE )
  294. {
  295. fprintf ( stderr, "Failed to open color image file: %s\n", filelist[it].c_str() );
  296. fprintf ( stderr, "%s\n", iE.what() );
  297. exit ( -1 );
  298. }
  299. if ( !isInit )
  300. {
  301. imgData.reInit ( img.width(),img.height(),filelist.size(),3 );
  302. isInit = true;
  303. }
  304. for ( int y = 0; y < img.height(); y++ )
  305. {
  306. for ( int x = 0; x < img.width(); x++ )
  307. {
  308. for ( int r = 0; r < 3; r++ )
  309. {
  310. imgData.set ( x, y, it, img.getPixel ( x,y,r ), r );
  311. }
  312. }
  313. }
  314. }
  315. else
  316. {
  317. NICE::Image img;
  318. try
  319. {
  320. img.read ( filelist[it] );
  321. }
  322. catch ( ImageException iE )
  323. {
  324. fprintf ( stderr, "Failed to open image file: %s\n", filelist[it].c_str() );
  325. fprintf ( stderr, "%s\n", iE.what() );
  326. exit ( -1 );
  327. }
  328. if ( !isInit )
  329. {
  330. imgData.reInit ( img.width(),img.height(),filelist.size(),1 );
  331. isInit = true;
  332. }
  333. for ( int y = 0; y < img.height(); y++ )
  334. {
  335. for ( int x = 0; x < img.width(); x++ )
  336. {
  337. imgData.set ( x, y, it, img.getPixel ( x,y ), 0 );
  338. }
  339. }
  340. }
  341. }
  342. if ( imagetype == IMAGETYPE_GRAY )
  343. {
  344. imgData.equalizeHistogram( 0 );
  345. #ifdef DEBUG_PRINTS
  346. for (int z = 0; z < imgData.depth(); z++)
  347. {
  348. NICE::Image im = imgData.getChannel( z, 0);
  349. im.write( filelist[z]+"_eq.pgm");
  350. }
  351. #endif
  352. }
  353. }
  354. void SemanticSegmentation::getProbabilityMap ( const NICE::MultiChannelImage3DT<double> & prob )
  355. {
  356. std::string s;
  357. for ( int cl = 0; cl < prob.channels(); cl++ )
  358. for ( int z = 0; z < prob.depth(); z++ )
  359. {
  360. NICE::ColorImage img( prob.width(),prob.height() );
  361. NICE::ImageT<double> m = prob.getChannelT(z, cl);
  362. imageToPseudoColor(m, img);
  363. std::stringstream out;
  364. out << "probmap_s" << z << "_c" << cl << ".ppm";
  365. s = out.str();
  366. img.write( s );
  367. //showImage(img, "Probability map");
  368. //getchar();
  369. }
  370. }
  371. ///////////////////// INTERFACE PERSISTENT /////////////////////
  372. // interface specific methods for store and restore
  373. ///////////////////// INTERFACE PERSISTENT /////////////////////
  374. void SemanticSegmentation::restore ( std::istream & is, int format )
  375. {
  376. //delete everything we knew so far...
  377. this->clear();
  378. bool b_restoreVerbose ( false );
  379. #ifdef B_RESTOREVERBOSE
  380. b_restoreVerbose = true;
  381. #endif
  382. if ( is.good() )
  383. {
  384. if ( b_restoreVerbose )
  385. std::cerr << " restore SemanticSegmentation" << std::endl;
  386. std::string tmp;
  387. is >> tmp; //class name
  388. if ( ! this->isStartTag( tmp, "SemanticSegmentation" ) )
  389. {
  390. std::cerr << " WARNING - attempt to restore SemanticSegmentation, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  391. throw;
  392. }
  393. is.precision (numeric_limits<double>::digits10 + 1);
  394. bool b_endOfBlock ( false ) ;
  395. while ( !b_endOfBlock )
  396. {
  397. is >> tmp; // start of block
  398. if ( this->isEndTag( tmp, "SemanticSegmentation" ) )
  399. {
  400. b_endOfBlock = true;
  401. continue;
  402. }
  403. tmp = this->removeStartTag ( tmp );
  404. if ( b_restoreVerbose )
  405. std::cerr << " currently restore section " << tmp << " in SemanticSegmentation" << std::endl;
  406. if ( tmp.compare("classNames") == 0 )
  407. {
  408. //dirty solution to circumvent the const-flag
  409. const_cast<ClassNames*>(this->classNames)->restore ( is, format );
  410. is >> tmp; // end of block
  411. tmp = this->removeEndTag ( tmp );
  412. }
  413. else if ( tmp.compare("imagetype") == 0 )
  414. {
  415. unsigned int ui_imagetyp;
  416. is >> ui_imagetyp;
  417. this->imagetype = static_cast<IMAGETYP> ( ui_imagetyp );
  418. is >> tmp; // end of block
  419. tmp = this->removeEndTag ( tmp );
  420. }
  421. else if ( tmp.compare("iterationCountSuffix") == 0 )
  422. {
  423. is >> this->iterationCountSuffix;
  424. is >> tmp; // end of block
  425. tmp = this->removeEndTag ( tmp );
  426. }
  427. else
  428. {
  429. std::cerr << "WARNING -- unexpected SemanticSegmentation object -- " << tmp << " -- for restoration... aborting" << std::endl;
  430. throw;
  431. }
  432. }
  433. }
  434. else
  435. {
  436. std::cerr << "SemanticSegmentation::restore -- InStream not initialized - restoring not possible!" << std::endl;
  437. throw;
  438. }
  439. //TODO check whether we also have to do something linke Preprocess::Init ( conf );
  440. }
  441. void SemanticSegmentation::store ( std::ostream & os, int format ) const
  442. {
  443. if (os.good())
  444. {
  445. // show starting point
  446. os << this->createStartTag( "SemanticSegmentation" ) << std::endl;
  447. os.precision (numeric_limits<double>::digits10 + 1);
  448. os << this->createStartTag( "classNames" ) << std::endl;
  449. this->classNames->store ( os, format );
  450. os << this->createEndTag( "classNames" ) << std::endl;
  451. //
  452. os << this->createStartTag( "imagetype" ) << std::endl;
  453. os << imagetype << std::endl;
  454. os << this->createEndTag( "imagetype" ) << std::endl;
  455. //
  456. os << this->createStartTag( "iterationCountSuffix" ) << std::endl;
  457. os << iterationCountSuffix << std::endl;
  458. os << this->createEndTag( "iterationCountSuffix" ) << std::endl;
  459. // done
  460. os << this->createEndTag( "SemanticSegmentation" ) << std::endl;
  461. }
  462. else
  463. {
  464. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  465. }
  466. }
  467. void SemanticSegmentation::clear ()
  468. {
  469. //TODO
  470. }