SemSegContextTree.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 "objrec/segmentation/RSMeanShift.h"
  8. #include "objrec/segmentation/RSGraphBased.h"
  9. #include "core/basics/numerictools.h"
  10. #include <omp.h>
  11. #include <iostream>
  12. #define BOUND(x,min,max) (((x)<(min))?(min):((x)>(max)?(max):(x)))
  13. #undef LOCALFEATS
  14. //#define LOCALFEATS
  15. using namespace OBJREC;
  16. using namespace std;
  17. using namespace NICE;
  18. class Minus:public Operation
  19. {
  20. public:
  21. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  22. {
  23. int xsize = feats.width();
  24. int ysize = feats.height();
  25. double v1 = feats.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),channel1);
  26. double v2 = feats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),channel2);
  27. return v1-v2;
  28. }
  29. virtual Operation* clone()
  30. {
  31. return new Minus();
  32. }
  33. virtual string writeInfos()
  34. {
  35. return "Minus";
  36. }
  37. };
  38. class MinusAbs:public Operation
  39. {
  40. public:
  41. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  42. {
  43. int xsize = feats.width();
  44. int ysize = feats.height();
  45. double v1 = feats.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),channel1);
  46. double v2 = feats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),channel2);
  47. return abs(v1-v2);
  48. }
  49. virtual Operation* clone()
  50. {
  51. return new MinusAbs();
  52. };
  53. virtual string writeInfos()
  54. {
  55. return "MinusAbs";
  56. }
  57. };
  58. class Addition:public Operation
  59. {
  60. public:
  61. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  62. {
  63. int xsize = feats.width();
  64. int ysize = feats.height();
  65. double v1 = feats.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),channel1);
  66. double v2 = feats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),channel2);
  67. return v1+v2;
  68. }
  69. virtual Operation* clone()
  70. {
  71. return new Addition();
  72. }
  73. virtual string writeInfos()
  74. {
  75. return "Addition";
  76. }
  77. };
  78. class Only1:public Operation
  79. {
  80. public:
  81. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  82. {
  83. int xsize = feats.width();
  84. int ysize = feats.height();
  85. double v1 = feats.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),channel1);
  86. return v1;
  87. }
  88. virtual Operation* clone()
  89. {
  90. return new Only1();
  91. }
  92. virtual string writeInfos()
  93. {
  94. return "Only1";
  95. }
  96. };
  97. class ContextMinus:public Operation
  98. {
  99. public:
  100. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  101. {
  102. int xsize = feats.width();
  103. int ysize = feats.height();
  104. double v1 = tree[cfeats[BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)]].dist[channel1];
  105. double v2 = tree[cfeats[BOUND(x+x2,0,xsize-1)][BOUND(y+y2,0,ysize-1)]].dist[channel2];
  106. return v1-v2;
  107. }
  108. virtual Operation* clone()
  109. {
  110. return new ContextMinus();
  111. }
  112. virtual string writeInfos()
  113. {
  114. return "ContextMinus";
  115. }
  116. };
  117. class ContextMinusAbs:public Operation
  118. {
  119. public:
  120. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  121. {
  122. int xsize = feats.width();
  123. int ysize = feats.height();
  124. double v1 = tree[cfeats[BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)]].dist[channel1];
  125. double v2 = tree[cfeats[BOUND(x+x2,0,xsize-1)][BOUND(y+y2,0,ysize-1)]].dist[channel2];
  126. return abs(v1-v2);
  127. }
  128. virtual Operation* clone()
  129. {
  130. return new ContextMinusAbs();
  131. }
  132. virtual string writeInfos()
  133. {
  134. return "ContextMinusAbs";
  135. }
  136. };
  137. class ContextAddition:public Operation
  138. {
  139. public:
  140. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  141. {
  142. int xsize = feats.width();
  143. int ysize = feats.height();
  144. double v1 = tree[cfeats[BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)]].dist[channel1];
  145. double v2 = tree[cfeats[BOUND(x+x2,0,xsize-1)][BOUND(y+y2,0,ysize-1)]].dist[channel2];
  146. return v1+v2;
  147. }
  148. virtual Operation* clone()
  149. {
  150. return new ContextAddition();
  151. }
  152. virtual string writeInfos()
  153. {
  154. return "ContextAddition";
  155. }
  156. };
  157. class ContextOnly1:public Operation
  158. {
  159. public:
  160. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  161. {
  162. int xsize = feats.width();
  163. int ysize = feats.height();
  164. double v1 = tree[cfeats[BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)]].dist[channel1];
  165. return v1;
  166. }
  167. virtual Operation* clone()
  168. {
  169. return new ContextOnly1();
  170. }
  171. virtual string writeInfos()
  172. {
  173. return "ContextOnly1";
  174. }
  175. };
  176. // uses mean of classification in window given by (x1,y1) (x2,y2)
  177. class IntegralOps:public Operation
  178. {
  179. public:
  180. virtual void set(int _x1, int _y1, int _x2, int _y2, int _channel1, int _channel2)
  181. {
  182. x1 = min(_x1,_x2);
  183. y1 = min(_y1,_y2);
  184. x2 = max(_x1,_x2);
  185. y2 = max(_y1,_y2);
  186. channel1 = _channel1;
  187. channel2 = _channel2;
  188. }
  189. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, const int &x, const int &y)
  190. {
  191. MultiChannelImageT<double> intImg;
  192. return computeMean(intImg,x1,y1,x2,y2,channel1);
  193. }
  194. virtual Operation* clone()
  195. {
  196. return new IntegralOps();
  197. }
  198. virtual string writeInfos()
  199. {
  200. return "IntegralOps";
  201. }
  202. inline double computeMean(const NICE::MultiChannelImageT<double> &intImg, int &uLx, int &uLy, int &lRx, int &lRy, int &chan)
  203. {
  204. double val1 = intImg.get(uLx,uLy, chan);
  205. double val2 = intImg.get(lRx,uLy, chan);
  206. double val3 = intImg.get(uLx,lRy, chan);
  207. double val4 = intImg.get(lRx,lRy, chan);
  208. double area = (lRx-uLx)*(lRy-uLy);
  209. return (val1+val4-val2-val3)/area;
  210. }
  211. };
  212. //uses mean of Integral image given by x1, y1 with current pixel as center
  213. class IntegralCenteredOps:public IntegralOps
  214. {
  215. public:
  216. virtual void set(int _x1, int _y1, int _x2, int _y2, int _channel1, int _channel2)
  217. {
  218. x1 = _x1;
  219. y1 = _y1;
  220. x2 = -x1;
  221. y2 = -y1;
  222. }
  223. virtual Operation* clone()
  224. {
  225. return new IntegralCenteredOps();
  226. }
  227. virtual string writeInfos()
  228. {
  229. return "IntegralCenteredOps";
  230. }
  231. };
  232. //uses different of mean of Integral image given by two windows, where (x1,y1) is the width and height of window1 and (x2,y2) of window 2
  233. //TODO von Integral ops ableiten
  234. SemSegContextTree::SemSegContextTree( const Config *conf, const MultiDataset *md )
  235. : SemanticSegmentation ( conf, &(md->getClassNames("train")) )
  236. {
  237. this->conf = conf;
  238. string section = "SSContextTree";
  239. lfcw = new LFColorWeijer(conf);
  240. grid = conf->gI(section, "grid", 10 );
  241. maxSamples = conf->gI(section, "max_samples", 2000);
  242. minFeats = conf->gI(section, "min_feats", 50 );
  243. maxDepth = conf->gI(section, "max_depth", 10 );
  244. windowSize = conf->gI(section, "window_size", 16);
  245. featsPerSplit = conf->gI(section, "feats_per_split", 200);
  246. useShannonEntropy = conf->gB(section, "use_shannon_entropy", true);
  247. string segmentationtype = conf->gS(section, "segmentation_type", "meanshift");
  248. useGaussian = conf->gB(section, "use_gaussian", true);
  249. pixelWiseLabeling = false;
  250. if(segmentationtype == "meanshift")
  251. segmentation = new RSMeanShift(conf);
  252. else if (segmentationtype == "none")
  253. {
  254. segmentation = NULL;
  255. pixelWiseLabeling = true;
  256. }
  257. else if (segmentationtype == "felzenszwalb")
  258. segmentation = new RSGraphBased(conf);
  259. else
  260. throw("no valid segmenation_type\n please choose between none, meanshift and felzenszwalb\n");
  261. ftypes = conf->gI(section, "features", 2);;
  262. ops.push_back(new Minus());
  263. ops.push_back(new MinusAbs());
  264. ops.push_back(new Addition());
  265. ops.push_back(new Only1());
  266. cops.push_back(new ContextMinus());
  267. cops.push_back(new ContextMinusAbs());
  268. cops.push_back(new ContextAddition());
  269. cops.push_back(new ContextOnly1());
  270. classnames = md->getClassNames ( "train" );
  271. ///////////////////////////////////
  272. // Train Segmentation Context Trees
  273. ///////////////////////////////////
  274. train ( md );
  275. }
  276. SemSegContextTree::~SemSegContextTree()
  277. {
  278. }
  279. void SemSegContextTree::getBestSplit(const vector<MultiChannelImageT<double> > &feats, vector<vector<vector<int> > > &currentfeats,const vector<vector<vector<int> > > &labels, int node, Operation *&splitop, double &splitval)
  280. {
  281. int imgCount = 0, featdim = 0;
  282. try
  283. {
  284. imgCount = (int)feats.size();
  285. featdim = feats[0].channels();
  286. }
  287. catch(Exception)
  288. {
  289. cerr << "no features computed?" << endl;
  290. }
  291. double bestig = -numeric_limits< double >::max();
  292. splitop = NULL;
  293. splitval = -1.0;
  294. set<vector<int> >selFeats;
  295. map<int,int> e;
  296. int featcounter = 0;
  297. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  298. {
  299. int xsize = (int)currentfeats[iCounter].size();
  300. int ysize = (int)currentfeats[iCounter][0].size();
  301. for(int x = 0; x < xsize; x++)
  302. {
  303. for(int y = 0; y < ysize; y++)
  304. {
  305. if(currentfeats[iCounter][x][y] == node)
  306. {
  307. featcounter++;
  308. }
  309. }
  310. }
  311. }
  312. if(featcounter < minFeats)
  313. {
  314. cout << "only " << featcounter << " feats in current node -> it's a leaf" << endl;
  315. return;
  316. }
  317. vector<double> fraction(a.size(),0.0);
  318. for(uint i = 0; i < fraction.size(); i++)
  319. {
  320. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  321. fraction[i] = 0;
  322. else
  323. fraction[i] = ((double)maxSamples)/((double)featcounter*a[i]*a.size());
  324. //cout << "fraction["<<i<<"]: "<< fraction[i] << " a[" << i << "]: " << a[i] << endl;
  325. }
  326. //cout << "a.size(): " << a.size() << endl;
  327. //getchar();
  328. featcounter = 0;
  329. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  330. {
  331. int xsize = (int)currentfeats[iCounter].size();
  332. int ysize = (int)currentfeats[iCounter][0].size();
  333. for(int x = 0; x < xsize; x++)
  334. {
  335. for(int y = 0; y < ysize; y++)
  336. {
  337. if(currentfeats[iCounter][x][y] == node)
  338. {
  339. int cn = labels[iCounter][x][y];
  340. double randD = (double)rand()/(double)RAND_MAX;
  341. if(randD < fraction[labelmap[cn]])
  342. {
  343. vector<int> tmp(3,0);
  344. tmp[0] = iCounter;
  345. tmp[1] = x;
  346. tmp[2] = y;
  347. featcounter++;
  348. selFeats.insert(tmp);
  349. e[cn]++;
  350. }
  351. }
  352. }
  353. }
  354. }
  355. //cout << "size: " << selFeats.size() << endl;
  356. //getchar();
  357. map<int,int>::iterator mapit;
  358. double globent = 0.0;
  359. for ( mapit=e.begin() ; mapit != e.end(); mapit++ )
  360. {
  361. //cout << "class: " << mapit->first << ": " << mapit->second << endl;
  362. double p = (double)(*mapit).second/(double)featcounter;
  363. globent += p*log2(p);
  364. }
  365. globent = -globent;
  366. if(globent < 0.5)
  367. {
  368. cout << "globent to small: " << globent << endl;
  369. return;
  370. }
  371. int classes = (int)labelmap.size();
  372. featsel.clear();
  373. for(int i = 0; i < featsPerSplit; i++)
  374. {
  375. int x1, x2, y1, y2;
  376. if(useGaussian)
  377. {
  378. double sigma = (double)windowSize/2.0;
  379. x1 = randGaussDouble(sigma)*(double)windowSize;
  380. x2 = randGaussDouble(sigma)*(double)windowSize;
  381. y1 = randGaussDouble(sigma)*(double)windowSize;
  382. y2 = randGaussDouble(sigma)*(double)windowSize;
  383. }
  384. else
  385. {
  386. x1 = (int)((double)rand()/(double)RAND_MAX*(double)windowSize)-windowSize/2;
  387. x2 = (int)((double)rand()/(double)RAND_MAX*(double)windowSize)-windowSize/2;
  388. y1 = (int)((double)rand()/(double)RAND_MAX*(double)windowSize)-windowSize/2;
  389. y2 = (int)((double)rand()/(double)RAND_MAX*(double)windowSize)-windowSize/2;
  390. }
  391. int ft = (int)((double)rand()/(double)RAND_MAX*(double)ftypes);
  392. if(ft == 0)
  393. {
  394. int f1 = (int)((double)rand()/(double)RAND_MAX*(double)featdim);
  395. int f2 = (int)((double)rand()/(double)RAND_MAX*(double)featdim);
  396. int o = (int)((double)rand()/(double)RAND_MAX*(double)ops.size());
  397. Operation *op = ops[o]->clone();
  398. op->set(x1,y1,x2,y2,f1,f2);
  399. featsel.push_back(op);
  400. }
  401. else if(ft == 1)
  402. {
  403. int f1 = (int)((double)rand()/(double)RAND_MAX*(double)classes);
  404. int f2 = (int)((double)rand()/(double)RAND_MAX*(double)classes);
  405. int o = (int)((double)rand()/(double)RAND_MAX*(double)cops.size());
  406. Operation *op = cops[o]->clone();
  407. op->set(x1,y1,x2,y2,f1,f2);
  408. featsel.push_back(op);
  409. }
  410. }
  411. #pragma omp parallel for private(mapit)
  412. for(int f = 0; f < featsPerSplit; f++)
  413. {
  414. double l_bestig = -numeric_limits< double >::max();
  415. double l_splitval = -1.0;
  416. set<vector<int> >::iterator it;
  417. vector<double> vals;
  418. for ( it=selFeats.begin() ; it != selFeats.end(); it++ )
  419. {
  420. vals.push_back(featsel[f]->getVal(feats[(*it)[0]],currentfeats[(*it)[0]],tree,(*it)[1], (*it)[2]));
  421. }
  422. int counter = 0;
  423. for ( it=selFeats.begin() ; it != selFeats.end(); it++ , counter++)
  424. {
  425. set<vector<int> >::iterator it2;
  426. double val = vals[counter];
  427. map<int,int> eL, eR;
  428. int counterL = 0, counterR = 0;
  429. int counter2 = 0;
  430. for ( it2=selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  431. {
  432. int cn = labels[(*it2)[0]][(*it2)[1]][(*it2)[2]];
  433. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  434. if(vals[counter2] < val)
  435. {
  436. //left entropie:
  437. eL[cn] = eL[cn]+1;
  438. counterL++;
  439. }
  440. else
  441. {
  442. //right entropie:
  443. eR[cn] = eR[cn]+1;
  444. counterR++;
  445. }
  446. }
  447. double leftent = 0.0;
  448. for ( mapit=eL.begin() ; mapit != eL.end(); mapit++ )
  449. {
  450. double p = (double)(*mapit).second/(double)counterL;
  451. leftent -= p*log2(p);
  452. }
  453. double rightent = 0.0;
  454. for ( mapit=eR.begin() ; mapit != eR.end(); mapit++ )
  455. {
  456. double p = (double)(*mapit).second/(double)counterR;
  457. rightent -= p*log2(p);
  458. }
  459. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  460. double pl = (double)counterL/(double)(counterL+counterR);
  461. double ig = globent - (1.0-pl) * rightent - pl*leftent;
  462. //double ig = globent - rightent - leftent;
  463. if(useShannonEntropy)
  464. {
  465. double esplit = - ( pl*log(pl) + (1-pl)*log(1-pl) );
  466. ig = 2*ig / ( globent + esplit );
  467. }
  468. if(ig > l_bestig)
  469. {
  470. l_bestig = ig;
  471. l_splitval = val;
  472. }
  473. }
  474. #pragma omp critical
  475. {
  476. //cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  477. //cout << "globent: " << globent << " l_bestig " << l_bestig << " f: " << p << " l_splitval: " << l_splitval << endl;
  478. //cout << "p: " << featsubset[f] << endl;
  479. if(l_bestig > bestig)
  480. {
  481. bestig = l_bestig;
  482. splitop = featsel[f];
  483. splitval = l_splitval;
  484. }
  485. }
  486. }
  487. //splitop->writeInfos();
  488. //cout<< "ig: " << bestig << endl;
  489. /*for(int i = 0; i < featsPerSplit; i++)
  490. {
  491. if(featsel[i] != splitop)
  492. delete featsel[i];
  493. }*/
  494. #ifdef debug
  495. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  496. #endif
  497. }
  498. void SemSegContextTree::train ( const MultiDataset *md )
  499. {
  500. const LabeledSet train = * ( *md ) ["train"];
  501. const LabeledSet *trainp = &train;
  502. ProgressBar pb ( "compute feats" );
  503. pb.show();
  504. //TODO: Speichefresser!, lohnt sich sparse?
  505. vector<MultiChannelImageT<double> > allfeats;
  506. vector<vector<vector<int> > > currentfeats;
  507. vector<vector<vector<int> > > labels;
  508. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  509. if ( forbidden_classes_s == "" )
  510. {
  511. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  512. }
  513. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  514. int imgcounter = 0;
  515. LOOP_ALL_S ( *trainp )
  516. {
  517. EACH_INFO ( classno,info );
  518. NICE::ColorImage img;
  519. std::string currentFile = info.img();
  520. CachedExample *ce = new CachedExample ( currentFile );
  521. const LocalizationResult *locResult = info.localization();
  522. if ( locResult->size() <= 0 )
  523. {
  524. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  525. currentFile.c_str() );
  526. continue;
  527. }
  528. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  529. int xsize, ysize;
  530. ce->getImageSize ( xsize, ysize );
  531. vector<vector<int> > tmp = vector<vector<int> >(xsize, vector<int>(ysize,0));
  532. currentfeats.push_back(tmp);
  533. labels.push_back(tmp);
  534. try {
  535. img = ColorImage(currentFile);
  536. } catch (Exception) {
  537. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  538. continue;
  539. }
  540. Globals::setCurrentImgFN ( currentFile );
  541. //TODO: resize image?!
  542. MultiChannelImageT<double> feats;
  543. allfeats.push_back(feats);
  544. #ifdef LOCALFEATS
  545. lfcw->getFeats(img, allfeats[imgcounter]);
  546. #else
  547. allfeats[imgcounter].reInit(xsize, ysize, 3, true);
  548. for(int x = 0; x < xsize; x++)
  549. {
  550. for(int y = 0; y < ysize; y++)
  551. {
  552. for(int r = 0; r < 3; r++)
  553. {
  554. allfeats[imgcounter].set(x,y,img.getPixel(x,y,r),r);
  555. }
  556. }
  557. }
  558. #endif
  559. // getting groundtruth
  560. NICE::Image pixelLabels (xsize, ysize);
  561. pixelLabels.set(0);
  562. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  563. for(int x = 0; x < xsize; x++)
  564. {
  565. for(int y = 0; y < ysize; y++)
  566. {
  567. classno = pixelLabels.getPixel(x, y);
  568. labels[imgcounter][x][y] = classno;
  569. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  570. continue;
  571. labelcounter[classno]++;
  572. }
  573. }
  574. imgcounter++;
  575. pb.update ( trainp->count());
  576. delete ce;
  577. }
  578. pb.hide();
  579. map<int,int>::iterator mapit;
  580. int classes = 0;
  581. for(mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  582. {
  583. labelmap[mapit->first] = classes;
  584. labelmapback[classes] = mapit->first;
  585. classes++;
  586. }
  587. //balancing
  588. int featcounter = 0;
  589. a = vector<double>(classes,0.0);
  590. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  591. {
  592. int xsize = (int)currentfeats[iCounter].size();
  593. int ysize = (int)currentfeats[iCounter][0].size();
  594. for(int x = 0; x < xsize; x++)
  595. {
  596. for(int y = 0; y < ysize; y++)
  597. {
  598. featcounter++;
  599. int cn = labels[iCounter][x][y];
  600. a[labelmap[cn]] ++;
  601. }
  602. }
  603. }
  604. for(int i = 0; i < (int)a.size(); i++)
  605. {
  606. a[i] /= (double)featcounter;
  607. }
  608. #ifdef DEBUG
  609. for(int i = 0; i < (int)a.size(); i++)
  610. {
  611. cout << "a["<<i<<"]: " << a[i] << endl;
  612. }
  613. cout << "a.size: " << a.size() << endl;
  614. #endif
  615. tree.push_back(TreeNode());
  616. tree[0].dist = vector<double>(classes,0.0);
  617. int depth = 0;
  618. tree[0].depth = depth;
  619. int startnode = 0;
  620. bool allleaf = false;
  621. //int baseFeatSize = allfeats[0].size();
  622. while(!allleaf && depth < maxDepth)
  623. {
  624. allleaf = true;
  625. //TODO vielleicht parallel wenn nächste schleife trotzdem noch parallelsiert würde, die hat mehr gewicht
  626. int t = (int) tree.size();
  627. int s = startnode;
  628. startnode = t;
  629. vector<vector<vector<int> > > lastfeats = currentfeats;
  630. vector<MultiChannelImageT<double> > integralImgs;
  631. //#pragma omp parallel for
  632. for(int i = s; i < t; i++)
  633. {
  634. if(!tree[i].isleaf && tree[i].left < 0)
  635. {
  636. Operation *splitfeat = NULL;
  637. double splitval;
  638. getBestSplit(allfeats, lastfeats,labels, i, splitfeat, splitval);
  639. tree[i].feat = splitfeat;
  640. tree[i].decision = splitval;
  641. if(splitfeat != NULL)
  642. {
  643. allleaf = false;
  644. int left = tree.size();
  645. tree.push_back(TreeNode());
  646. tree.push_back(TreeNode());
  647. int right = left+1;
  648. tree[i].left = left;
  649. tree[i].right = right;
  650. tree[left].dist = vector<double>(classes, 0.0);
  651. tree[right].dist = vector<double>(classes, 0.0);
  652. tree[left].depth = depth+1;
  653. tree[right].depth = depth+1;
  654. #pragma omp parallel for
  655. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  656. {
  657. int xsize = currentfeats[iCounter].size();
  658. int ysize = currentfeats[iCounter][0].size();
  659. for(int x = 0; x < xsize; x++)
  660. {
  661. for(int y = 0; y < ysize; y++)
  662. {
  663. if(currentfeats[iCounter][x][y] == i)
  664. {
  665. double val = splitfeat->getVal(allfeats[iCounter],lastfeats[iCounter],tree,x,y);
  666. if(val < splitval)
  667. {
  668. currentfeats[iCounter][x][y] = left;
  669. tree[left].dist[labelmap[labels[iCounter][x][y]]]++;
  670. }
  671. else
  672. {
  673. currentfeats[iCounter][x][y] = right;
  674. tree[right].dist[labelmap[labels[iCounter][x][y]]]++;
  675. }
  676. }
  677. }
  678. }
  679. }
  680. double lcounter = 0.0, rcounter = 0.0;
  681. for(uint d = 0; d < tree[left].dist.size(); d++)
  682. {
  683. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  684. {
  685. tree[left].dist[d] = 0;
  686. tree[right].dist[d] = 0;
  687. }
  688. else
  689. {
  690. tree[left].dist[d]/=a[d];
  691. lcounter +=tree[left].dist[d];
  692. tree[right].dist[d]/=a[d];
  693. rcounter +=tree[right].dist[d];
  694. }
  695. }
  696. if(lcounter <= 0 || rcounter <= 0)
  697. {
  698. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  699. cout << "splitval: " << splitval << endl;
  700. assert(lcounter > 0 && rcounter > 0);
  701. }
  702. for(uint d = 0; d < tree[left].dist.size(); d++)
  703. {
  704. tree[left].dist[d]/=lcounter;
  705. tree[right].dist[d]/=rcounter;
  706. }
  707. }
  708. else
  709. {
  710. tree[i].isleaf = true;
  711. }
  712. }
  713. }
  714. //TODO: features neu berechnen!
  715. #if 1
  716. //compute integral image
  717. int channels = (int)labelmap.size();
  718. if(integralImgs.size() == 0)
  719. {
  720. for(int i = 0; i < imgcounter; i++)
  721. {
  722. int xsize = allfeats[i].width();
  723. int ysize = allfeats[i].height();
  724. integralImgs.push_back(MultiChannelImageT<double>(xsize, ysize, channels));
  725. }
  726. }
  727. for(int i = 0; i < imgcounter; i++)
  728. {
  729. int xsize = allfeats[i].width();
  730. int ysize = allfeats[i].height();
  731. for(int c = 0; c < channels; c++)
  732. {
  733. integralImgs[i].set(0,0,tree[currentfeats[i][0][0]].dist[c], c);
  734. //first column
  735. for(int y = 1; y < ysize; y++)
  736. {
  737. integralImgs[i].set(0,0,tree[currentfeats[i][0][y]].dist[c]+integralImgs[i].get(0,y,c), c);
  738. }
  739. //first row
  740. for(int x = 1; x < xsize; x++)
  741. {
  742. integralImgs[i].set(0,0,tree[currentfeats[i][x][0]].dist[c]+integralImgs[i].get(x,0,c), c);
  743. }
  744. //rest
  745. for(int y = 1; y < ysize; y++)
  746. {
  747. for(int x = 1; x < xsize; x++)
  748. {
  749. double val = tree[currentfeats[i][x][y]].dist[c]+integralImgs[i].get(x,y-1,c)+integralImgs[i].get(x-1,y,c)-integralImgs[i].get(x-1,y-1,c);
  750. integralImgs[i].set(0, 0, val, c);
  751. }
  752. }
  753. }
  754. }
  755. #endif
  756. depth++;
  757. #ifdef DEBUG
  758. cout << "depth: " << depth << endl;
  759. #endif
  760. }
  761. #ifdef DEBUG
  762. int t = (int) tree.size();
  763. for(int i = 0; i < t; i++)
  764. {
  765. printf("tree[%i]: left: %i, right: %i", i, tree[i].left, tree[i].right);
  766. if(!tree[i].isleaf && tree[i].left != -1)
  767. cout << ", feat: " << tree[i].feat->writeInfos() << " ";
  768. for(int d = 0; d < (int)tree[i].dist.size(); d++)
  769. {
  770. cout << " " << tree[i].dist[d];
  771. }
  772. cout << endl;
  773. }
  774. #endif
  775. }
  776. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult,NICE::MultiChannelImageT<double> & probabilities )
  777. {
  778. int xsize;
  779. int ysize;
  780. ce->getImageSize ( xsize, ysize );
  781. int numClasses = classNames->numClasses();
  782. fprintf (stderr, "ContextTree classification !\n");
  783. probabilities.reInit ( xsize, ysize, numClasses, true );
  784. probabilities.setAll ( 0 );
  785. NICE::ColorImage img;
  786. std::string currentFile = Globals::getCurrentImgFN();
  787. try {
  788. img = ColorImage(currentFile);
  789. } catch (Exception) {
  790. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  791. return;
  792. }
  793. //TODO: resize image?!
  794. MultiChannelImageT<double> feats;
  795. #ifdef LOCALFEATS
  796. lfcw->getFeats(img, feats);
  797. #else
  798. feats.reInit (xsize, ysize, 3, true);
  799. for(int x = 0; x < xsize; x++)
  800. {
  801. for(int y = 0; y < ysize; y++)
  802. {
  803. for(int r = 0; r < 3; r++)
  804. {
  805. feats.set(x,y,img.getPixel(x,y,r),r);
  806. }
  807. }
  808. }
  809. #endif
  810. bool allleaf = false;
  811. vector<vector<int> > currentfeats = vector<vector<int> >(xsize, vector<int>(ysize,0));
  812. int depth = 0;
  813. while(!allleaf)
  814. {
  815. allleaf = true;
  816. //TODO vielleicht parallel wenn nächste schleife auch noch parallelsiert würde, die hat mehr gewicht
  817. //#pragma omp parallel for
  818. vector<vector<int> > lastfeats = currentfeats;
  819. for(int x = 0; x < xsize; x++)
  820. {
  821. for(int y = 0; y < ysize; y++)
  822. {
  823. int t = currentfeats[x][y];
  824. if(tree[t].left > 0)
  825. {
  826. allleaf = false;
  827. double val = tree[t].feat->getVal(feats,lastfeats,tree,x,y);
  828. if(val < tree[t].decision)
  829. {
  830. currentfeats[x][y] = tree[t].left;
  831. }
  832. else
  833. {
  834. currentfeats[x][y] = tree[t].right;
  835. }
  836. }
  837. }
  838. }
  839. //TODO: features neu berechnen! analog zum training
  840. depth++;
  841. }
  842. if(pixelWiseLabeling)
  843. {
  844. //finales labeln:
  845. long int offset = 0;
  846. for(int x = 0; x < xsize; x++)
  847. {
  848. for(int y = 0; y < ysize; y++,offset++)
  849. {
  850. int t = currentfeats[x][y];
  851. double maxvalue = - numeric_limits<double>::max(); //TODO: das muss nur pro knoten gemacht werden, nicht pro pixel
  852. int maxindex = 0;
  853. for(uint i = 0; i < tree[i].dist.size(); i++)
  854. {
  855. probabilities.data[labelmapback[i]][offset] = tree[t].dist[i];
  856. if(tree[t].dist[i] > maxvalue)
  857. {
  858. maxvalue = tree[t].dist[i];
  859. maxindex = labelmapback[i];
  860. }
  861. segresult.setPixel(x,y,maxindex);
  862. }
  863. }
  864. }
  865. }
  866. else
  867. {
  868. //final labeling using segmentation
  869. //TODO: segmentation
  870. Matrix regions;
  871. int regionNumber = segmentation->segRegions(img,regions);
  872. cout << "regions: " << regionNumber << endl;
  873. int dSize = (int)labelmap.size();
  874. vector<vector<double> > regionProbs(regionNumber, vector<double>(dSize,0.0));
  875. vector<int> bestlabels(regionNumber, 0);
  876. for(int y = 0; y < img.height(); y++)
  877. {
  878. for(int x = 0; x < img.width(); x++)
  879. {
  880. int cnode = currentfeats[x][y];
  881. int cregion = regions(x,y);
  882. for(int d = 0; d < dSize; d++)
  883. {
  884. regionProbs[cregion][d]+=tree[cnode].dist[d];
  885. }
  886. }
  887. }
  888. for(int r = 0; r < regionNumber; r++)
  889. {
  890. double maxval = regionProbs[r][0];
  891. for(int d = 1; d < dSize; d++)
  892. {
  893. if(maxval < regionProbs[r][d])
  894. {
  895. maxval = regionProbs[r][d];
  896. bestlabels[r] = d;
  897. }
  898. }
  899. bestlabels[r] = labelmapback[bestlabels[r]];
  900. }
  901. for(int y = 0; y < img.height(); y++)
  902. {
  903. for(int x = 0; x < img.width(); x++)
  904. {
  905. segresult.setPixel(x,y,bestlabels[regions(x,y)]);
  906. }
  907. }
  908. }
  909. }