SemSegContextTree.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, 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, MultiChannelImageT<double> &integralImg, const int &x, const int &y)
  190. {
  191. int xsize = feats.width();
  192. int ysize = feats.height();
  193. return computeMean(integralImg,BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),channel1);
  194. }
  195. inline double computeMean(const NICE::MultiChannelImageT<double> &intImg, const int &uLx, const int &uLy, const int &lRx, const int &lRy, const int &chan)
  196. {
  197. double val1 = intImg.get(uLx,uLy, chan);
  198. double val2 = intImg.get(lRx,uLy, chan);
  199. double val3 = intImg.get(uLx,lRy, chan);
  200. double val4 = intImg.get(lRx,lRy, chan);
  201. double area = (lRx-uLx)*(lRy-uLy);
  202. return (val1+val4-val2-val3)/area;
  203. }
  204. virtual Operation* clone()
  205. {
  206. return new IntegralOps();
  207. }
  208. virtual string writeInfos()
  209. {
  210. return "IntegralOps";
  211. }
  212. };
  213. //uses mean of Integral image given by x1, y1 with current pixel as center
  214. class IntegralCenteredOps:public IntegralOps
  215. {
  216. public:
  217. virtual void set(int _x1, int _y1, int _x2, int _y2, int _channel1, int _channel2)
  218. {
  219. x1 = min(_x1,-_x1);
  220. y1 = min(_y1,-_y1);
  221. x2 = -x1;
  222. y2 = -y1;
  223. channel1 = _channel1;
  224. channel2 = _channel2;
  225. }
  226. virtual Operation* clone()
  227. {
  228. return new IntegralCenteredOps();
  229. }
  230. virtual string writeInfos()
  231. {
  232. return "IntegralCenteredOps";
  233. }
  234. };
  235. //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
  236. class BiIntegralCenteredOps:public IntegralOps
  237. {
  238. public:
  239. virtual void set(int _x1, int _y1, int _x2, int _y2, int _channel1, int _channel2)
  240. {
  241. x1 = min(abs(_x1),abs(_x2));
  242. y1 = min(abs(_y1),abs(_y2));
  243. x2 = max(abs(_x1),abs(_x2));
  244. y2 = max(abs(_y1),abs(_y2));
  245. channel1 = _channel1;
  246. channel2 = _channel2;
  247. }
  248. virtual double getVal(const NICE::MultiChannelImageT<double> &feats, const std::vector<std::vector<int> > &cfeats, const std::vector<TreeNode> &tree, MultiChannelImageT<double> &integralImg, const int &x, const int &y)
  249. {
  250. int xsize = feats.width();
  251. int ysize = feats.height();
  252. return computeMean(integralImg,BOUND(x-x1,0,xsize-1),BOUND(y-y1,0,ysize-1),BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),channel1) - computeMean(integralImg,BOUND(x-x2,0,xsize-1),BOUND(y-y2,0,ysize-1),BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),channel1);
  253. }
  254. virtual Operation* clone()
  255. {
  256. return new BiIntegralCenteredOps();
  257. }
  258. virtual string writeInfos()
  259. {
  260. return "BiIntegralCenteredOps";
  261. }
  262. };
  263. SemSegContextTree::SemSegContextTree( const Config *conf, const MultiDataset *md )
  264. : SemanticSegmentation ( conf, &(md->getClassNames("train")) )
  265. {
  266. this->conf = conf;
  267. string section = "SSContextTree";
  268. lfcw = new LFColorWeijer(conf);
  269. grid = conf->gI(section, "grid", 10 );
  270. maxSamples = conf->gI(section, "max_samples", 2000);
  271. minFeats = conf->gI(section, "min_feats", 50 );
  272. maxDepth = conf->gI(section, "max_depth", 10 );
  273. windowSize = conf->gI(section, "window_size", 16);
  274. featsPerSplit = conf->gI(section, "feats_per_split", 200);
  275. useShannonEntropy = conf->gB(section, "use_shannon_entropy", true);
  276. string segmentationtype = conf->gS(section, "segmentation_type", "meanshift");
  277. useGaussian = conf->gB(section, "use_gaussian", true);
  278. if(useGaussian)
  279. throw("there something wrong with using gaussian! first fix it!");
  280. pixelWiseLabeling = false;
  281. if(segmentationtype == "meanshift")
  282. segmentation = new RSMeanShift(conf);
  283. else if (segmentationtype == "none")
  284. {
  285. segmentation = NULL;
  286. pixelWiseLabeling = true;
  287. }
  288. else if (segmentationtype == "felzenszwalb")
  289. segmentation = new RSGraphBased(conf);
  290. else
  291. throw("no valid segmenation_type\n please choose between none, meanshift and felzenszwalb\n");
  292. ftypes = conf->gI(section, "features", 2);;
  293. ops.push_back(new Minus());
  294. ops.push_back(new MinusAbs());
  295. ops.push_back(new Addition());
  296. ops.push_back(new Only1());
  297. cops.push_back(new ContextMinus());
  298. cops.push_back(new ContextMinusAbs());
  299. cops.push_back(new ContextAddition());
  300. cops.push_back(new ContextOnly1());
  301. cops.push_back(new BiIntegralCenteredOps());
  302. cops.push_back(new IntegralCenteredOps());
  303. cops.push_back(new IntegralOps());
  304. classnames = md->getClassNames ( "train" );
  305. ///////////////////////////////////
  306. // Train Segmentation Context Trees
  307. ///////////////////////////////////
  308. train ( md );
  309. }
  310. SemSegContextTree::~SemSegContextTree()
  311. {
  312. }
  313. double SemSegContextTree::getBestSplit(const vector<MultiChannelImageT<double> > &feats, vector<vector<vector<int> > > &currentfeats, vector<MultiChannelImageT<double> > &integralImgs, const vector<vector<vector<int> > > &labels, int node, Operation *&splitop, double &splitval)
  314. {
  315. int imgCount = 0, featdim = 0;
  316. try
  317. {
  318. imgCount = (int)feats.size();
  319. featdim = feats[0].channels();
  320. }
  321. catch(Exception)
  322. {
  323. cerr << "no features computed?" << endl;
  324. }
  325. double bestig = -numeric_limits< double >::max();
  326. splitop = NULL;
  327. splitval = -1.0;
  328. set<vector<int> >selFeats;
  329. map<int,int> e;
  330. int featcounter = 0;
  331. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  332. {
  333. int xsize = (int)currentfeats[iCounter].size();
  334. int ysize = (int)currentfeats[iCounter][0].size();
  335. for(int x = 0; x < xsize; x++)
  336. {
  337. for(int y = 0; y < ysize; y++)
  338. {
  339. if(currentfeats[iCounter][x][y] == node)
  340. {
  341. featcounter++;
  342. }
  343. }
  344. }
  345. }
  346. if(featcounter < minFeats)
  347. {
  348. cout << "only " << featcounter << " feats in current node -> it's a leaf" << endl;
  349. return 0.0;
  350. }
  351. vector<double> fraction(a.size(),0.0);
  352. for(uint i = 0; i < fraction.size(); i++)
  353. {
  354. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  355. fraction[i] = 0;
  356. else
  357. fraction[i] = ((double)maxSamples)/((double)featcounter*a[i]*a.size());
  358. //cout << "fraction["<<i<<"]: "<< fraction[i] << " a[" << i << "]: " << a[i] << endl;
  359. }
  360. //cout << "a.size(): " << a.size() << endl;
  361. //getchar();
  362. featcounter = 0;
  363. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  364. {
  365. int xsize = (int)currentfeats[iCounter].size();
  366. int ysize = (int)currentfeats[iCounter][0].size();
  367. for(int x = 0; x < xsize; x++)
  368. {
  369. for(int y = 0; y < ysize; y++)
  370. {
  371. if(currentfeats[iCounter][x][y] == node)
  372. {
  373. int cn = labels[iCounter][x][y];
  374. double randD = (double)rand()/(double)RAND_MAX;
  375. if(randD < fraction[labelmap[cn]])
  376. {
  377. vector<int> tmp(3,0);
  378. tmp[0] = iCounter;
  379. tmp[1] = x;
  380. tmp[2] = y;
  381. featcounter++;
  382. selFeats.insert(tmp);
  383. e[cn]++;
  384. }
  385. }
  386. }
  387. }
  388. }
  389. //cout << "size: " << selFeats.size() << endl;
  390. //getchar();
  391. map<int,int>::iterator mapit;
  392. double globent = 0.0;
  393. for ( mapit=e.begin() ; mapit != e.end(); mapit++ )
  394. {
  395. //cout << "class: " << mapit->first << ": " << mapit->second << endl;
  396. double p = (double)(*mapit).second/(double)featcounter;
  397. globent += p*log2(p);
  398. }
  399. globent = -globent;
  400. if(globent < 0.5)
  401. {
  402. cout << "globent to small: " << globent << endl;
  403. return 0.0;
  404. }
  405. int classes = (int)tree[0].dist.size();
  406. featsel.clear();
  407. for(int i = 0; i < featsPerSplit; i++)
  408. {
  409. int x1, x2, y1, y2;
  410. int ft = (int)((double)rand()/(double)RAND_MAX*(double)ftypes);
  411. int tmpws = windowSize;
  412. if(integralImgs[0].width() == 0)
  413. ft = 0;
  414. if(ft > 0)
  415. {
  416. tmpws *= 2;
  417. }
  418. if(useGaussian)
  419. {
  420. double sigma = (double)tmpws/2.0;
  421. x1 = randGaussDouble(sigma)*(double)tmpws;
  422. x2 = randGaussDouble(sigma)*(double)tmpws;
  423. y1 = randGaussDouble(sigma)*(double)tmpws;
  424. y2 = randGaussDouble(sigma)*(double)tmpws;
  425. }
  426. else
  427. {
  428. x1 = (int)((double)rand()/(double)RAND_MAX*(double)tmpws)-tmpws/2;
  429. x2 = (int)((double)rand()/(double)RAND_MAX*(double)tmpws)-tmpws/2;
  430. y1 = (int)((double)rand()/(double)RAND_MAX*(double)tmpws)-tmpws/2;
  431. y2 = (int)((double)rand()/(double)RAND_MAX*(double)tmpws)-tmpws/2;
  432. }
  433. if(ft == 0)
  434. {
  435. int f1 = (int)((double)rand()/(double)RAND_MAX*(double)featdim);
  436. int f2 = (int)((double)rand()/(double)RAND_MAX*(double)featdim);
  437. int o = (int)((double)rand()/(double)RAND_MAX*(double)ops.size());
  438. Operation *op = ops[o]->clone();
  439. op->set(x1,y1,x2,y2,f1,f2);
  440. featsel.push_back(op);
  441. }
  442. else if(ft == 1)
  443. {
  444. int f1 = (int)((double)rand()/(double)RAND_MAX*(double)classes);
  445. int f2 = (int)((double)rand()/(double)RAND_MAX*(double)classes);
  446. int o = (int)((double)rand()/(double)RAND_MAX*(double)cops.size());
  447. Operation *op = cops[o]->clone();
  448. op->set(x1,y1,x2,y2,f1,f2);
  449. featsel.push_back(op);
  450. }
  451. }
  452. #pragma omp parallel for private(mapit)
  453. for(int f = 0; f < featsPerSplit; f++)
  454. {
  455. double l_bestig = -numeric_limits< double >::max();
  456. double l_splitval = -1.0;
  457. set<vector<int> >::iterator it;
  458. vector<double> vals;
  459. for ( it=selFeats.begin() ; it != selFeats.end(); it++ )
  460. {
  461. vals.push_back(featsel[f]->getVal(feats[(*it)[0]],currentfeats[(*it)[0]],tree, integralImgs[(*it)[0]], (*it)[1], (*it)[2]));
  462. }
  463. int counter = 0;
  464. for ( it=selFeats.begin() ; it != selFeats.end(); it++ , counter++)
  465. {
  466. set<vector<int> >::iterator it2;
  467. double val = vals[counter];
  468. map<int,int> eL, eR;
  469. int counterL = 0, counterR = 0;
  470. int counter2 = 0;
  471. for ( it2=selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  472. {
  473. int cn = labels[(*it2)[0]][(*it2)[1]][(*it2)[2]];
  474. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  475. if(vals[counter2] < val)
  476. {
  477. //left entropie:
  478. eL[cn] = eL[cn]+1;
  479. counterL++;
  480. }
  481. else
  482. {
  483. //right entropie:
  484. eR[cn] = eR[cn]+1;
  485. counterR++;
  486. }
  487. }
  488. double leftent = 0.0;
  489. for ( mapit=eL.begin() ; mapit != eL.end(); mapit++ )
  490. {
  491. double p = (double)(*mapit).second/(double)counterL;
  492. leftent -= p*log2(p);
  493. }
  494. double rightent = 0.0;
  495. for ( mapit=eR.begin() ; mapit != eR.end(); mapit++ )
  496. {
  497. double p = (double)(*mapit).second/(double)counterR;
  498. rightent -= p*log2(p);
  499. }
  500. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  501. double pl = (double)counterL/(double)(counterL+counterR);
  502. double ig = globent - (1.0-pl) * rightent - pl*leftent;
  503. //double ig = globent - rightent - leftent;
  504. if(useShannonEntropy)
  505. {
  506. double esplit = - ( pl*log(pl) + (1-pl)*log(1-pl) );
  507. ig = 2*ig / ( globent + esplit );
  508. }
  509. if(ig > l_bestig)
  510. {
  511. l_bestig = ig;
  512. l_splitval = val;
  513. }
  514. }
  515. #pragma omp critical
  516. {
  517. //cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  518. //cout << "globent: " << globent << " l_bestig " << l_bestig << " f: " << p << " l_splitval: " << l_splitval << endl;
  519. //cout << "p: " << featsubset[f] << endl;
  520. if(l_bestig > bestig)
  521. {
  522. bestig = l_bestig;
  523. splitop = featsel[f];
  524. splitval = l_splitval;
  525. }
  526. }
  527. }
  528. //splitop->writeInfos();
  529. //cout<< "ig: " << bestig << endl;
  530. /*for(int i = 0; i < featsPerSplit; i++)
  531. {
  532. if(featsel[i] != splitop)
  533. delete featsel[i];
  534. }*/
  535. #ifdef debug
  536. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  537. #endif
  538. return bestig;
  539. }
  540. void SemSegContextTree::computeIntegralImage(const vector<vector<int> > &currentfeats, MultiChannelImageT<double> &integralImage)
  541. {
  542. int xsize = currentfeats.size();
  543. assert(xsize > 0);
  544. int ysize = currentfeats[0].size();
  545. int channels = (int)labelmap.size();
  546. for(int c = 0; c < channels; c++)
  547. {
  548. integralImage.set(0,0,tree[currentfeats[0][0]].dist[c], c);
  549. //first column
  550. for(int y = 1; y < ysize; y++)
  551. {
  552. integralImage.set(0,y,tree[currentfeats[0][y]].dist[c]+integralImage.get(0,y,c), c);
  553. }
  554. //first row
  555. for(int x = 1; x < xsize; x++)
  556. {
  557. integralImage.set(x,0,tree[currentfeats[x][0]].dist[c]+integralImage.get(x,0,c), c);
  558. }
  559. //rest
  560. for(int y = 1; y < ysize; y++)
  561. {
  562. for(int x = 1; x < xsize; x++)
  563. {
  564. double val = tree[currentfeats[x][y]].dist[c]+integralImage.get(x,y-1,c)+integralImage.get(x-1,y,c)-integralImage.get(x-1,y-1,c);
  565. integralImage.set(x, y, val, c);
  566. }
  567. }
  568. }
  569. }
  570. void SemSegContextTree::train ( const MultiDataset *md )
  571. {
  572. const LabeledSet train = * ( *md ) ["train"];
  573. const LabeledSet *trainp = &train;
  574. ProgressBar pb ( "compute feats" );
  575. pb.show();
  576. //TODO: Speichefresser!, lohnt sich sparse?
  577. vector<MultiChannelImageT<double> > allfeats;
  578. vector<vector<vector<int> > > currentfeats;
  579. vector<vector<vector<int> > > labels;
  580. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  581. if ( forbidden_classes_s == "" )
  582. {
  583. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  584. }
  585. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  586. int imgcounter = 0;
  587. LOOP_ALL_S ( *trainp )
  588. {
  589. EACH_INFO ( classno,info );
  590. NICE::ColorImage img;
  591. std::string currentFile = info.img();
  592. CachedExample *ce = new CachedExample ( currentFile );
  593. const LocalizationResult *locResult = info.localization();
  594. if ( locResult->size() <= 0 )
  595. {
  596. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  597. currentFile.c_str() );
  598. continue;
  599. }
  600. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  601. int xsize, ysize;
  602. ce->getImageSize ( xsize, ysize );
  603. vector<vector<int> > tmp = vector<vector<int> >(xsize, vector<int>(ysize,0));
  604. currentfeats.push_back(tmp);
  605. labels.push_back(tmp);
  606. try {
  607. img = ColorImage(currentFile);
  608. } catch (Exception) {
  609. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  610. continue;
  611. }
  612. Globals::setCurrentImgFN ( currentFile );
  613. //TODO: resize image?!
  614. MultiChannelImageT<double> feats;
  615. allfeats.push_back(feats);
  616. #ifdef LOCALFEATS
  617. lfcw->getFeats(img, allfeats[imgcounter]);
  618. #else
  619. allfeats[imgcounter].reInit(xsize, ysize, 3, true);
  620. for(int x = 0; x < xsize; x++)
  621. {
  622. for(int y = 0; y < ysize; y++)
  623. {
  624. for(int r = 0; r < 3; r++)
  625. {
  626. allfeats[imgcounter].set(x,y,img.getPixel(x,y,r),r);
  627. }
  628. }
  629. }
  630. #endif
  631. // getting groundtruth
  632. NICE::Image pixelLabels (xsize, ysize);
  633. pixelLabels.set(0);
  634. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  635. for(int x = 0; x < xsize; x++)
  636. {
  637. for(int y = 0; y < ysize; y++)
  638. {
  639. classno = pixelLabels.getPixel(x, y);
  640. labels[imgcounter][x][y] = classno;
  641. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  642. continue;
  643. labelcounter[classno]++;
  644. }
  645. }
  646. imgcounter++;
  647. pb.update ( trainp->count());
  648. delete ce;
  649. }
  650. pb.hide();
  651. map<int,int>::iterator mapit;
  652. int classes = 0;
  653. for(mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  654. {
  655. labelmap[mapit->first] = classes;
  656. labelmapback[classes] = mapit->first;
  657. classes++;
  658. }
  659. //balancing
  660. int featcounter = 0;
  661. a = vector<double>(classes,0.0);
  662. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  663. {
  664. int xsize = (int)currentfeats[iCounter].size();
  665. int ysize = (int)currentfeats[iCounter][0].size();
  666. for(int x = 0; x < xsize; x++)
  667. {
  668. for(int y = 0; y < ysize; y++)
  669. {
  670. featcounter++;
  671. int cn = labels[iCounter][x][y];
  672. a[labelmap[cn]] ++;
  673. }
  674. }
  675. }
  676. for(int i = 0; i < (int)a.size(); i++)
  677. {
  678. a[i] /= (double)featcounter;
  679. }
  680. #ifdef DEBUG
  681. for(int i = 0; i < (int)a.size(); i++)
  682. {
  683. cout << "a["<<i<<"]: " << a[i] << endl;
  684. }
  685. cout << "a.size: " << a.size() << endl;
  686. #endif
  687. tree.push_back(TreeNode());
  688. tree[0].dist = vector<double>(classes,0.0);
  689. int depth = 0;
  690. tree[0].depth = depth;
  691. int startnode = 0;
  692. bool allleaf = false;
  693. //int baseFeatSize = allfeats[0].size();
  694. vector<MultiChannelImageT<double> > integralImgs(imgcounter,MultiChannelImageT<double>());
  695. while(!allleaf && depth < maxDepth)
  696. {
  697. allleaf = true;
  698. int t = (int) tree.size();
  699. int s = startnode;
  700. startnode = t;
  701. vector<vector<vector<int> > > lastfeats = currentfeats;
  702. //TODO vielleicht parallel wenn nächste schleife trotzdem noch parallelsiert würde, die hat mehr gewicht
  703. //#pragma omp parallel for
  704. for(int i = s; i < t; i++)
  705. {
  706. if(!tree[i].isleaf && tree[i].left < 0)
  707. {
  708. Operation *splitfeat = NULL;
  709. double splitval;
  710. double bestig = getBestSplit(allfeats, lastfeats, integralImgs, labels, i, splitfeat, splitval);
  711. tree[i].feat = splitfeat;
  712. tree[i].decision = splitval;
  713. if(splitfeat != NULL)
  714. {
  715. allleaf = false;
  716. int left = tree.size();
  717. tree.push_back(TreeNode());
  718. tree.push_back(TreeNode());
  719. int right = left+1;
  720. tree[i].left = left;
  721. tree[i].right = right;
  722. tree[left].dist = vector<double>(classes, 0.0);
  723. tree[right].dist = vector<double>(classes, 0.0);
  724. tree[left].depth = depth+1;
  725. tree[right].depth = depth+1;
  726. #pragma omp parallel for
  727. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  728. {
  729. int xsize = currentfeats[iCounter].size();
  730. int ysize = currentfeats[iCounter][0].size();
  731. for(int x = 0; x < xsize; x++)
  732. {
  733. for(int y = 0; y < ysize; y++)
  734. {
  735. if(currentfeats[iCounter][x][y] == i)
  736. {
  737. double val = splitfeat->getVal(allfeats[iCounter],lastfeats[iCounter], tree, integralImgs[iCounter],x,y);
  738. if(val < splitval)
  739. {
  740. currentfeats[iCounter][x][y] = left;
  741. tree[left].dist[labelmap[labels[iCounter][x][y]]]++;
  742. }
  743. else
  744. {
  745. currentfeats[iCounter][x][y] = right;
  746. tree[right].dist[labelmap[labels[iCounter][x][y]]]++;
  747. }
  748. }
  749. }
  750. }
  751. }
  752. double lcounter = 0.0, rcounter = 0.0;
  753. for(uint d = 0; d < tree[left].dist.size(); d++)
  754. {
  755. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  756. {
  757. tree[left].dist[d] = 0;
  758. tree[right].dist[d] = 0;
  759. }
  760. else
  761. {
  762. tree[left].dist[d]/=a[d];
  763. lcounter +=tree[left].dist[d];
  764. tree[right].dist[d]/=a[d];
  765. rcounter +=tree[right].dist[d];
  766. }
  767. }
  768. if(lcounter <= 0 || rcounter <= 0)
  769. {
  770. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  771. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  772. cout << "bestig: " << bestig << endl;
  773. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  774. {
  775. int xsize = currentfeats[iCounter].size();
  776. int ysize = currentfeats[iCounter][0].size();
  777. int counter = 0;
  778. for(int x = 0; x < xsize; x++)
  779. {
  780. for(int y = 0; y < ysize; y++)
  781. {
  782. if(lastfeats[iCounter][x][y] == i)
  783. {
  784. if(++counter > 30)
  785. break;
  786. double val = splitfeat->getVal(allfeats[iCounter],lastfeats[iCounter], tree, integralImgs[iCounter],x,y);
  787. cout << "splitval: " << splitval << " val: " << val << endl;
  788. }
  789. }
  790. }
  791. }
  792. assert(lcounter > 0 && rcounter > 0);
  793. }
  794. for(uint d = 0; d < tree[left].dist.size(); d++)
  795. {
  796. tree[left].dist[d]/=lcounter;
  797. tree[right].dist[d]/=rcounter;
  798. }
  799. }
  800. else
  801. {
  802. tree[i].isleaf = true;
  803. }
  804. }
  805. }
  806. //TODO: features neu berechnen!
  807. //compute integral image
  808. int channels = (int)labelmap.size();
  809. if(integralImgs[0].width() == 0)
  810. {
  811. for(int i = 0; i < imgcounter; i++)
  812. {
  813. int xsize = allfeats[i].width();
  814. int ysize = allfeats[i].height();
  815. integralImgs[i].reInit(xsize, ysize, channels);
  816. }
  817. }
  818. for(int i = 0; i < imgcounter; i++)
  819. {
  820. computeIntegralImage(currentfeats[i],integralImgs[i]);
  821. }
  822. depth++;
  823. #ifdef DEBUG
  824. cout << "depth: " << depth << endl;
  825. #endif
  826. }
  827. #ifdef DEBUG
  828. int t = (int) tree.size();
  829. for(int i = 0; i < t; i++)
  830. {
  831. printf("tree[%i]: left: %i, right: %i", i, tree[i].left, tree[i].right);
  832. if(!tree[i].isleaf && tree[i].left != -1)
  833. cout << ", feat: " << tree[i].feat->writeInfos() << " ";
  834. for(int d = 0; d < (int)tree[i].dist.size(); d++)
  835. {
  836. cout << " " << tree[i].dist[d];
  837. }
  838. cout << endl;
  839. }
  840. #endif
  841. }
  842. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult,NICE::MultiChannelImageT<double> & probabilities )
  843. {
  844. int xsize;
  845. int ysize;
  846. ce->getImageSize ( xsize, ysize );
  847. int numClasses = classNames->numClasses();
  848. fprintf (stderr, "ContextTree classification !\n");
  849. probabilities.reInit ( xsize, ysize, numClasses, true );
  850. probabilities.setAll ( 0 );
  851. NICE::ColorImage img;
  852. std::string currentFile = Globals::getCurrentImgFN();
  853. try {
  854. img = ColorImage(currentFile);
  855. } catch (Exception) {
  856. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  857. return;
  858. }
  859. //TODO: resize image?!
  860. MultiChannelImageT<double> feats;
  861. #ifdef LOCALFEATS
  862. lfcw->getFeats(img, feats);
  863. #else
  864. feats.reInit (xsize, ysize, 3, true);
  865. for(int x = 0; x < xsize; x++)
  866. {
  867. for(int y = 0; y < ysize; y++)
  868. {
  869. for(int r = 0; r < 3; r++)
  870. {
  871. feats.set(x,y,img.getPixel(x,y,r),r);
  872. }
  873. }
  874. }
  875. #endif
  876. bool allleaf = false;
  877. MultiChannelImageT<double> integralImg;
  878. vector<vector<int> > currentfeats = vector<vector<int> >(xsize, vector<int>(ysize,0));
  879. int depth = 0;
  880. while(!allleaf)
  881. {
  882. allleaf = true;
  883. //TODO vielleicht parallel wenn nächste schleife auch noch parallelsiert würde, die hat mehr gewicht
  884. //#pragma omp parallel for
  885. vector<vector<int> > lastfeats = currentfeats;
  886. for(int x = 0; x < xsize; x++)
  887. {
  888. for(int y = 0; y < ysize; y++)
  889. {
  890. int t = currentfeats[x][y];
  891. if(tree[t].left > 0)
  892. {
  893. allleaf = false;
  894. double val = tree[t].feat->getVal(feats,lastfeats,tree,integralImg,x,y);
  895. if(val < tree[t].decision)
  896. {
  897. currentfeats[x][y] = tree[t].left;
  898. }
  899. else
  900. {
  901. currentfeats[x][y] = tree[t].right;
  902. }
  903. }
  904. }
  905. }
  906. //compute integral image
  907. int channels = (int)labelmap.size();
  908. if(integralImg.width() == 0)
  909. {
  910. int xsize = feats.width();
  911. int ysize = feats.height();
  912. integralImg.reInit(xsize, ysize, channels);
  913. }
  914. computeIntegralImage(currentfeats,integralImg);
  915. depth++;
  916. }
  917. if(pixelWiseLabeling)
  918. {
  919. //finales labeln:
  920. long int offset = 0;
  921. for(int x = 0; x < xsize; x++)
  922. {
  923. for(int y = 0; y < ysize; y++,offset++)
  924. {
  925. int t = currentfeats[x][y];
  926. double maxvalue = - numeric_limits<double>::max(); //TODO: das muss nur pro knoten gemacht werden, nicht pro pixel
  927. int maxindex = 0;
  928. for(uint i = 0; i < tree[i].dist.size(); i++)
  929. {
  930. probabilities.data[labelmapback[i]][offset] = tree[t].dist[i];
  931. if(tree[t].dist[i] > maxvalue)
  932. {
  933. maxvalue = tree[t].dist[i];
  934. maxindex = labelmapback[i];
  935. }
  936. segresult.setPixel(x,y,maxindex);
  937. }
  938. }
  939. }
  940. }
  941. else
  942. {
  943. //final labeling using segmentation
  944. //TODO: segmentation
  945. Matrix regions;
  946. int regionNumber = segmentation->segRegions(img,regions);
  947. cout << "regions: " << regionNumber << endl;
  948. int dSize = (int)labelmap.size();
  949. vector<vector<double> > regionProbs(regionNumber, vector<double>(dSize,0.0));
  950. vector<int> bestlabels(regionNumber, 0);
  951. for(int y = 0; y < img.height(); y++)
  952. {
  953. for(int x = 0; x < img.width(); x++)
  954. {
  955. int cnode = currentfeats[x][y];
  956. int cregion = regions(x,y);
  957. for(int d = 0; d < dSize; d++)
  958. {
  959. regionProbs[cregion][d]+=tree[cnode].dist[d];
  960. }
  961. }
  962. }
  963. for(int r = 0; r < regionNumber; r++)
  964. {
  965. double maxval = regionProbs[r][0];
  966. for(int d = 1; d < dSize; d++)
  967. {
  968. if(maxval < regionProbs[r][d])
  969. {
  970. maxval = regionProbs[r][d];
  971. bestlabels[r] = d;
  972. }
  973. }
  974. bestlabels[r] = labelmapback[bestlabels[r]];
  975. }
  976. for(int y = 0; y < img.height(); y++)
  977. {
  978. for(int x = 0; x < img.width(); x++)
  979. {
  980. segresult.setPixel(x,y,bestlabels[regions(x,y)]);
  981. }
  982. }
  983. }
  984. }