SemSegContextTree.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. #include "SemSegContextTree.h"
  2. #include "vislearning/baselib/Globals.h"
  3. #include "vislearning/baselib/ProgressBar.h"
  4. #include "core/basics/StringTools.h"
  5. #include "vislearning/cbaselib/CachedExample.h"
  6. #include "vislearning/cbaselib/PascalResults.h"
  7. #include "vislearning/baselib/ColorSpace.h"
  8. #include "objrec/segmentation/RSMeanShift.h"
  9. #include "objrec/segmentation/RSGraphBased.h"
  10. #include "core/basics/numerictools.h"
  11. #include "core/basics/StringTools.h"
  12. #include "core/basics/FileName.h"
  13. #include "vislearning/baselib/ICETools.h"
  14. #include "core/basics/Timer.h"
  15. #include "core/basics/vectorio.h"
  16. #include "core/image/FilterT.h"
  17. #include <omp.h>
  18. #include <iostream>
  19. #undef LOCALFEATS
  20. #undef WRITEGLOB
  21. #undef TEXTONMAP
  22. //#define LOCALFEATS
  23. using namespace OBJREC;
  24. using namespace std;
  25. using namespace NICE;
  26. SemSegContextTree::SemSegContextTree ( const Config *conf, const MultiDataset *md )
  27. : SemanticSegmentation ( conf, & ( md->getClassNames ( "train" ) ) )
  28. {
  29. this->conf = conf;
  30. string section = "SSContextTree";
  31. lfcw = new LFColorWeijer ( conf );
  32. grid = conf->gI ( section, "grid", 10 );
  33. maxSamples = conf->gI ( section, "max_samples", 2000 );
  34. minFeats = conf->gI ( section, "min_feats", 50 );
  35. maxDepth = conf->gI ( section, "max_depth", 10 );
  36. windowSize = conf->gI ( section, "window_size", 16 );
  37. featsPerSplit = conf->gI ( section, "feats_per_split", 200 );
  38. useShannonEntropy = conf->gB ( section, "use_shannon_entropy", true );
  39. nbTrees = conf->gI ( section, "amount_trees", 1 );
  40. string segmentationtype = conf->gS ( section, "segmentation_type", "meanshift" );
  41. randomTests = conf->gI ( section, "random_tests", 10 );
  42. bool saveLoadData = conf->gB ( "debug", "save_load_data", false );
  43. string fileLocation = conf->gS ( "debug", "datafile", "tmp.txt" );
  44. pixelWiseLabeling = false;
  45. if ( segmentationtype == "meanshift" )
  46. segmentation = new RSMeanShift ( conf );
  47. else if ( segmentationtype == "none" )
  48. {
  49. segmentation = NULL;
  50. pixelWiseLabeling = true;
  51. }
  52. else if ( segmentationtype == "felzenszwalb" )
  53. segmentation = new RSGraphBased ( conf );
  54. else
  55. throw ( "no valid segmenation_type\n please choose between none, meanshift and felzenszwalb\n" );
  56. ftypes = conf->gI ( section, "features", 100 );;
  57. string featsec = "Features";
  58. if ( conf->gB ( featsec, "minus", true ) )
  59. ops.push_back ( new Minus() );
  60. if ( conf->gB ( featsec, "minus_abs", true ) )
  61. ops.push_back ( new MinusAbs() );
  62. if ( conf->gB ( featsec, "addition", true ) )
  63. ops.push_back ( new Addition() );
  64. if ( conf->gB ( featsec, "only1", true ) )
  65. ops.push_back ( new Only1() );
  66. if ( conf->gB ( featsec, "rel_x", true ) )
  67. ops.push_back ( new RelativeXPosition() );
  68. if ( conf->gB ( featsec, "rel_y", true ) )
  69. ops.push_back ( new RelativeYPosition() );
  70. if ( conf->gB ( featsec, "bi_int_cent", true ) )
  71. cops.push_back ( new BiIntegralCenteredOps() );
  72. if ( conf->gB ( featsec, "int_cent", true ) )
  73. cops.push_back ( new IntegralCenteredOps() );
  74. if ( conf->gB ( featsec, "int", true ) )
  75. cops.push_back ( new IntegralOps() );
  76. if ( conf->gB ( featsec, "haar_horz", true ) )
  77. cops.push_back ( new HaarHorizontal() );
  78. if ( conf->gB ( featsec, "haar_vert", true ) )
  79. cops.push_back ( new HaarVertical() );
  80. if ( conf->gB ( featsec, "haar_diag", true ) )
  81. cops.push_back ( new HaarDiag() );
  82. if ( conf->gB ( featsec, "haar3_horz", true ) )
  83. cops.push_back ( new Haar3Horiz() );
  84. if ( conf->gB ( featsec, "haar3_vert", true ) )
  85. cops.push_back ( new Haar3Vert() );
  86. if ( conf->gB ( featsec, "glob", true ) )
  87. cops.push_back ( new GlobalFeats() );
  88. useGradient = conf->gB ( featsec, "use_gradient", true );
  89. useRegionFeature = conf->gB ( featsec, "use_region", true );
  90. // geometric features of hoiem
  91. useHoiemFeatures = conf->gB( featsec, "use_hoiem_features", false );
  92. if ( useHoiemFeatures )
  93. {
  94. hoiemDirectory = conf->gS( featsec, "hoiem_directory" );
  95. }
  96. opOverview = vector<int> ( NBOPERATIONS, 0 );
  97. contextOverview = vector<vector<double> > ( maxDepth, vector<double> ( 2, 0.0 ) );
  98. calcVal.push_back ( new MCImageAccess() );
  99. calcVal.push_back ( new ClassificationResultAccess() );
  100. classnames = md->getClassNames ( "train" );
  101. ///////////////////////////////////
  102. // Train Segmentation Context Trees
  103. ///////////////////////////////////
  104. if ( saveLoadData )
  105. {
  106. if ( FileMgt::fileExists ( fileLocation ) )
  107. read ( fileLocation );
  108. else
  109. {
  110. train ( md );
  111. write ( fileLocation );
  112. }
  113. }
  114. else
  115. {
  116. train ( md );
  117. }
  118. }
  119. SemSegContextTree::~SemSegContextTree()
  120. {
  121. }
  122. double SemSegContextTree::getBestSplit ( std::vector<NICE::MultiChannelImageT<double> > &feats, std::vector<NICE::MultiChannelImageT<unsigned short int> > &currentfeats, std::vector<NICE::MultiChannelImageT<double> > &integralImgs, const std::vector<NICE::MatrixT<int> > &labels, int node, Operation *&splitop, double &splitval, const int &tree )
  123. {
  124. Timer t;
  125. t.start();
  126. int imgCount = 0, featdim = 0;
  127. try
  128. {
  129. imgCount = (int)feats.size();
  130. }
  131. catch ( Exception )
  132. {
  133. cerr << "no features computed?" << endl;
  134. }
  135. double bestig = -numeric_limits< double >::max();
  136. splitop = NULL;
  137. splitval = -1.0;
  138. set<vector<int> >selFeats;
  139. map<int, int> e;
  140. int featcounter = forest[tree][node].featcounter;
  141. if ( featcounter < minFeats )
  142. {
  143. //cout << "only " << featcounter << " feats in current node -> it's a leaf" << endl;
  144. return 0.0;
  145. }
  146. vector<double> fraction ( a.size(), 0.0 );
  147. for ( uint i = 0; i < fraction.size(); i++ )
  148. {
  149. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  150. fraction[i] = 0;
  151. else
  152. fraction[i] = ( (double)maxSamples ) / ( (double)featcounter * a[i] * a.size() );
  153. }
  154. featcounter = 0;
  155. for ( int iCounter = 0; iCounter < imgCount; iCounter++ )
  156. {
  157. int xsize = (int)currentfeats[iCounter].width();
  158. int ysize = (int)currentfeats[iCounter].height();
  159. for ( int x = 0; x < xsize; x++ )
  160. {
  161. for ( int y = 0; y < ysize; y++ )
  162. {
  163. if ( currentfeats[iCounter].get ( x, y, tree ) == node )
  164. {
  165. int cn = labels[iCounter] ( x, y );
  166. double randD = (double)rand() / (double)RAND_MAX;
  167. if ( labelmap.find ( cn ) == labelmap.end() )
  168. continue;
  169. if ( randD < fraction[labelmap[cn]] )
  170. {
  171. vector<int> tmp ( 3, 0 );
  172. tmp[0] = iCounter;
  173. tmp[1] = x;
  174. tmp[2] = y;
  175. featcounter++;
  176. selFeats.insert ( tmp );
  177. e[cn]++;
  178. }
  179. }
  180. }
  181. }
  182. }
  183. map<int, int>::iterator mapit;
  184. double globent = 0.0;
  185. for ( mapit = e.begin() ; mapit != e.end(); mapit++ )
  186. {
  187. double p = (double)( *mapit ).second / (double)featcounter;
  188. globent += p * log2 ( p );
  189. }
  190. globent = -globent;
  191. if ( globent < 0.5 )
  192. {
  193. return 0.0;
  194. }
  195. featsel.clear();
  196. for ( int i = 0; i < featsPerSplit; i++ )
  197. {
  198. int x1, x2, y1, y2;
  199. int ft = (int)( (double)rand() / (double)RAND_MAX * (double)ftypes );
  200. int tmpws = windowSize;
  201. if ( integralImgs[0].width() == 0 )
  202. ft = 0;
  203. if ( ft > 0 )
  204. {
  205. tmpws *= 4;
  206. }
  207. x1 = (int)( (double)rand() / (double)RAND_MAX * (double)tmpws ) - tmpws / 2;
  208. x2 = (int)( (double)rand() / (double)RAND_MAX * (double)tmpws ) - tmpws / 2;
  209. y1 = (int)( (double)rand() / (double)RAND_MAX * (double)tmpws ) - tmpws / 2;
  210. y2 = (int)( (double)rand() / (double)RAND_MAX * (double)tmpws ) - tmpws / 2;
  211. if ( ft == 0 )
  212. {
  213. int f1 = (int)( (double)rand() / (double)RAND_MAX * (double)featdim );
  214. int f2 = (int)( (double)rand() / (double)RAND_MAX * (double)featdim );
  215. int o = (int)( (double)rand() / (double)RAND_MAX * (double)ops.size() );
  216. Operation *op = ops[o]->clone();
  217. op->set ( x1, y1, x2, y2, f1, f2, calcVal[ft] );
  218. op->setContext ( false );
  219. featsel.push_back ( op );
  220. }
  221. else if ( ft == 1 )
  222. {
  223. int opssize = (int)ops.size();
  224. //opssize = 0;
  225. int o = (int)( (double)rand() / (double)RAND_MAX * ( ( (double)cops.size() ) + (double)opssize ) );
  226. Operation *op;
  227. if ( o < opssize )
  228. {
  229. int chans = (int)forest[0][0].dist.size();
  230. int f1 = (int)( (double)rand() / (double)RAND_MAX * (double)chans );
  231. int f2 = (int)( (double)rand() / (double)RAND_MAX * (double)chans );
  232. op = ops[o]->clone();
  233. op->set ( x1, y1, x2, y2, f1, f2, calcVal[ft] );
  234. op->setContext ( true );
  235. }
  236. else
  237. {
  238. int chans = integralImgs[0].channels();
  239. int f1 = (int)( (double)rand() / (double)RAND_MAX * (double)chans );
  240. int f2 = (int)( (double)rand() / (double)RAND_MAX * (double)chans );
  241. o -= opssize;
  242. op = cops[o]->clone();
  243. op->set ( x1, y1, x2, y2, f1, f2, calcVal[ft] );
  244. if ( f1 < (int)forest[0][0].dist.size() )
  245. op->setContext ( true );
  246. else
  247. op->setContext ( false );
  248. }
  249. featsel.push_back ( op );
  250. }
  251. }
  252. #pragma omp parallel for private(mapit)
  253. for ( int f = 0; f < featsPerSplit; f++ )
  254. {
  255. double l_bestig = -numeric_limits< double >::max();
  256. double l_splitval = -1.0;
  257. set<vector<int> >::iterator it;
  258. vector<double> vals;
  259. double maxval = -numeric_limits<double>::max();
  260. double minval = numeric_limits<double>::max();
  261. for ( it = selFeats.begin() ; it != selFeats.end(); it++ )
  262. {
  263. Features feat;
  264. feat.feats = &feats[ ( *it ) [0]];
  265. feat.cfeats = &currentfeats[ ( *it ) [0]];
  266. feat.cTree = tree;
  267. feat.tree = &forest[tree];
  268. feat.integralImg = &integralImgs[ ( *it ) [0]];
  269. double val = featsel[f]->getVal ( feat, ( *it ) [1], ( *it ) [2] );
  270. vals.push_back ( val );
  271. maxval = std::max ( val, maxval );
  272. minval = std::min ( val, minval );
  273. }
  274. if ( minval == maxval )
  275. continue;
  276. double scale = maxval - minval;
  277. vector<double> splits;
  278. for ( int r = 0; r < randomTests; r++ )
  279. {
  280. splits.push_back ( ( (double)rand() / (double)RAND_MAX*scale ) + minval );
  281. }
  282. for ( int run = 0 ; run < randomTests; run++ )
  283. {
  284. set<vector<int> >::iterator it2;
  285. double val = splits[run];
  286. map<int, int> eL, eR;
  287. int counterL = 0, counterR = 0;
  288. int counter2 = 0;
  289. for ( it2 = selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  290. {
  291. int cn = labels[ ( *it2 ) [0]] ( ( *it2 ) [1], ( *it2 ) [2] );
  292. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  293. if ( vals[counter2] < val )
  294. {
  295. //left entropie:
  296. eL[cn] = eL[cn] + 1;
  297. counterL++;
  298. }
  299. else
  300. {
  301. //right entropie:
  302. eR[cn] = eR[cn] + 1;
  303. counterR++;
  304. }
  305. }
  306. double leftent = 0.0;
  307. for ( mapit = eL.begin() ; mapit != eL.end(); mapit++ )
  308. {
  309. double p = (double)( *mapit ).second / (double)counterL;
  310. leftent -= p * log2 ( p );
  311. }
  312. double rightent = 0.0;
  313. for ( mapit = eR.begin() ; mapit != eR.end(); mapit++ )
  314. {
  315. double p = (double)( *mapit ).second / (double)counterR;
  316. rightent -= p * log2 ( p );
  317. }
  318. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  319. double pl = (double)counterL / (double)( counterL + counterR );
  320. double ig = globent - ( 1.0 - pl ) * rightent - pl * leftent;
  321. //double ig = globent - rightent - leftent;
  322. if ( useShannonEntropy )
  323. {
  324. double esplit = - ( pl * log ( pl ) + ( 1 - pl ) * log ( 1 - pl ) );
  325. ig = 2 * ig / ( globent + esplit );
  326. }
  327. if ( ig > l_bestig )
  328. {
  329. l_bestig = ig;
  330. l_splitval = val;
  331. }
  332. }
  333. #pragma omp critical
  334. {
  335. //cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  336. //cout << "globent: " << globent << " l_bestig " << l_bestig << " f: " << p << " l_splitval: " << l_splitval << endl;
  337. //cout << "p: " << featsubset[f] << endl;
  338. if ( l_bestig > bestig )
  339. {
  340. bestig = l_bestig;
  341. splitop = featsel[f];
  342. splitval = l_splitval;
  343. }
  344. }
  345. }
  346. //getchar();
  347. //splitop->writeInfos();
  348. //cout<< "ig: " << bestig << endl;
  349. //FIXME: delete all features!
  350. /*for(int i = 0; i < featsPerSplit; i++)
  351. {
  352. if(featsel[i] != splitop)
  353. delete featsel[i];
  354. }*/
  355. #ifdef debug
  356. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  357. #endif
  358. return bestig;
  359. }
  360. inline double SemSegContextTree::getMeanProb ( const int &x, const int &y, const int &channel, const MultiChannelImageT<unsigned short int> &currentfeats )
  361. {
  362. double val = 0.0;
  363. for ( int tree = 0; tree < nbTrees; tree++ )
  364. {
  365. val += forest[tree][currentfeats.get ( x,y,tree ) ].dist[channel];
  366. }
  367. return val / (double)nbTrees;
  368. }
  369. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<SparseVectorInt> &infeats, NICE::MultiChannelImageT<SparseVectorInt> &integralImage )
  370. {
  371. int xsize = infeats.width();
  372. int ysize = infeats.height();
  373. integralImage ( 0, 0 ).add ( infeats.get ( 0, 0 ) );
  374. //first column
  375. for ( int y = 1; y < ysize; y++ )
  376. {
  377. integralImage ( 0, y ).add ( infeats.get ( 0, y ) );
  378. integralImage ( 0, y ).add ( integralImage ( 0, y - 1 ) );
  379. }
  380. //first row
  381. for ( int x = 1; x < xsize; x++ )
  382. {
  383. integralImage ( x, 0 ).add ( infeats.get ( x, 0 ) );
  384. integralImage ( x, 0 ).add ( integralImage ( x - 1, 0 ) );
  385. }
  386. //rest
  387. for ( int y = 1; y < ysize; y++ )
  388. {
  389. for ( int x = 1; x < xsize; x++ )
  390. {
  391. integralImage ( x, y ).add ( infeats.get ( x, y ) );
  392. integralImage ( x, y ).add ( integralImage ( x, y - 1 ) );
  393. integralImage ( x, y ).add ( integralImage ( x - 1, y ) );
  394. integralImage ( x, y ).sub ( integralImage ( x - 1, y - 1 ) );
  395. }
  396. }
  397. }
  398. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<unsigned short int> &currentfeats, const NICE::MultiChannelImageT<double> &lfeats, NICE::MultiChannelImageT<double> &integralImage )
  399. {
  400. int xsize = currentfeats.width();
  401. int ysize = currentfeats.height();
  402. int channels = (int)forest[0][0].dist.size();
  403. #pragma omp parallel for
  404. for ( int c = 0; c < channels; c++ )
  405. {
  406. integralImage.set ( 0, 0, getMeanProb ( 0, 0, c, currentfeats ), c );
  407. //first column
  408. for ( int y = 1; y < ysize; y++ )
  409. {
  410. integralImage.set ( 0, y, getMeanProb ( 0, y, c, currentfeats ) + integralImage.get ( 0, y - 1, c ), c );
  411. }
  412. //first row
  413. for ( int x = 1; x < xsize; x++ )
  414. {
  415. integralImage.set ( x, 0, getMeanProb ( x, 0, c, currentfeats ) + integralImage.get ( x - 1, 0, c ), c );
  416. }
  417. //rest
  418. for ( int y = 1; y < ysize; y++ )
  419. {
  420. for ( int x = 1; x < xsize; x++ )
  421. {
  422. double val = getMeanProb ( x, y, c, currentfeats ) + integralImage.get ( x, y - 1, c ) + integralImage.get ( x - 1, y, c ) - integralImage.get ( x - 1, y - 1, c );
  423. integralImage.set ( x, y, val, c );
  424. }
  425. }
  426. }
  427. int channels2 = (int)lfeats.channels();
  428. xsize = lfeats.width();
  429. ysize = lfeats.height();
  430. if ( integralImage.get ( xsize - 1, ysize - 1, channels ) == 0.0 )
  431. {
  432. #pragma omp parallel for
  433. for ( int c1 = 0; c1 < channels2; c1++ )
  434. {
  435. int c = channels + c1;
  436. integralImage.set ( 0, 0, lfeats.get ( 0, 0, c1 ), c );
  437. //first column
  438. for ( int y = 1; y < ysize; y++ )
  439. {
  440. integralImage.set ( 0, y, lfeats.get ( 0, y, c1 ) + integralImage.get ( 0, y, c ), c );
  441. }
  442. //first row
  443. for ( int x = 1; x < xsize; x++ )
  444. {
  445. integralImage.set ( x, 0, lfeats.get ( x, 0, c1 ) + integralImage.get ( x, 0, c ), c );
  446. }
  447. //rest
  448. for ( int y = 1; y < ysize; y++ )
  449. {
  450. for ( int x = 1; x < xsize; x++ )
  451. {
  452. double val = lfeats.get ( x, y, c1 ) + integralImage.get ( x, y - 1, c ) + integralImage.get ( x - 1, y, c ) - integralImage.get ( x - 1, y - 1, c );
  453. integralImage.set ( x, y, val, c );
  454. }
  455. }
  456. }
  457. }
  458. }
  459. inline double computeWeight ( const double &d, const double &dim )
  460. {
  461. return 1.0 / ( pow ( 2, (double)( dim - d + 1 ) ) );
  462. }
  463. void SemSegContextTree::train ( const MultiDataset *md )
  464. {
  465. const LabeledSet train = * ( *md ) ["train"];
  466. const LabeledSet *trainp = &train;
  467. ProgressBar pb ( "compute feats" );
  468. pb.show();
  469. //TODO: Speichefresser!, lohnt sich sparse?
  470. vector<MultiChannelImageT<double> > allfeats;
  471. vector<MultiChannelImageT<unsigned short int> > currentfeats;
  472. vector<MatrixT<int> > labels;
  473. #ifdef TEXTONMAP
  474. vector<MultiChannelImageT<SparseVectorInt> > textonMap;
  475. #endif
  476. vector<MultiChannelImageT<SparseVectorInt> > integralTexton;
  477. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  478. if ( forbidden_classes_s == "" )
  479. {
  480. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  481. }
  482. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  483. int imgcounter = 0;
  484. int amountPixels = 0;
  485. LOOP_ALL_S ( *trainp )
  486. {
  487. EACH_INFO ( classno, info );
  488. NICE::ColorImage img;
  489. std::string currentFile = info.img();
  490. CachedExample *ce = new CachedExample ( currentFile );
  491. const LocalizationResult *locResult = info.localization();
  492. if ( locResult->size() <= 0 )
  493. {
  494. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  495. currentFile.c_str() );
  496. continue;
  497. }
  498. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  499. int xsize, ysize;
  500. ce->getImageSize ( xsize, ysize );
  501. amountPixels += xsize * ysize;
  502. MatrixT<int> tmpMat ( xsize, ysize );
  503. currentfeats.push_back ( MultiChannelImageT<unsigned short int> ( xsize, ysize, nbTrees ) );
  504. currentfeats[imgcounter].setAll ( 0 );
  505. #ifdef TEXTONMAP
  506. textonMap.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  507. integralTexton.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  508. #endif
  509. labels.push_back ( tmpMat );
  510. try {
  511. img = ColorImage ( currentFile );
  512. } catch ( Exception ) {
  513. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  514. continue;
  515. }
  516. Globals::setCurrentImgFN ( currentFile );
  517. //TODO: resize image?!
  518. MultiChannelImageT<double> feats;
  519. allfeats.push_back ( feats );
  520. // read image and do some simple transformations
  521. extractBasicFeatures (allfeats[imgcounter], img, currentFile);
  522. // getting groundtruth
  523. NICE::Image pixelLabels ( xsize, ysize );
  524. pixelLabels.set ( 0 );
  525. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  526. for ( int x = 0; x < xsize; x++ )
  527. {
  528. for ( int y = 0; y < ysize; y++ )
  529. {
  530. classno = pixelLabels.getPixel ( x, y );
  531. labels[imgcounter] ( x, y ) = classno;
  532. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  533. continue;
  534. labelcounter[classno]++;
  535. }
  536. }
  537. imgcounter++;
  538. pb.update ( trainp->count() );
  539. delete ce;
  540. }
  541. pb.hide();
  542. map<int, int>::iterator mapit;
  543. int classes = 0;
  544. for ( mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++ )
  545. {
  546. labelmap[mapit->first] = classes;
  547. labelmapback[classes] = mapit->first;
  548. classes++;
  549. }
  550. ////////////////////////////////////////////////////
  551. //define which featurextraction methods should be used for each channel
  552. #ifdef LOCALFEATS
  553. int colorchannels = 9;
  554. #else
  555. int colorchannels = 3;
  556. #endif
  557. if(useGradient)
  558. colorchannels *= 2;
  559. // gray value images
  560. for(int i = 0; i < colorchannels; i++)
  561. {
  562. channelType.push_back(0);
  563. }
  564. // regions
  565. if(useRegionFeature)
  566. channelType.push_back(2);
  567. // integral images
  568. for(int i = 0; i < colorchannels+classes; i++)
  569. {
  570. channelType.push_back(1);
  571. }
  572. int amountTypes = 3;
  573. channelsPerType = vector<vector<int> >(amountTypes, vector<int>());
  574. for(int i = 0; i < channelType.size(); i++)
  575. {
  576. channelsPerType[channelType[i]].push_back(i);
  577. }
  578. ftypes = std::min(amountTypes,ftypes);
  579. ////////////////////////////////////////////////////
  580. //balancing
  581. int featcounter = 0;
  582. a = vector<double> ( classes, 0.0 );
  583. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  584. {
  585. int xsize = (int)currentfeats[iCounter].width();
  586. int ysize = (int)currentfeats[iCounter].height();
  587. for ( int x = 0; x < xsize; x++ )
  588. {
  589. for ( int y = 0; y < ysize; y++ )
  590. {
  591. featcounter++;
  592. int cn = labels[iCounter] ( x, y );
  593. if ( labelmap.find ( cn ) == labelmap.end() )
  594. continue;
  595. a[labelmap[cn]] ++;
  596. }
  597. }
  598. }
  599. for ( int i = 0; i < (int)a.size(); i++ )
  600. {
  601. a[i] /= (double)featcounter;
  602. }
  603. #ifdef DEBUG
  604. for ( int i = 0; i < (int)a.size(); i++ )
  605. {
  606. cout << "a[" << i << "]: " << a[i] << endl;
  607. }
  608. cout << "a.size: " << a.size() << endl;
  609. #endif
  610. depth = 0;
  611. int uniquenumber = 0;
  612. for ( int t = 0; t < nbTrees; t++ )
  613. {
  614. vector<TreeNode> tree;
  615. tree.push_back ( TreeNode() );
  616. tree[0].dist = vector<double> ( classes, 0.0 );
  617. tree[0].depth = depth;
  618. tree[0].featcounter = amountPixels;
  619. tree[0].nodeNumber = uniquenumber;
  620. uniquenumber++;
  621. forest.push_back ( tree );
  622. }
  623. vector<int> startnode ( nbTrees, 0 );
  624. bool allleaf = false;
  625. //int baseFeatSize = allfeats[0].size();
  626. vector<MultiChannelImageT<double> > integralImgs ( imgcounter, MultiChannelImageT<double>() );
  627. while ( !allleaf && depth < maxDepth )
  628. {
  629. depth++;
  630. #ifdef DEBUG
  631. cout << "depth: " << depth << endl;
  632. #endif
  633. allleaf = true;
  634. vector<MultiChannelImageT<unsigned short int> > lastfeats = currentfeats;
  635. #if 1
  636. Timer timer;
  637. timer.start();
  638. #endif
  639. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  640. if ( depth == 1 )
  641. {
  642. weight = computeWeight ( 1, maxDepth );
  643. }
  644. for ( int tree = 0; tree < nbTrees; tree++ )
  645. {
  646. int t = (int)forest[tree].size();
  647. int s = startnode[tree];
  648. startnode[tree] = t;
  649. //TODO vielleicht parallel wenn nächste schleife trotzdem noch parallelsiert würde, die hat mehr gewicht
  650. //#pragma omp parallel for
  651. for ( int i = s; i < t; i++ )
  652. {
  653. if ( !forest[tree][i].isleaf && forest[tree][i].left < 0 )
  654. {
  655. #if 0
  656. timer.stop();
  657. cout << "time 1: " << timer.getLast() << endl;
  658. timer.start();
  659. #endif
  660. Operation *splitfeat = NULL;
  661. double splitval;
  662. double bestig = getBestSplit ( allfeats, lastfeats, integralImgs, labels, i, splitfeat, splitval, tree );
  663. for ( int ii = 0; ii < lastfeats.size(); ii++ )
  664. {
  665. for ( int c = 0; c < lastfeats[ii].channels(); c++ )
  666. {
  667. short unsigned int minv, maxv;
  668. lastfeats[ii].statistics ( minv, maxv, c );
  669. //cout << "min: " << minv << " max: " << maxv << endl;
  670. }
  671. }
  672. #if 0
  673. timer.stop();
  674. double tl = timer.getLast();
  675. if ( tl > 10.0 )
  676. {
  677. cout << "time 2: " << tl << endl;
  678. cout << "slow split: " << splitfeat->writeInfos() << endl;
  679. getchar();
  680. }
  681. timer.start();
  682. #endif
  683. forest[tree][i].feat = splitfeat;
  684. forest[tree][i].decision = splitval;
  685. if ( splitfeat != NULL )
  686. {
  687. allleaf = false;
  688. int left = forest[tree].size();
  689. forest[tree].push_back ( TreeNode() );
  690. forest[tree].push_back ( TreeNode() );
  691. int right = left + 1;
  692. forest[tree][i].left = left;
  693. forest[tree][i].right = right;
  694. forest[tree][left].dist = vector<double> ( classes, 0.0 );
  695. forest[tree][right].dist = vector<double> ( classes, 0.0 );
  696. forest[tree][left].depth = depth;
  697. forest[tree][right].depth = depth;
  698. forest[tree][left].featcounter = 0;
  699. forest[tree][right].featcounter = 0;
  700. forest[tree][left].nodeNumber = uniquenumber;
  701. int leftu = uniquenumber;
  702. uniquenumber++;
  703. forest[tree][right].nodeNumber = uniquenumber;
  704. int rightu = uniquenumber;
  705. uniquenumber++;
  706. forest[tree][right].featcounter = 0;
  707. #if 0
  708. timer.stop();
  709. cout << "time 3: " << timer.getLast() << endl;
  710. timer.start();
  711. #endif
  712. #pragma omp parallel for
  713. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  714. {
  715. int xsize = currentfeats[iCounter].width();
  716. int ysize = currentfeats[iCounter].height();
  717. for ( int x = 0; x < xsize; x++ )
  718. {
  719. for ( int y = 0; y < ysize; y++ )
  720. {
  721. if ( currentfeats[iCounter].get ( x, y, tree ) == i )
  722. {
  723. Features feat;
  724. feat.feats = &allfeats[iCounter];
  725. feat.cfeats = &lastfeats[iCounter];
  726. feat.cTree = tree;
  727. feat.tree = &forest[tree];
  728. feat.integralImg = &integralImgs[iCounter];
  729. double val = splitfeat->getVal ( feat, x, y );
  730. int subx = x / grid;
  731. int suby = y / grid;
  732. #pragma omp critical
  733. if ( val < splitval )
  734. {
  735. currentfeats[iCounter].set ( x, y, left, tree );
  736. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  737. forest[tree][left].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  738. forest[tree][left].featcounter++;
  739. SparseVectorInt v;
  740. v.insert ( pair<int, double> ( leftu, weight ) );
  741. #ifdef TEXTONMAP
  742. textonMap[iCounter] ( subx, suby ).add ( v );
  743. #endif
  744. }
  745. else
  746. {
  747. currentfeats[iCounter].set ( x, y, right, tree );
  748. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  749. forest[tree][right].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  750. forest[tree][right].featcounter++;
  751. //feld im subsampled finden und in diesem rechts hochzählen
  752. SparseVectorInt v;
  753. v.insert ( pair<int, double> ( rightu, weight ) );
  754. #ifdef TEXTONMAP
  755. textonMap[iCounter] ( subx, suby ).add ( v );
  756. #endif
  757. }
  758. }
  759. }
  760. }
  761. }
  762. #if 0
  763. timer.stop();
  764. cout << "time 4: " << timer.getLast() << endl;
  765. timer.start();
  766. #endif
  767. // forest[tree][right].featcounter = forest[tree][i].featcounter - forest[tree][left].featcounter;
  768. double lcounter = 0.0, rcounter = 0.0;
  769. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  770. {
  771. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  772. {
  773. forest[tree][left].dist[d] = 0;
  774. forest[tree][right].dist[d] = 0;
  775. }
  776. else
  777. {
  778. forest[tree][left].dist[d] /= a[d];
  779. lcounter += forest[tree][left].dist[d];
  780. forest[tree][right].dist[d] /= a[d];
  781. rcounter += forest[tree][right].dist[d];
  782. }
  783. }
  784. #if 0
  785. timer.stop();
  786. cout << "time 5: " << timer.getLast() << endl;
  787. timer.start();
  788. #endif
  789. if ( lcounter <= 0 || rcounter <= 0 )
  790. {
  791. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  792. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  793. cout << "bestig: " << bestig << endl;
  794. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  795. {
  796. int xsize = currentfeats[iCounter].width();
  797. int ysize = currentfeats[iCounter].height();
  798. int counter = 0;
  799. for ( int x = 0; x < xsize; x++ )
  800. {
  801. for ( int y = 0; y < ysize; y++ )
  802. {
  803. if ( lastfeats[iCounter].get ( x, y, tree ) == i )
  804. {
  805. if ( ++counter > 30 )
  806. break;
  807. Features feat;
  808. feat.feats = &allfeats[iCounter];
  809. feat.cfeats = &lastfeats[iCounter];
  810. feat.cTree = tree;
  811. feat.tree = &forest[tree];
  812. feat.integralImg = &integralImgs[iCounter];
  813. double val = splitfeat->getVal ( feat, x, y );
  814. cout << "splitval: " << splitval << " val: " << val << endl;
  815. }
  816. }
  817. }
  818. }
  819. assert ( lcounter > 0 && rcounter > 0 );
  820. }
  821. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  822. {
  823. forest[tree][left].dist[d] /= lcounter;
  824. forest[tree][right].dist[d] /= rcounter;
  825. }
  826. }
  827. else
  828. {
  829. forest[tree][i].isleaf = true;
  830. }
  831. }
  832. }
  833. #if 0
  834. timer.stop();
  835. cout << "time after tree: " << timer.getLast() << endl;
  836. timer.start();
  837. #endif
  838. }
  839. //compute integral images
  840. int channels = classes + allfeats[0].channels();
  841. if ( integralImgs[0].width() == 0 )
  842. {
  843. for ( int i = 0; i < imgcounter; i++ )
  844. {
  845. int xsize = allfeats[i].width();
  846. int ysize = allfeats[i].height();
  847. integralImgs[i].reInit ( xsize, ysize, channels );
  848. integralImgs[i].setAll ( 0.0 );
  849. }
  850. }
  851. #if 0
  852. timer.stop();
  853. cout << "time for part1: " << timer.getLast() << endl;
  854. timer.start();
  855. #endif
  856. #pragma omp parallel for
  857. for ( int i = 0; i < imgcounter; i++ )
  858. {
  859. computeIntegralImage ( currentfeats[i], allfeats[i], integralImgs[i] );
  860. #ifdef TEXTONMAP
  861. computeIntegralImage ( textonMap[i], integralTexton[i] );
  862. #endif
  863. }
  864. #if 1
  865. timer.stop();
  866. cout << "time for depth " << depth << ": " << timer.getLast() << endl;
  867. #endif
  868. }
  869. #ifdef WRITEGLOB
  870. ofstream outstream ( "globtrain.feat" );
  871. for ( int i = 0; i < textonMap.size(); i++ )
  872. {
  873. set<int> usedclasses;
  874. for ( uint x = 0; x < labels[i].rows(); x++ )
  875. {
  876. for ( uint y = 0; y < labels[i].cols(); y++ )
  877. {
  878. int classno = labels[i] ( x, y );
  879. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  880. continue;
  881. usedclasses.insert ( classno );
  882. }
  883. }
  884. cout << "labels.cols: " << labels[i].cols() << " labels.rows " << labels[i].rows() << endl;
  885. cout << "currentfeats : " << allfeats[i].width() << " allfeats[i].height(); " << allfeats[i].height() << endl;
  886. set<int>::iterator it;
  887. for ( it = usedclasses.begin() ; it != usedclasses.end(); it++ )
  888. outstream << *it << " ";
  889. outstream << endl;
  890. integralTexton[i] ( integralTexton[i].width() - 1, integralTexton[i].height() - 1 ).store ( outstream );
  891. }
  892. outstream.close();
  893. #endif
  894. cout << "uniquenumber " << uniquenumber << endl;
  895. //getchar();
  896. #ifdef DEBUG
  897. for ( int tree = 0; tree < nbTrees; tree++ )
  898. {
  899. int t = (int)forest[tree].size();
  900. for ( int i = 0; i < t; i++ )
  901. {
  902. printf ( "tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right );
  903. if ( !forest[tree][i].isleaf && forest[tree][i].left != -1 )
  904. {
  905. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  906. opOverview[forest[tree][i].feat->getOps() ]++;
  907. contextOverview[forest[tree][i].depth][ (int)forest[tree][i].feat->getContext() ]++;
  908. }
  909. for ( int d = 0; d < (int)forest[tree][i].dist.size(); d++ )
  910. {
  911. cout << " " << forest[tree][i].dist[d];
  912. }
  913. cout << endl;
  914. }
  915. }
  916. for ( uint c = 0; c < ops.size(); c++ )
  917. {
  918. cout << ops[c]->writeInfos() << ": " << opOverview[ops[c]->getOps() ] << endl;
  919. }
  920. for ( uint c = 0; c < cops.size(); c++ )
  921. {
  922. cout << cops[c]->writeInfos() << ": " << opOverview[cops[c]->getOps() ] << endl;
  923. }
  924. for ( int d = 0; d < maxDepth; d++ )
  925. {
  926. double sum = contextOverview[d][0] + contextOverview[d][1];
  927. contextOverview[d][0] /= sum;
  928. contextOverview[d][1] /= sum;
  929. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  930. }
  931. #endif
  932. }
  933. void SemSegContextTree::extractBasicFeatures ( NICE::MultiChannelImageT<double> &feats, const ColorImage &img, const string &currentFile)
  934. {
  935. int xsize = img.width();
  936. int ysize = img.height();
  937. //TODO: resize image?!
  938. #ifdef LOCALFEATS
  939. lfcw->getFeats ( img, feats );
  940. #else
  941. feats.reInit ( xsize, ysize, 3 );
  942. for ( int x = 0; x < xsize; x++ )
  943. {
  944. for ( int y = 0; y < ysize; y++ )
  945. {
  946. for ( int r = 0; r < 3; r++ )
  947. {
  948. feats.set ( x, y, img.getPixel ( x, y, r ), r );
  949. }
  950. }
  951. }
  952. feats = ColorSpace::rgbtolab ( feats );
  953. #endif
  954. if ( useGradient )
  955. {
  956. int currentsize = feats.channels();
  957. feats.addChannel ( currentsize );
  958. for ( int c = 0; c < currentsize; c++ )
  959. {
  960. ImageT<double> tmp = feats[c];
  961. ImageT<double> tmp2 = feats[c+currentsize];
  962. NICE::FilterT<double>::sobel ( tmp, tmp2 );
  963. }
  964. }
  965. // read the geometric cues produced by Hoiem et al.
  966. if ( useHoiemFeatures )
  967. {
  968. // we could also give the following set as a config option
  969. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  970. vector<string> hoiemClasses;
  971. StringTools::split ( hoiemClasses_s, ' ', hoiemClasses );
  972. // Now we have to do some fancy regular expressions :)
  973. // Original image filename: basel_000083.jpg
  974. // hoiem result: basel_000083_c_sky.png
  975. // Fancy class of Ferid which supports string handling especially for filenames
  976. FileName fn ( currentFile );
  977. fn.removeExtension();
  978. FileName fnBase = fn.extractFileName();
  979. // counter for the channel index, starts with the current size of the destination multi-channel image
  980. int currentChannel = feats.channels();
  981. // add a channel for each feature in advance
  982. feats.addChannel ( hoiemClasses.size() );
  983. // loop through all geometric categories and add the images
  984. for ( vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++ )
  985. {
  986. string hoiemClass = *i;
  987. FileName fnConfidenceImage ( hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png" );
  988. if ( ! fnConfidenceImage.fileExists() )
  989. {
  990. fthrow(Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << currentFile << ")" );
  991. } else {
  992. Image confidenceImage ( fnConfidenceImage.str() );
  993. // check whether the image size is consistent
  994. if ( confidenceImage.width() != feats.width() || confidenceImage.height() != feats.height() )
  995. {
  996. fthrow(Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str());
  997. }
  998. ImageT<double> dst = feats[currentChannel];
  999. // copy standard image to double image
  1000. for ( uint y = 0 ; y < confidenceImage.height(); y++ )
  1001. for ( uint x = 0 ; x < confidenceImage.width(); x++ )
  1002. feats(x, y, currentChannel) = (double)confidenceImage(x,y);
  1003. }
  1004. }
  1005. }
  1006. }
  1007. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities )
  1008. {
  1009. int xsize;
  1010. int ysize;
  1011. ce->getImageSize ( xsize, ysize );
  1012. int numClasses = classNames->numClasses();
  1013. fprintf ( stderr, "ContextTree classification !\n" );
  1014. probabilities.reInit ( xsize, ysize, numClasses );
  1015. probabilities.setAll ( 0 );
  1016. #ifdef TEXTONMAP
  1017. MultiChannelImageT<SparseVectorInt> textonMap ( xsize / grid + 1, ysize / grid + 1, 1 );
  1018. MultiChannelImageT<SparseVectorInt> integralTexton ( xsize / grid + 1, ysize / grid + 1, 1 );
  1019. #endif
  1020. std::string currentFile = Globals::getCurrentImgFN();
  1021. MultiChannelImageT<double> feats;
  1022. NICE::ColorImage img;
  1023. try {
  1024. img = ColorImage ( currentFile );
  1025. } catch ( Exception ) {
  1026. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  1027. return;
  1028. }
  1029. extractBasicFeatures(feats, img, currentFile); //read image and do some simple transformations
  1030. bool allleaf = false;
  1031. MultiChannelImageT<double> integralImg;
  1032. MultiChannelImageT<unsigned short int> currentfeats ( xsize, ysize, nbTrees );
  1033. currentfeats.setAll ( 0 );
  1034. depth = 0;
  1035. for ( int d = 0; d < maxDepth && !allleaf; d++ )
  1036. {
  1037. depth++;
  1038. #ifdef TEXTONMAP
  1039. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  1040. if ( depth == 1 )
  1041. {
  1042. weight = computeWeight ( 1, maxDepth );
  1043. }
  1044. #endif
  1045. allleaf = true;
  1046. MultiChannelImageT<unsigned short int> lastfeats = currentfeats;
  1047. int tree;
  1048. #pragma omp parallel for private(tree)
  1049. for ( tree = 0; tree < nbTrees; tree++ )
  1050. {
  1051. for ( int x = 0; x < xsize; x++ )
  1052. {
  1053. for ( int y = 0; y < ysize; y++ )
  1054. {
  1055. int t = currentfeats.get ( x, y, tree );
  1056. if ( forest[tree][t].left > 0 )
  1057. {
  1058. allleaf = false;
  1059. Features feat;
  1060. feat.feats = &feats;
  1061. feat.cfeats = &lastfeats;
  1062. feat.cTree = tree;
  1063. feat.tree = &forest[tree];
  1064. feat.integralImg = &integralImg;
  1065. double val = forest[tree][t].feat->getVal ( feat, x, y );
  1066. int subx = x / grid;
  1067. int suby = y / grid;
  1068. if ( val < forest[tree][t].decision )
  1069. {
  1070. currentfeats.set ( x, y, forest[tree][t].left, tree );
  1071. #ifdef TEXTONMAP
  1072. #pragma omp critical
  1073. {
  1074. SparseVectorInt v;
  1075. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].left].nodeNumber, weight ) );
  1076. textonMap ( subx, suby ).add ( v );
  1077. }
  1078. #endif
  1079. }
  1080. else
  1081. {
  1082. currentfeats.set ( x, y, forest[tree][t].right, tree );
  1083. #ifdef TEXTONMAP
  1084. #pragma omp critical
  1085. {
  1086. SparseVectorInt v;
  1087. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].right].nodeNumber, weight ) );
  1088. textonMap ( subx, suby ).add ( v );
  1089. }
  1090. #endif
  1091. }
  1092. /*if ( x == xpos && y == ypos )
  1093. {
  1094. cout << "val: " << val << " decision: " << forest[tree][t].decision << " details: " << forest[tree][t].feat->writeInfos() << endl;
  1095. }*/
  1096. }
  1097. }
  1098. }
  1099. if ( depth < maxDepth )
  1100. {
  1101. //compute integral image
  1102. int channels = (int)labelmap.size() + feats.channels();
  1103. if ( integralImg.width() == 0 )
  1104. {
  1105. int xsize = feats.width();
  1106. int ysize = feats.height();
  1107. integralImg.reInit ( xsize, ysize, channels );
  1108. integralImg.setAll ( 0.0 );
  1109. }
  1110. }
  1111. }
  1112. if ( depth < maxDepth )
  1113. {
  1114. computeIntegralImage ( currentfeats, feats, integralImg );
  1115. #ifdef TEXTONMAP
  1116. computeIntegralImage ( textonMap, integralTexton );
  1117. #endif
  1118. }
  1119. }
  1120. // cout << forest[0][currentfeats.get ( xpos, ypos, 0 ) ].dist << endl;
  1121. #ifdef WRITEGLOB
  1122. ofstream outstream ( "globtest.feat", ofstream::app );
  1123. outstream << 0 << endl;
  1124. integralTexton ( integralTexton.width() - 1, integralTexton.height() - 1 ).store ( outstream );
  1125. outstream.close();
  1126. #endif
  1127. string cndir = conf->gS ( "SSContextTree", "cndir", "" );
  1128. int classes = (int)probabilities.channels();
  1129. vector<int> useclass ( classes, 1 );
  1130. #ifdef WRITEGLOB
  1131. std::vector< std::string > list;
  1132. StringTools::split ( currentFile, '/', list );
  1133. string orgname = list.back();
  1134. ofstream ostream ( "filelist.txt", ofstream::app );
  1135. ostream << orgname << ".dat" << endl;
  1136. ostream.close();
  1137. if ( cndir != "" )
  1138. {
  1139. useclass = vector<int> ( classes, 0 );
  1140. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1141. #undef OLD
  1142. #ifdef OLD
  1143. while ( !infile.eof() && infile.good() )
  1144. {
  1145. int tmp;
  1146. infile >> tmp;
  1147. assert ( tmp >= 0 && tmp < classes );
  1148. useclass[tmp] = 1;
  1149. }
  1150. #else
  1151. int c = 0;
  1152. vector<double> probs ( classes, 0.0 );
  1153. while ( !infile.eof() && infile.good() )
  1154. {
  1155. infile >> probs[c];
  1156. c++;
  1157. }
  1158. vector<double> sorted = probs;
  1159. sort ( sorted.begin(), sorted.end() );
  1160. double thr = sorted[10];
  1161. if ( thr < 0.0 )
  1162. thr = 0.0;
  1163. for ( int c = 0; c < classes; c++ )
  1164. {
  1165. if ( probs[c] < thr )
  1166. {
  1167. useclass[c] = 1;
  1168. }
  1169. }
  1170. #endif
  1171. for ( int c = 0; c < classes; c++ )
  1172. {
  1173. if ( useclass[c] == 0 )
  1174. {
  1175. probabilities.set ( -numeric_limits< double >::max(), c );
  1176. }
  1177. }
  1178. }
  1179. #endif
  1180. if ( pixelWiseLabeling )
  1181. {
  1182. //finales labeln:
  1183. //long int offset = 0;
  1184. for ( int x = 0; x < xsize; x++ )
  1185. {
  1186. for ( int y = 0; y < ysize; y++ )
  1187. {
  1188. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1189. int maxindex = 0;
  1190. uint s = forest[0][0].dist.size();
  1191. for ( uint i = 0; i < s; i++ )
  1192. {
  1193. int currentclass = labelmapback[i];
  1194. if ( useclass[currentclass] )
  1195. {
  1196. probabilities ( x, y, currentclass ) = getMeanProb ( x, y, i, currentfeats );
  1197. if ( probabilities ( x, y, currentclass ) > maxvalue )
  1198. {
  1199. maxvalue = probabilities ( x, y, currentclass );
  1200. maxindex = currentclass;
  1201. }
  1202. }
  1203. }
  1204. segresult.setPixel ( x, y, maxindex );
  1205. if ( maxvalue > 1 )
  1206. cout << "maxvalue: " << maxvalue << endl;
  1207. }
  1208. }
  1209. #undef VISUALIZE
  1210. #ifdef VISUALIZE
  1211. for ( int j = 0 ; j < (int)probabilities.numChannels; j++ )
  1212. {
  1213. //cout << "class: " << j << endl;//" " << cn.text ( j ) << endl;
  1214. NICE::Matrix tmp ( probabilities.height(), probabilities.width() );
  1215. double maxval = -numeric_limits<double>::max();
  1216. double minval = numeric_limits<double>::max();
  1217. for ( int y = 0; y < probabilities.height(); y++ )
  1218. for ( int x = 0; x < probabilities.width(); x++ )
  1219. {
  1220. double val = probabilities ( x, y, j );
  1221. tmp ( y, x ) = val;
  1222. maxval = std::max ( val, maxval );
  1223. minval = std::min ( val, minval );
  1224. }
  1225. tmp ( 0, 0 ) = 1.0;
  1226. tmp ( 0, 1 ) = 0.0;
  1227. NICE::ColorImage imgrgb ( probabilities.width(), probabilities.height() );
  1228. ICETools::convertToRGB ( tmp, imgrgb );
  1229. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text ( j ) << endl;
  1230. std::string s;
  1231. std::stringstream out;
  1232. out << "tmpprebmap" << j << ".ppm";
  1233. s = out.str();
  1234. imgrgb.write ( s );
  1235. //showImage(imgrgb, "Ergebnis");
  1236. //getchar();
  1237. }
  1238. cout << "fertsch" << endl;
  1239. getchar();
  1240. cout << "weiter gehtsch" << endl;
  1241. #endif
  1242. }
  1243. else
  1244. {
  1245. //final labeling using segmentation
  1246. Matrix regions;
  1247. //showImage(img);
  1248. int regionNumber = segmentation->segRegions ( img, regions );
  1249. cout << "regions: " << regionNumber << endl;
  1250. int dSize = forest[0][0].dist.size();
  1251. vector<vector<double> > regionProbs ( regionNumber, vector<double> ( dSize, 0.0 ) );
  1252. vector<int> bestlabels ( regionNumber, 0 );
  1253. for ( int y = 0; y < img.height(); y++ )
  1254. {
  1255. for ( int x = 0; x < img.width(); x++ )
  1256. {
  1257. int cregion = regions ( x, y );
  1258. for ( int d = 0; d < dSize; d++ )
  1259. {
  1260. regionProbs[cregion][d] += getMeanProb ( x, y, d, currentfeats );
  1261. }
  1262. }
  1263. }
  1264. for ( int r = 0; r < regionNumber; r++ )
  1265. {
  1266. double maxval = regionProbs[r][0];
  1267. bestlabels[r] = 0;
  1268. for ( int d = 1; d < dSize; d++ )
  1269. {
  1270. if ( maxval < regionProbs[r][d] )
  1271. {
  1272. maxval = regionProbs[r][d];
  1273. bestlabels[r] = d;
  1274. }
  1275. }
  1276. bestlabels[r] = labelmapback[bestlabels[r]];
  1277. }
  1278. for ( int y = 0; y < img.height(); y++ )
  1279. {
  1280. for ( int x = 0; x < img.width(); x++ )
  1281. {
  1282. segresult.setPixel ( x, y, bestlabels[regions ( x,y ) ] );
  1283. }
  1284. }
  1285. #define WRITEREGIONS
  1286. #ifdef WRITEREGIONS
  1287. RegionGraph rg;
  1288. segmentation->getGraphRepresentation ( img, regions, rg );
  1289. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1290. {
  1291. rg[pos]->setProbs ( regionProbs[pos] );
  1292. }
  1293. std::string s;
  1294. std::stringstream out;
  1295. std::vector< std::string > list;
  1296. StringTools::split ( Globals::getCurrentImgFN (), '/', list );
  1297. out << "rgout/" << list.back() << ".graph";
  1298. string writefile = out.str();
  1299. rg.write ( writefile );
  1300. #endif
  1301. }
  1302. cout << "segmentation finished" << endl;
  1303. }
  1304. void SemSegContextTree::store ( std::ostream & os, int format ) const
  1305. {
  1306. os << nbTrees << endl;
  1307. classnames.store ( os );
  1308. map<int, int>::const_iterator it;
  1309. os << labelmap.size() << endl;
  1310. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1311. os << ( *it ).first << " " << ( *it ).second << endl;
  1312. os << labelmapback.size() << endl;
  1313. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1314. os << ( *it ).first << " " << ( *it ).second << endl;
  1315. int trees = forest.size();
  1316. os << trees << endl;
  1317. for ( int t = 0; t < trees; t++ )
  1318. {
  1319. int nodes = forest[t].size();
  1320. os << nodes << endl;
  1321. for ( int n = 0; n < nodes; n++ )
  1322. {
  1323. os << forest[t][n].left << " " << forest[t][n].right << " " << forest[t][n].decision << " " << forest[t][n].isleaf << " " << forest[t][n].depth << " " << forest[t][n].featcounter << " " << forest[t][n].nodeNumber << endl;
  1324. os << forest[t][n].dist << endl;
  1325. if ( forest[t][n].feat == NULL )
  1326. os << -1 << endl;
  1327. else
  1328. {
  1329. os << forest[t][n].feat->getOps() << endl;
  1330. forest[t][n].feat->store ( os );
  1331. }
  1332. }
  1333. }
  1334. os << channelType.size() << endl;
  1335. for(int i = 0; i < channelType.size(); i++)
  1336. {
  1337. os << channelType[i] << " ";
  1338. }
  1339. os << endl;
  1340. }
  1341. void SemSegContextTree::restore ( std::istream & is, int format )
  1342. {
  1343. is >> nbTrees;
  1344. classnames.restore ( is );
  1345. int lsize;
  1346. is >> lsize;
  1347. labelmap.clear();
  1348. for ( int l = 0; l < lsize; l++ )
  1349. {
  1350. int first, second;
  1351. is >> first;
  1352. is >> second;
  1353. labelmap[first] = second;
  1354. }
  1355. is >> lsize;
  1356. labelmapback.clear();
  1357. for ( int l = 0; l < lsize; l++ )
  1358. {
  1359. int first, second;
  1360. is >> first;
  1361. is >> second;
  1362. labelmapback[first] = second;
  1363. }
  1364. int trees;
  1365. is >> trees;
  1366. forest.clear();
  1367. for ( int t = 0; t < trees; t++ )
  1368. {
  1369. vector<TreeNode> tmptree;
  1370. forest.push_back ( tmptree );
  1371. int nodes;
  1372. is >> nodes;
  1373. //cout << "nodes: " << nodes << endl;
  1374. for ( int n = 0; n < nodes; n++ )
  1375. {
  1376. TreeNode tmpnode;
  1377. forest[t].push_back ( tmpnode );
  1378. is >> forest[t][n].left;
  1379. is >> forest[t][n].right;
  1380. is >> forest[t][n].decision;
  1381. is >> forest[t][n].isleaf;
  1382. is >> forest[t][n].depth;
  1383. is >> forest[t][n].featcounter;
  1384. is >> forest[t][n].nodeNumber;
  1385. is >> forest[t][n].dist;
  1386. int feattype;
  1387. is >> feattype;
  1388. assert ( feattype < NBOPERATIONS );
  1389. forest[t][n].feat = NULL;
  1390. if ( feattype >= 0 )
  1391. {
  1392. for ( uint o = 0; o < ops.size(); o++ )
  1393. {
  1394. if ( ops[o]->getOps() == feattype )
  1395. {
  1396. forest[t][n].feat = ops[o]->clone();
  1397. break;
  1398. }
  1399. }
  1400. if ( forest[t][n].feat == NULL )
  1401. {
  1402. for ( uint o = 0; o < cops.size(); o++ )
  1403. {
  1404. if ( cops[o]->getOps() == feattype )
  1405. {
  1406. forest[t][n].feat = cops[o]->clone();
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. assert ( forest[t][n].feat != NULL );
  1412. forest[t][n].feat->restore ( is );
  1413. }
  1414. }
  1415. }
  1416. channelType.clear();
  1417. int ctsize;
  1418. is >> ctsize;
  1419. for(int i = 0; i < ctsize; i++)
  1420. {
  1421. int tmp;
  1422. is >> tmp;
  1423. channelType.push_back(tmp);
  1424. }
  1425. }