SemSegContextTree.cpp 46 KB

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