SemSegContextTree.cpp 46 KB

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