SemSegContextTree.cpp 47 KB

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