SemSegContextTree.cpp 45 KB

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