SemanticSegmentation.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 "vislearning/baselib/Preprocess.h"
  9. #include "vislearning/baselib/Globals.h"
  10. #include <iostream>
  11. using namespace OBJREC;
  12. using namespace std;
  13. using namespace NICE;
  14. ///////////////////// ///////////////////// /////////////////////
  15. // CONSTRUCTORS / DESTRUCTORS
  16. ///////////////////// ///////////////////// /////////////////////
  17. SemanticSegmentation::SemanticSegmentation ( )
  18. : iterationCountSuffix(1)
  19. {
  20. this->imagetype = IMAGETYPE_RGB;
  21. this->classNames = new ClassNames();
  22. }
  23. SemanticSegmentation::SemanticSegmentation ( const Config *conf,
  24. const ClassNames *classNames )
  25. : iterationCountSuffix(1)
  26. {
  27. ///////////
  28. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  29. ///////////
  30. ///////////
  31. // here comes the new code part different from the empty constructor
  32. ///////////
  33. this->classNames = classNames;
  34. this->initFromConfig( conf );
  35. }
  36. SemanticSegmentation::~SemanticSegmentation()
  37. {
  38. }
  39. void SemanticSegmentation::initFromConfig(const Config* conf, const string& s_confSection)
  40. {
  41. std::string imagetype_s = conf->gS ( "main", "imagetype", "rgb" );
  42. coarseMode = conf->gB( "main", "coarse_mode", false );
  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::ImageT<int> & 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<int> & 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::ImageT<int> 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::make3DImage ( const std::vector<std::string> & filelist,
  234. NICE::MultiChannelImage3DT<double> & imgData )
  235. {
  236. bool isInit = false;
  237. for ( int it = 0; it < ( int ) filelist.size(); it++ )
  238. {
  239. if ( imagetype == IMAGETYPE_RGB )
  240. {
  241. NICE::ColorImage img;
  242. try
  243. {
  244. img.read ( filelist[it] );
  245. }
  246. catch ( ImageException iE )
  247. {
  248. fprintf ( stderr, "Failed to open color image file: %s\n", filelist[it].c_str() );
  249. fprintf ( stderr, "%s\n", iE.what() );
  250. exit ( -1 );
  251. }
  252. if ( !isInit )
  253. {
  254. imgData.reInit ( img.width(),img.height(),filelist.size(),3 );
  255. isInit = true;
  256. }
  257. for ( int y = 0; y < img.height(); y++ )
  258. {
  259. for ( int x = 0; x < img.width(); x++ )
  260. {
  261. for ( int r = 0; r < 3; r++ )
  262. {
  263. imgData.set ( x, y, it, img.getPixel ( x,y,r ), r );
  264. }
  265. }
  266. }
  267. }
  268. else
  269. {
  270. NICE::Image img;
  271. try
  272. {
  273. img.read ( filelist[it] );
  274. }
  275. catch ( ImageException iE )
  276. {
  277. fprintf ( stderr, "Failed to open 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(),1 );
  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. imgData.set ( x, y, it, img.getPixel ( x,y ), 0 );
  291. }
  292. }
  293. }
  294. }
  295. if ( imagetype == IMAGETYPE_GRAY )
  296. {
  297. imgData.equalizeHistogram( 0 );
  298. #ifdef DEBUG_PRINTS
  299. for (int z = 0; z < imgData.depth(); z++)
  300. {
  301. NICE::Image im = imgData.getChannel( z, 0);
  302. im.write( filelist[z]+"_eq.pgm");
  303. }
  304. #endif
  305. }
  306. }
  307. void SemanticSegmentation::getProbabilityMap ( const NICE::MultiChannelImage3DT<double> & prob )
  308. {
  309. std::string s;
  310. for ( int cl = 0; cl < prob.channels(); cl++ )
  311. for ( int z = 0; z < prob.depth(); z++ )
  312. {
  313. NICE::ColorImage img( prob.width(),prob.height() );
  314. NICE::ImageT<double> m = prob.getChannelT(z, cl);
  315. imageToPseudoColor(m, img);
  316. std::stringstream out;
  317. out << "probmap_s" << z << "_c" << cl << ".ppm";
  318. s = out.str();
  319. img.write( s );
  320. //showImage(img, "Probability map");
  321. //getchar();
  322. }
  323. }
  324. ///////////////////// INTERFACE PERSISTENT /////////////////////
  325. // interface specific methods for store and restore
  326. ///////////////////// INTERFACE PERSISTENT /////////////////////
  327. void SemanticSegmentation::restore ( std::istream & is, int format )
  328. {
  329. //delete everything we knew so far...
  330. this->clear();
  331. bool b_restoreVerbose ( false );
  332. #ifdef B_RESTOREVERBOSE
  333. b_restoreVerbose = true;
  334. #endif
  335. if ( is.good() )
  336. {
  337. if ( b_restoreVerbose )
  338. std::cerr << " restore SemanticSegmentation" << std::endl;
  339. std::string tmp;
  340. is >> tmp; //class name
  341. if ( ! this->isStartTag( tmp, "SemanticSegmentation" ) )
  342. {
  343. std::cerr << " WARNING - attempt to restore SemanticSegmentation, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  344. throw;
  345. }
  346. is.precision (numeric_limits<double>::digits10 + 1);
  347. bool b_endOfBlock ( false ) ;
  348. while ( !b_endOfBlock )
  349. {
  350. is >> tmp; // start of block
  351. if ( this->isEndTag( tmp, "SemanticSegmentation" ) )
  352. {
  353. b_endOfBlock = true;
  354. continue;
  355. }
  356. tmp = this->removeStartTag ( tmp );
  357. if ( b_restoreVerbose )
  358. std::cerr << " currently restore section " << tmp << " in SemanticSegmentation" << std::endl;
  359. if ( tmp.compare("classNames") == 0 )
  360. {
  361. //dirty solution to circumvent the const-flag
  362. const_cast<ClassNames*>(this->classNames)->restore ( is, format );
  363. is >> tmp; // end of block
  364. tmp = this->removeEndTag ( tmp );
  365. }
  366. else if ( tmp.compare("imagetype") == 0 )
  367. {
  368. unsigned int ui_imagetyp;
  369. is >> ui_imagetyp;
  370. this->imagetype = static_cast<IMAGETYP> ( ui_imagetyp );
  371. is >> tmp; // end of block
  372. tmp = this->removeEndTag ( tmp );
  373. }
  374. else if ( tmp.compare("iterationCountSuffix") == 0 )
  375. {
  376. is >> this->iterationCountSuffix;
  377. is >> tmp; // end of block
  378. tmp = this->removeEndTag ( tmp );
  379. }
  380. else
  381. {
  382. std::cerr << "WARNING -- unexpected SemanticSegmentation object -- " << tmp << " -- for restoration... aborting" << std::endl;
  383. throw;
  384. }
  385. }
  386. }
  387. else
  388. {
  389. std::cerr << "SemanticSegmentation::restore -- InStream not initialized - restoring not possible!" << std::endl;
  390. throw;
  391. }
  392. //TODO check whether we also have to do something linke Preprocess::Init ( conf );
  393. }
  394. void SemanticSegmentation::store ( std::ostream & os, int format ) const
  395. {
  396. if (os.good())
  397. {
  398. // show starting point
  399. os << this->createStartTag( "SemanticSegmentation" ) << std::endl;
  400. os.precision (numeric_limits<double>::digits10 + 1);
  401. os << this->createStartTag( "classNames" ) << std::endl;
  402. this->classNames->store ( os, format );
  403. os << this->createEndTag( "classNames" ) << std::endl;
  404. //
  405. os << this->createStartTag( "imagetype" ) << std::endl;
  406. os << imagetype << std::endl;
  407. os << this->createEndTag( "imagetype" ) << std::endl;
  408. //
  409. os << this->createStartTag( "iterationCountSuffix" ) << std::endl;
  410. os << iterationCountSuffix << std::endl;
  411. os << this->createEndTag( "iterationCountSuffix" ) << std::endl;
  412. // done
  413. os << this->createEndTag( "SemanticSegmentation" ) << std::endl;
  414. }
  415. else
  416. {
  417. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  418. }
  419. }
  420. void SemanticSegmentation::clear ()
  421. {
  422. //TODO
  423. }