SemSegContextTree.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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. //cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  341. //cout << "globent: " << globent << " l_bestig " << l_bestig << " f: " << p << " l_splitval: " << l_splitval << endl;
  342. //cout << "p: " << featsubset[f] << endl;
  343. if ( l_bestig > bestig )
  344. {
  345. bestig = l_bestig;
  346. splitop = featsel[f];
  347. splitval = l_splitval;
  348. }
  349. }
  350. }
  351. //getchar();
  352. //splitop->writeInfos();
  353. //cout<< "ig: " << bestig << endl;
  354. //FIXME: delete all features!
  355. /*for(int i = 0; i < featsPerSplit; i++)
  356. {
  357. if(featsel[i] != splitop)
  358. delete featsel[i];
  359. }*/
  360. #ifdef debug
  361. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  362. #endif
  363. return bestig;
  364. }
  365. inline double SemSegContextTree::getMeanProb ( const int &x, const int &y, const int &channel, const MultiChannelImageT<unsigned short int> &currentfeats )
  366. {
  367. double val = 0.0;
  368. for ( int tree = 0; tree < nbTrees; tree++ )
  369. {
  370. val += forest[tree][currentfeats.get ( x,y,tree ) ].dist[channel];
  371. }
  372. return val / (double)nbTrees;
  373. }
  374. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<SparseVectorInt> &infeats, NICE::MultiChannelImageT<SparseVectorInt> &integralImage )
  375. {
  376. int xsize = infeats.width();
  377. int ysize = infeats.height();
  378. integralImage ( 0, 0 ).add ( infeats.get ( 0, 0 ) );
  379. //first column
  380. for ( int y = 1; y < ysize; y++ )
  381. {
  382. integralImage ( 0, y ).add ( infeats.get ( 0, y ) );
  383. integralImage ( 0, y ).add ( integralImage ( 0, y - 1 ) );
  384. }
  385. //first row
  386. for ( int x = 1; x < xsize; x++ )
  387. {
  388. integralImage ( x, 0 ).add ( infeats.get ( x, 0 ) );
  389. integralImage ( x, 0 ).add ( integralImage ( x - 1, 0 ) );
  390. }
  391. //rest
  392. for ( int y = 1; y < ysize; y++ )
  393. {
  394. for ( int x = 1; x < xsize; x++ )
  395. {
  396. integralImage ( x, y ).add ( infeats.get ( x, y ) );
  397. integralImage ( x, y ).add ( integralImage ( x, y - 1 ) );
  398. integralImage ( x, y ).add ( integralImage ( x - 1, y ) );
  399. integralImage ( x, y ).sub ( integralImage ( x - 1, y - 1 ) );
  400. }
  401. }
  402. }
  403. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<unsigned short int> &currentfeats, NICE::MultiChannelImageT<double> &feats, int firstChannel )
  404. {
  405. int xsize = currentfeats.width();
  406. int ysize = currentfeats.height();
  407. xsize = feats.width();
  408. ysize = feats.height();
  409. if ( firstiteration )
  410. {
  411. firstiteration = false;
  412. #pragma omp parallel for
  413. for ( int it = 0; it < integralMap.size(); it++ )
  414. {
  415. int c1 = integralMap[it].first;
  416. int c = integralMap[it].second;
  417. feats( 0, 0, c ) = feats( 0, 0, c1 );
  418. //first column
  419. for ( int y = 1; y < ysize; y++ )
  420. {
  421. feats( 0, y, c ) = feats.get ( 0, y, c1 )
  422. + feats.get ( 0, y-1, c );
  423. }
  424. //first row
  425. for ( int x = 1; x < xsize; x++ )
  426. {
  427. feats( x, 0, c ) = feats.get ( x, 0, c1 )
  428. + feats.get ( x-1, 0, c );
  429. }
  430. //rest
  431. for ( int y = 1; y < ysize; y++ )
  432. {
  433. for ( int x = 1; x < xsize; x++ )
  434. {
  435. feats ( x, y, c ) = feats ( x, y, c1 )
  436. + feats ( x, y - 1, c )
  437. + feats ( x - 1, y, c )
  438. - feats ( x - 1, y - 1, c );
  439. }
  440. }
  441. }
  442. }
  443. int channels = ( int ) forest[0][0].dist.size();
  444. #pragma omp parallel for
  445. for ( int c = 0; c < channels; c++ )
  446. {
  447. feats ( 0, 0, firstChannel + c ) = getMeanProb ( 0, 0, c, currentfeats );
  448. //first column
  449. for ( int y = 1; y < ysize; y++ )
  450. {
  451. feats ( 0, y, firstChannel + c ) = getMeanProb ( 0, y, c, currentfeats )
  452. + feats ( 0, y - 1, firstChannel + c );
  453. }
  454. //first row
  455. for ( int x = 1; x < xsize; x++ )
  456. {
  457. feats ( x, 0, firstChannel + c ) = getMeanProb ( x, 0, c, currentfeats )
  458. + feats ( x - 1, 0, firstChannel + c );
  459. }
  460. //rest
  461. for ( int y = 1; y < ysize; y++ )
  462. {
  463. for ( int x = 1; x < xsize; x++ )
  464. {
  465. feats ( x, y, firstChannel + c ) = getMeanProb ( x, y, c, currentfeats )
  466. + feats ( x, y - 1, firstChannel + c )
  467. + feats ( x - 1, y, firstChannel + c )
  468. - feats ( x - 1, y - 1, firstChannel + c );
  469. }
  470. }
  471. }
  472. }
  473. inline double computeWeight ( const double &d, const double &dim )
  474. {
  475. return 1.0 / ( pow ( 2, (double)( dim - d + 1 ) ) );
  476. }
  477. void SemSegContextTree::train ( const MultiDataset *md )
  478. {
  479. const LabeledSet train = * ( *md ) ["train"];
  480. const LabeledSet *trainp = &train;
  481. ProgressBar pb ( "compute feats" );
  482. pb.show();
  483. //TODO: Speichefresser!, lohnt sich sparse?
  484. vector<MultiChannelImageT<double> > allfeats;
  485. vector<MultiChannelImageT<unsigned short int> > currentfeats;
  486. vector<MatrixT<int> > labels;
  487. #ifdef TEXTONMAP
  488. vector<MultiChannelImageT<SparseVectorInt> > textonMap;
  489. #endif
  490. vector<MultiChannelImageT<SparseVectorInt> > integralTexton;
  491. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  492. if ( forbidden_classes_s == "" )
  493. {
  494. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  495. }
  496. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  497. int imgcounter = 0;
  498. int amountPixels = 0;
  499. LOOP_ALL_S ( *trainp )
  500. {
  501. EACH_INFO ( classno, info );
  502. NICE::ColorImage img;
  503. std::string currentFile = info.img();
  504. CachedExample *ce = new CachedExample ( currentFile );
  505. const LocalizationResult *locResult = info.localization();
  506. if ( locResult->size() <= 0 )
  507. {
  508. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  509. currentFile.c_str() );
  510. continue;
  511. }
  512. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  513. int xsize, ysize;
  514. ce->getImageSize ( xsize, ysize );
  515. amountPixels += xsize * ysize;
  516. MatrixT<int> tmpMat ( xsize, ysize );
  517. currentfeats.push_back ( MultiChannelImageT<unsigned short int> ( xsize, ysize, nbTrees ) );
  518. currentfeats[imgcounter].setAll ( 0 );
  519. #ifdef TEXTONMAP
  520. textonMap.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  521. integralTexton.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  522. #endif
  523. labels.push_back ( tmpMat );
  524. try {
  525. img = ColorImage ( currentFile );
  526. } catch ( Exception ) {
  527. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  528. continue;
  529. }
  530. Globals::setCurrentImgFN ( currentFile );
  531. //TODO: resize image?!
  532. MultiChannelImageT<double> feats;
  533. allfeats.push_back ( feats );
  534. // read image and do some simple transformations
  535. extractBasicFeatures ( allfeats[imgcounter], img, currentFile );
  536. // getting groundtruth
  537. NICE::Image pixelLabels ( xsize, ysize );
  538. pixelLabels.set ( 0 );
  539. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  540. for ( int x = 0; x < xsize; x++ )
  541. {
  542. for ( int y = 0; y < ysize; y++ )
  543. {
  544. classno = pixelLabels.getPixel ( x, y );
  545. labels[imgcounter] ( x, y ) = classno;
  546. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  547. continue;
  548. labelcounter[classno]++;
  549. }
  550. }
  551. imgcounter++;
  552. pb.update ( trainp->count() );
  553. delete ce;
  554. }
  555. pb.hide();
  556. map<int, int>::iterator mapit;
  557. int classes = 0;
  558. for ( mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++ )
  559. {
  560. labelmap[mapit->first] = classes;
  561. labelmapback[classes] = mapit->first;
  562. classes++;
  563. }
  564. ////////////////////////////////////////////////////
  565. //define which featurextraction methods should be used for each channel
  566. #ifdef LOCALFEATS
  567. rawChannels = 9;
  568. #else
  569. rawChannels = 3;
  570. #endif
  571. // how many channels without integral image
  572. int shift = 0;
  573. if ( useGradient )
  574. rawChannels *= 2;
  575. if ( useHoiemFeatures )
  576. rawChannels += 8;
  577. // gray value images
  578. for ( int i = 0; i < rawChannels; i++ )
  579. {
  580. channelType.push_back ( 0 );
  581. }
  582. // regions
  583. if ( useRegionFeature )
  584. {
  585. channelType.push_back ( 1 );
  586. shift++;
  587. }
  588. for ( int i = 0; i < rawChannels; i++ )
  589. {
  590. channelType.push_back ( 2 );
  591. }
  592. // integral images
  593. for ( int i = 0; i < classes; i++ )
  594. {
  595. channelType.push_back ( 3 );
  596. }
  597. integralMap.clear();
  598. int integralImageAmount = rawChannels;
  599. for ( int ii = 0; ii < integralImageAmount; ii++ )
  600. {
  601. integralMap.push_back ( pair<int, int> ( ii, ii + integralImageAmount + shift ) );
  602. }
  603. int amountTypes = 5;
  604. channelsPerType = vector<vector<int> > ( amountTypes, vector<int>() );
  605. for ( int i = 0; i < channelType.size(); i++ )
  606. {
  607. channelsPerType[channelType[i]].push_back ( i );
  608. }
  609. for ( int i = 0; i < classes; i++ )
  610. {
  611. channelsPerType[channelsPerType.size()-1].push_back ( i );
  612. }
  613. ftypes = std::min ( amountTypes, ftypes );
  614. ////////////////////////////////////////////////////
  615. //balancing
  616. int featcounter = 0;
  617. a = vector<double> ( classes, 0.0 );
  618. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  619. {
  620. int xsize = (int)currentfeats[iCounter].width();
  621. int ysize = (int)currentfeats[iCounter].height();
  622. for ( int x = 0; x < xsize; x++ )
  623. {
  624. for ( int y = 0; y < ysize; y++ )
  625. {
  626. featcounter++;
  627. int cn = labels[iCounter] ( x, y );
  628. if ( labelmap.find ( cn ) == labelmap.end() )
  629. continue;
  630. a[labelmap[cn]] ++;
  631. }
  632. }
  633. }
  634. for ( int i = 0; i < (int)a.size(); i++ )
  635. {
  636. a[i] /= (double)featcounter;
  637. }
  638. #ifdef DEBUG
  639. for ( int i = 0; i < (int)a.size(); i++ )
  640. {
  641. cout << "a[" << i << "]: " << a[i] << endl;
  642. }
  643. cout << "a.size: " << a.size() << endl;
  644. #endif
  645. depth = 0;
  646. int uniquenumber = 0;
  647. for ( int t = 0; t < nbTrees; t++ )
  648. {
  649. vector<TreeNode> tree;
  650. tree.push_back ( TreeNode() );
  651. tree[0].dist = vector<double> ( classes, 0.0 );
  652. tree[0].depth = depth;
  653. tree[0].featcounter = amountPixels;
  654. tree[0].nodeNumber = uniquenumber;
  655. uniquenumber++;
  656. forest.push_back ( tree );
  657. }
  658. vector<int> startnode ( nbTrees, 0 );
  659. bool allleaf = false;
  660. //int baseFeatSize = allfeats[0].size();
  661. while ( !allleaf && depth < maxDepth )
  662. {
  663. depth++;
  664. #ifdef DEBUG
  665. cout << "depth: " << depth << endl;
  666. #endif
  667. allleaf = true;
  668. vector<MultiChannelImageT<unsigned short int> > lastfeats = currentfeats;
  669. #if 1
  670. Timer timer;
  671. timer.start();
  672. #endif
  673. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  674. if ( depth == 1 )
  675. {
  676. weight = computeWeight ( 1, maxDepth );
  677. }
  678. for ( int tree = 0; tree < nbTrees; tree++ )
  679. {
  680. int t = (int)forest[tree].size();
  681. int s = startnode[tree];
  682. startnode[tree] = t;
  683. //TODO vielleicht parallel wenn nächste schleife trotzdem noch parallelsiert würde, die hat mehr gewicht
  684. //#pragma omp parallel for
  685. for ( int i = s; i < t; i++ )
  686. {
  687. if ( !forest[tree][i].isleaf && forest[tree][i].left < 0 )
  688. {
  689. Operation *splitfeat = NULL;
  690. double splitval;
  691. double bestig = getBestSplit ( allfeats, lastfeats, labels, i, splitfeat, splitval, tree );
  692. for ( int ii = 0; ii < lastfeats.size(); ii++ )
  693. {
  694. for ( int c = 0; c < lastfeats[ii].channels(); c++ )
  695. {
  696. short unsigned int minv, maxv;
  697. lastfeats[ii].statistics ( minv, maxv, c );
  698. }
  699. }
  700. forest[tree][i].feat = splitfeat;
  701. forest[tree][i].decision = splitval;
  702. if ( splitfeat != NULL )
  703. {
  704. allleaf = false;
  705. int left = forest[tree].size();
  706. forest[tree].push_back ( TreeNode() );
  707. forest[tree].push_back ( TreeNode() );
  708. int right = left + 1;
  709. forest[tree][i].left = left;
  710. forest[tree][i].right = right;
  711. forest[tree][left].dist = vector<double> ( classes, 0.0 );
  712. forest[tree][right].dist = vector<double> ( classes, 0.0 );
  713. forest[tree][left].depth = depth;
  714. forest[tree][right].depth = depth;
  715. forest[tree][left].featcounter = 0;
  716. forest[tree][right].featcounter = 0;
  717. forest[tree][left].nodeNumber = uniquenumber;
  718. int leftu = uniquenumber;
  719. uniquenumber++;
  720. forest[tree][right].nodeNumber = uniquenumber;
  721. int rightu = uniquenumber;
  722. uniquenumber++;
  723. forest[tree][right].featcounter = 0;
  724. #pragma omp parallel for
  725. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  726. {
  727. int xsize = currentfeats[iCounter].width();
  728. int ysize = currentfeats[iCounter].height();
  729. for ( int x = 0; x < xsize; x++ )
  730. {
  731. for ( int y = 0; y < ysize; y++ )
  732. {
  733. if ( currentfeats[iCounter].get ( x, y, tree ) == i )
  734. {
  735. Features feat;
  736. feat.feats = &allfeats[iCounter];
  737. feat.cfeats = &lastfeats[iCounter];
  738. feat.cTree = tree;
  739. feat.tree = &forest[tree];
  740. double val = splitfeat->getVal ( feat, x, y );
  741. int subx = x / grid;
  742. int suby = y / grid;
  743. #pragma omp critical
  744. if ( val < splitval )
  745. {
  746. currentfeats[iCounter].set ( x, y, left, tree );
  747. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  748. forest[tree][left].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  749. forest[tree][left].featcounter++;
  750. SparseVectorInt v;
  751. v.insert ( pair<int, double> ( leftu, weight ) );
  752. #ifdef TEXTONMAP
  753. textonMap[iCounter] ( subx, suby ).add ( v );
  754. #endif
  755. }
  756. else
  757. {
  758. currentfeats[iCounter].set ( x, y, right, tree );
  759. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  760. forest[tree][right].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  761. forest[tree][right].featcounter++;
  762. //feld im subsampled finden und in diesem rechts hochzählen
  763. SparseVectorInt v;
  764. v.insert ( pair<int, double> ( rightu, weight ) );
  765. #ifdef TEXTONMAP
  766. textonMap[iCounter] ( subx, suby ).add ( v );
  767. #endif
  768. }
  769. }
  770. }
  771. }
  772. }
  773. double lcounter = 0.0, rcounter = 0.0;
  774. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  775. {
  776. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  777. {
  778. forest[tree][left].dist[d] = 0;
  779. forest[tree][right].dist[d] = 0;
  780. }
  781. else
  782. {
  783. forest[tree][left].dist[d] /= a[d];
  784. lcounter += forest[tree][left].dist[d];
  785. forest[tree][right].dist[d] /= a[d];
  786. rcounter += forest[tree][right].dist[d];
  787. }
  788. }
  789. if ( lcounter <= 0 || rcounter <= 0 )
  790. {
  791. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  792. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  793. cout << "bestig: " << bestig << endl;
  794. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  795. {
  796. int xsize = currentfeats[iCounter].width();
  797. int ysize = currentfeats[iCounter].height();
  798. int counter = 0;
  799. for ( int x = 0; x < xsize; x++ )
  800. {
  801. for ( int y = 0; y < ysize; y++ )
  802. {
  803. if ( lastfeats[iCounter].get ( x, y, tree ) == i )
  804. {
  805. if ( ++counter > 30 )
  806. break;
  807. Features feat;
  808. feat.feats = &allfeats[iCounter];
  809. feat.cfeats = &lastfeats[iCounter];
  810. feat.cTree = tree;
  811. feat.tree = &forest[tree];
  812. double val = splitfeat->getVal ( feat, x, y );
  813. cout << "splitval: " << splitval << " val: " << val << endl;
  814. }
  815. }
  816. }
  817. }
  818. assert ( lcounter > 0 && rcounter > 0 );
  819. }
  820. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  821. {
  822. forest[tree][left].dist[d] /= lcounter;
  823. forest[tree][right].dist[d] /= rcounter;
  824. }
  825. }
  826. else
  827. {
  828. forest[tree][i].isleaf = true;
  829. }
  830. }
  831. }
  832. }
  833. //compute integral images
  834. if ( firstiteration )
  835. {
  836. for ( int i = 0; i < imgcounter; i++ )
  837. {
  838. int pos = allfeats.size();
  839. allfeats[i].addChannel ( ( int ) ( classes + rawChannels ) );
  840. }
  841. }
  842. #pragma omp parallel for
  843. for ( int i = 0; i < imgcounter; i++ )
  844. {
  845. computeIntegralImage ( currentfeats[i], allfeats[i], channelType.size() - classes );
  846. #ifdef TEXTONMAP
  847. computeIntegralImage ( textonMap[i], integralTexton[i] );
  848. #endif
  849. }
  850. #if 1
  851. timer.stop();
  852. cout << "time for depth " << depth << ": " << timer.getLast() << endl;
  853. #endif
  854. }
  855. #ifdef WRITEGLOB
  856. ofstream outstream ( "globtrain.feat" );
  857. for ( int i = 0; i < textonMap.size(); i++ )
  858. {
  859. set<int> usedclasses;
  860. for ( uint x = 0; x < labels[i].rows(); x++ )
  861. {
  862. for ( uint y = 0; y < labels[i].cols(); y++ )
  863. {
  864. int classno = labels[i] ( x, y );
  865. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  866. continue;
  867. usedclasses.insert ( classno );
  868. }
  869. }
  870. cout << "labels.cols: " << labels[i].cols() << " labels.rows " << labels[i].rows() << endl;
  871. cout << "currentfeats : " << allfeats[i].width() << " allfeats[i].height(); " << allfeats[i].height() << endl;
  872. set<int>::iterator it;
  873. for ( it = usedclasses.begin() ; it != usedclasses.end(); it++ )
  874. outstream << *it << " ";
  875. outstream << endl;
  876. integralTexton[i] ( integralTexton[i].width() - 1, integralTexton[i].height() - 1 ).store ( outstream );
  877. }
  878. outstream.close();
  879. #endif
  880. cout << "uniquenumber " << uniquenumber << endl;
  881. //getchar();
  882. #ifdef DEBUG
  883. for ( int tree = 0; tree < nbTrees; tree++ )
  884. {
  885. int t = (int)forest[tree].size();
  886. for ( int i = 0; i < t; i++ )
  887. {
  888. printf ( "tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right );
  889. if ( !forest[tree][i].isleaf && forest[tree][i].left != -1 )
  890. {
  891. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  892. opOverview[forest[tree][i].feat->getOps() ]++;
  893. contextOverview[forest[tree][i].depth][ (int)forest[tree][i].feat->getContext() ]++;
  894. }
  895. for ( int d = 0; d < (int)forest[tree][i].dist.size(); d++ )
  896. {
  897. cout << " " << forest[tree][i].dist[d];
  898. }
  899. cout << endl;
  900. }
  901. }
  902. for ( uint c = 0; c < ops.size(); c++ )
  903. {
  904. for ( int t = 0; t < ops[c].size(); t++ )
  905. {
  906. cout << ops[c][t]->writeInfos() << ": " << opOverview[ops[c][t]->getOps() ] << endl;
  907. }
  908. }
  909. for ( int d = 0; d < maxDepth; d++ )
  910. {
  911. double sum = contextOverview[d][0] + contextOverview[d][1];
  912. contextOverview[d][0] /= sum;
  913. contextOverview[d][1] /= sum;
  914. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  915. }
  916. #endif
  917. }
  918. void SemSegContextTree::extractBasicFeatures ( NICE::MultiChannelImageT<double> &feats, const ColorImage &img, const string &currentFile )
  919. {
  920. int xsize = img.width();
  921. int ysize = img.height();
  922. //TODO: resize image?!
  923. #ifdef LOCALFEATS
  924. lfcw->getFeats ( img, feats );
  925. #else
  926. feats.reInit ( xsize, ysize, 3 );
  927. for ( int x = 0; x < xsize; x++ )
  928. {
  929. for ( int y = 0; y < ysize; y++ )
  930. {
  931. for ( int r = 0; r < 3; r++ )
  932. {
  933. feats.set ( x, y, img.getPixel ( x, y, r ), r );
  934. }
  935. }
  936. }
  937. feats = ColorSpace::rgbtolab ( feats );
  938. #endif
  939. if ( useGradient )
  940. {
  941. int currentsize = feats.channels();
  942. feats.addChannel ( currentsize );
  943. for ( int c = 0; c < currentsize; c++ )
  944. {
  945. ImageT<double> tmp = feats[c];
  946. ImageT<double> tmp2 = feats[c+currentsize];
  947. NICE::FilterT<double,double,double>::gradientStrength( tmp, tmp2 );
  948. }
  949. }
  950. // read the geometric cues produced by Hoiem et al.
  951. if ( useHoiemFeatures )
  952. {
  953. // we could also give the following set as a config option
  954. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  955. vector<string> hoiemClasses;
  956. StringTools::split ( hoiemClasses_s, ' ', hoiemClasses );
  957. // Now we have to do some fancy regular expressions :)
  958. // Original image filename: basel_000083.jpg
  959. // hoiem result: basel_000083_c_sky.png
  960. // Fancy class of Ferid which supports string handling especially for filenames
  961. FileName fn ( currentFile );
  962. fn.removeExtension();
  963. FileName fnBase = fn.extractFileName();
  964. // counter for the channel index, starts with the current size of the destination multi-channel image
  965. int currentChannel = feats.channels();
  966. // add a channel for each feature in advance
  967. feats.addChannel ( hoiemClasses.size() );
  968. // loop through all geometric categories and add the images
  969. for ( vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++ )
  970. {
  971. string hoiemClass = *i;
  972. FileName fnConfidenceImage ( hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png" );
  973. if ( ! fnConfidenceImage.fileExists() )
  974. {
  975. fthrow ( Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << currentFile << ")" );
  976. } else {
  977. Image confidenceImage ( fnConfidenceImage.str() );
  978. // check whether the image size is consistent
  979. if ( confidenceImage.width() != feats.width() || confidenceImage.height() != feats.height() )
  980. {
  981. fthrow ( Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str() );
  982. }
  983. ImageT<double> dst = feats[currentChannel];
  984. // copy standard image to double image
  985. for ( uint y = 0 ; y < confidenceImage.height(); y++ )
  986. for ( uint x = 0 ; x < confidenceImage.width(); x++ )
  987. feats ( x, y, currentChannel ) = ( double ) confidenceImage ( x, y );
  988. }
  989. }
  990. }
  991. }
  992. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities )
  993. {
  994. int xsize;
  995. int ysize;
  996. ce->getImageSize ( xsize, ysize );
  997. firstiteration = true;
  998. int classes = labelmapback.size();
  999. int numClasses = classNames->numClasses();
  1000. fprintf ( stderr, "ContextTree classification !\n" );
  1001. probabilities.reInit ( xsize, ysize, numClasses );
  1002. probabilities.setAll ( 0 );
  1003. #ifdef TEXTONMAP
  1004. MultiChannelImageT<SparseVectorInt> textonMap ( xsize / grid + 1, ysize / grid + 1, 1 );
  1005. MultiChannelImageT<SparseVectorInt> integralTexton ( xsize / grid + 1, ysize / grid + 1, 1 );
  1006. #endif
  1007. std::string currentFile = Globals::getCurrentImgFN();
  1008. MultiChannelImageT<double> feats;
  1009. NICE::ColorImage img;
  1010. try {
  1011. img = ColorImage ( currentFile );
  1012. } catch ( Exception ) {
  1013. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  1014. return;
  1015. }
  1016. extractBasicFeatures ( feats, img, currentFile ); //read image and do some simple transformations
  1017. bool allleaf = false;
  1018. MultiChannelImageT<unsigned short int> currentfeats ( xsize, ysize, nbTrees );
  1019. currentfeats.setAll ( 0 );
  1020. depth = 0;
  1021. for ( int d = 0; d < maxDepth && !allleaf; d++ )
  1022. {
  1023. depth++;
  1024. #ifdef TEXTONMAP
  1025. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  1026. if ( depth == 1 )
  1027. {
  1028. weight = computeWeight ( 1, maxDepth );
  1029. }
  1030. #endif
  1031. allleaf = true;
  1032. MultiChannelImageT<unsigned short int> lastfeats = currentfeats;
  1033. int tree;
  1034. #pragma omp parallel for private(tree)
  1035. for ( tree = 0; tree < nbTrees; tree++ )
  1036. {
  1037. for ( int x = 0; x < xsize; x++ )
  1038. {
  1039. for ( int y = 0; y < ysize; y++ )
  1040. {
  1041. int t = currentfeats.get ( x, y, tree );
  1042. if ( forest[tree][t].left > 0 )
  1043. {
  1044. allleaf = false;
  1045. Features feat;
  1046. feat.feats = &feats;
  1047. feat.cfeats = &lastfeats;
  1048. feat.cTree = tree;
  1049. feat.tree = &forest[tree];
  1050. double val = forest[tree][t].feat->getVal ( feat, x, y );
  1051. int subx = x / grid;
  1052. int suby = y / grid;
  1053. if ( val < forest[tree][t].decision )
  1054. {
  1055. currentfeats.set ( x, y, forest[tree][t].left, tree );
  1056. #ifdef TEXTONMAP
  1057. #pragma omp critical
  1058. {
  1059. SparseVectorInt v;
  1060. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].left].nodeNumber, weight ) );
  1061. textonMap ( subx, suby ).add ( v );
  1062. }
  1063. #endif
  1064. }
  1065. else
  1066. {
  1067. currentfeats.set ( x, y, forest[tree][t].right, tree );
  1068. #ifdef TEXTONMAP
  1069. #pragma omp critical
  1070. {
  1071. SparseVectorInt v;
  1072. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].right].nodeNumber, weight ) );
  1073. textonMap ( subx, suby ).add ( v );
  1074. }
  1075. #endif
  1076. }
  1077. }
  1078. }
  1079. }
  1080. if ( depth < maxDepth )
  1081. {
  1082. //compute integral images
  1083. if ( firstiteration )
  1084. {
  1085. feats.addChannel ( classes + rawChannels );
  1086. }
  1087. }
  1088. }
  1089. if ( depth < maxDepth )
  1090. {
  1091. computeIntegralImage ( currentfeats, feats, channelType.size() - classes );
  1092. #ifdef TEXTONMAP
  1093. computeIntegralImage ( textonMap, integralTexton );
  1094. #endif
  1095. }
  1096. }
  1097. #ifdef WRITEGLOB
  1098. ofstream outstream ( "globtest.feat", ofstream::app );
  1099. outstream << 0 << endl;
  1100. integralTexton ( integralTexton.width() - 1, integralTexton.height() - 1 ).store ( outstream );
  1101. outstream.close();
  1102. #endif
  1103. string cndir = conf->gS ( "SSContextTree", "cndir", "" );
  1104. int allClasses = ( int ) probabilities.channels();
  1105. vector<int> useclass ( allClasses, 1 );
  1106. #ifdef WRITEGLOB
  1107. std::vector< std::string > list;
  1108. StringTools::split ( currentFile, '/', list );
  1109. string orgname = list.back();
  1110. ofstream ostream ( "filelist.txt", ofstream::app );
  1111. ostream << orgname << ".dat" << endl;
  1112. ostream.close();
  1113. if ( cndir != "" )
  1114. {
  1115. useclass = vector<int> ( allClasses, 0 );
  1116. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1117. #undef OLD
  1118. #ifdef OLD
  1119. while ( !infile.eof() && infile.good() )
  1120. {
  1121. int tmp;
  1122. infile >> tmp;
  1123. assert ( tmp >= 0 && tmp < allClasses );
  1124. useclass[tmp] = 1;
  1125. }
  1126. #else
  1127. int c = 0;
  1128. vector<double> probs ( allClasses, 0.0 );
  1129. while ( !infile.eof() && infile.good() )
  1130. {
  1131. infile >> probs[c];
  1132. c++;
  1133. }
  1134. vector<double> sorted = probs;
  1135. sort ( sorted.begin(), sorted.end() );
  1136. double thr = sorted[10];
  1137. if ( thr < 0.0 )
  1138. thr = 0.0;
  1139. for ( int c = 0; c < allClasses; c++ )
  1140. {
  1141. if ( probs[c] < thr )
  1142. {
  1143. useclass[c] = 1;
  1144. }
  1145. }
  1146. #endif
  1147. for ( int c = 0; c < allClasses; c++ )
  1148. {
  1149. if ( useclass[c] == 0 )
  1150. {
  1151. probabilities.set ( -numeric_limits< double >::max(), c );
  1152. }
  1153. }
  1154. }
  1155. #endif
  1156. if ( pixelWiseLabeling )
  1157. {
  1158. //finales labeln:
  1159. //long int offset = 0;
  1160. for ( int x = 0; x < xsize; x++ )
  1161. {
  1162. for ( int y = 0; y < ysize; y++ )
  1163. {
  1164. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1165. int maxindex = 0;
  1166. uint s = forest[0][0].dist.size();
  1167. for ( uint i = 0; i < s; i++ )
  1168. {
  1169. int currentclass = labelmapback[i];
  1170. if ( useclass[currentclass] )
  1171. {
  1172. probabilities ( x, y, currentclass ) = getMeanProb ( x, y, i, currentfeats );
  1173. if ( probabilities ( x, y, currentclass ) > maxvalue )
  1174. {
  1175. maxvalue = probabilities ( x, y, currentclass );
  1176. maxindex = currentclass;
  1177. }
  1178. }
  1179. }
  1180. segresult.setPixel ( x, y, maxindex );
  1181. if ( maxvalue > 1 )
  1182. cout << "maxvalue: " << maxvalue << endl;
  1183. }
  1184. }
  1185. #undef VISUALIZE
  1186. #ifdef VISUALIZE
  1187. for ( int j = 0 ; j < (int)probabilities.numChannels; j++ )
  1188. {
  1189. //cout << "class: " << j << endl;//" " << cn.text ( j ) << endl;
  1190. NICE::Matrix tmp ( probabilities.height(), probabilities.width() );
  1191. double maxval = -numeric_limits<double>::max();
  1192. double minval = numeric_limits<double>::max();
  1193. for ( int y = 0; y < probabilities.height(); y++ )
  1194. for ( int x = 0; x < probabilities.width(); x++ )
  1195. {
  1196. double val = probabilities ( x, y, j );
  1197. tmp ( y, x ) = val;
  1198. maxval = std::max ( val, maxval );
  1199. minval = std::min ( val, minval );
  1200. }
  1201. tmp ( 0, 0 ) = 1.0;
  1202. tmp ( 0, 1 ) = 0.0;
  1203. NICE::ColorImage imgrgb ( probabilities.width(), probabilities.height() );
  1204. ICETools::convertToRGB ( tmp, imgrgb );
  1205. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text ( j ) << endl;
  1206. std::string s;
  1207. std::stringstream out;
  1208. out << "tmpprebmap" << j << ".ppm";
  1209. s = out.str();
  1210. imgrgb.write ( s );
  1211. //showImage(imgrgb, "Ergebnis");
  1212. //getchar();
  1213. }
  1214. cout << "fertsch" << endl;
  1215. getchar();
  1216. cout << "weiter gehtsch" << endl;
  1217. #endif
  1218. }
  1219. else
  1220. {
  1221. //final labeling using segmentation
  1222. Matrix regions;
  1223. //showImage(img);
  1224. int regionNumber = segmentation->segRegions ( img, regions );
  1225. cout << "regions: " << regionNumber << endl;
  1226. int dSize = forest[0][0].dist.size();
  1227. vector<vector<double> > regionProbs ( regionNumber, vector<double> ( dSize, 0.0 ) );
  1228. vector<int> bestlabels ( regionNumber, 0 );
  1229. for ( int y = 0; y < img.height(); y++ )
  1230. {
  1231. for ( int x = 0; x < img.width(); x++ )
  1232. {
  1233. int cregion = regions ( x, y );
  1234. for ( int d = 0; d < dSize; d++ )
  1235. {
  1236. regionProbs[cregion][d] += getMeanProb ( x, y, d, currentfeats );
  1237. }
  1238. }
  1239. }
  1240. for ( int r = 0; r < regionNumber; r++ )
  1241. {
  1242. double maxval = regionProbs[r][0];
  1243. bestlabels[r] = 0;
  1244. for ( int d = 1; d < dSize; d++ )
  1245. {
  1246. if ( maxval < regionProbs[r][d] )
  1247. {
  1248. maxval = regionProbs[r][d];
  1249. bestlabels[r] = d;
  1250. }
  1251. }
  1252. bestlabels[r] = labelmapback[bestlabels[r]];
  1253. }
  1254. for ( int y = 0; y < img.height(); y++ )
  1255. {
  1256. for ( int x = 0; x < img.width(); x++ )
  1257. {
  1258. segresult.setPixel ( x, y, bestlabels[regions ( x,y ) ] );
  1259. }
  1260. }
  1261. #define WRITEREGIONS
  1262. #ifdef WRITEREGIONS
  1263. RegionGraph rg;
  1264. segmentation->getGraphRepresentation ( img, regions, rg );
  1265. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1266. {
  1267. rg[pos]->setProbs ( regionProbs[pos] );
  1268. }
  1269. std::string s;
  1270. std::stringstream out;
  1271. std::vector< std::string > list;
  1272. StringTools::split ( Globals::getCurrentImgFN (), '/', list );
  1273. out << "rgout/" << list.back() << ".graph";
  1274. string writefile = out.str();
  1275. rg.write ( writefile );
  1276. #endif
  1277. }
  1278. cout << "segmentation finished" << endl;
  1279. }
  1280. void SemSegContextTree::store ( std::ostream & os, int format ) const
  1281. {
  1282. os << nbTrees << endl;
  1283. classnames.store ( os );
  1284. map<int, int>::const_iterator it;
  1285. os << labelmap.size() << endl;
  1286. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1287. os << ( *it ).first << " " << ( *it ).second << endl;
  1288. os << labelmapback.size() << endl;
  1289. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1290. os << ( *it ).first << " " << ( *it ).second << endl;
  1291. int trees = forest.size();
  1292. os << trees << endl;
  1293. for ( int t = 0; t < trees; t++ )
  1294. {
  1295. int nodes = forest[t].size();
  1296. os << nodes << endl;
  1297. for ( int n = 0; n < nodes; n++ )
  1298. {
  1299. 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;
  1300. os << forest[t][n].dist << endl;
  1301. if ( forest[t][n].feat == NULL )
  1302. os << -1 << endl;
  1303. else
  1304. {
  1305. os << forest[t][n].feat->getOps() << endl;
  1306. forest[t][n].feat->store ( os );
  1307. }
  1308. }
  1309. }
  1310. os << channelType.size() << endl;
  1311. for ( int i = 0; i < channelType.size(); i++ )
  1312. {
  1313. os << channelType[i] << " ";
  1314. }
  1315. os << endl;
  1316. os << integralMap.size() << endl;
  1317. for ( int i = 0; i < integralMap.size(); i++ )
  1318. {
  1319. os << integralMap[i].first << " " << integralMap[i].second << endl;
  1320. }
  1321. os << rawChannels << endl;
  1322. }
  1323. void SemSegContextTree::restore ( std::istream & is, int format )
  1324. {
  1325. is >> nbTrees;
  1326. classnames.restore ( is );
  1327. int lsize;
  1328. is >> lsize;
  1329. labelmap.clear();
  1330. for ( int l = 0; l < lsize; l++ )
  1331. {
  1332. int first, second;
  1333. is >> first;
  1334. is >> second;
  1335. labelmap[first] = second;
  1336. }
  1337. is >> lsize;
  1338. labelmapback.clear();
  1339. for ( int l = 0; l < lsize; l++ )
  1340. {
  1341. int first, second;
  1342. is >> first;
  1343. is >> second;
  1344. labelmapback[first] = second;
  1345. }
  1346. int trees;
  1347. is >> trees;
  1348. forest.clear();
  1349. for ( int t = 0; t < trees; t++ )
  1350. {
  1351. vector<TreeNode> tmptree;
  1352. forest.push_back ( tmptree );
  1353. int nodes;
  1354. is >> nodes;
  1355. //cout << "nodes: " << nodes << endl;
  1356. for ( int n = 0; n < nodes; n++ )
  1357. {
  1358. TreeNode tmpnode;
  1359. forest[t].push_back ( tmpnode );
  1360. is >> forest[t][n].left;
  1361. is >> forest[t][n].right;
  1362. is >> forest[t][n].decision;
  1363. is >> forest[t][n].isleaf;
  1364. is >> forest[t][n].depth;
  1365. is >> forest[t][n].featcounter;
  1366. is >> forest[t][n].nodeNumber;
  1367. is >> forest[t][n].dist;
  1368. int feattype;
  1369. is >> feattype;
  1370. assert ( feattype < NBOPERATIONS );
  1371. forest[t][n].feat = NULL;
  1372. if ( feattype >= 0 )
  1373. {
  1374. for ( uint o = 0; o < ops.size(); o++ )
  1375. {
  1376. for ( uint o2 = 0; o2 < ops[o].size(); o2++ )
  1377. {
  1378. if ( forest[t][n].feat == NULL )
  1379. {
  1380. for ( uint c = 0; c < ops[o].size(); c++ )
  1381. {
  1382. if ( ops[o][o2]->getOps() == feattype )
  1383. {
  1384. forest[t][n].feat = ops[o][o2]->clone();
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. assert ( forest[t][n].feat != NULL );
  1392. forest[t][n].feat->restore ( is );
  1393. }
  1394. }
  1395. }
  1396. channelType.clear();
  1397. int ctsize;
  1398. is >> ctsize;
  1399. for ( int i = 0; i < ctsize; i++ )
  1400. {
  1401. int tmp;
  1402. is >> tmp;
  1403. channelType.push_back ( tmp );
  1404. }
  1405. integralMap.clear();
  1406. int iMapSize;
  1407. is >> iMapSize;
  1408. for ( int i = 0; i < iMapSize; i++ )
  1409. {
  1410. int first;
  1411. int second;
  1412. is >> first;
  1413. is >> second;
  1414. integralMap.push_back ( pair<int, int> ( first, second ) );
  1415. }
  1416. is >> rawChannels;
  1417. }