SemSegContextTree.cpp 47 KB

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