SemanticSegmentation.cpp 14 KB

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