SemanticSegmentation.cpp 15 KB

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