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