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