SemanticSegmentation.cpp 15 KB

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