SemSegContextTree.cpp 48 KB

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