SemanticSegmentation.cpp 14 KB

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