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