SemSegContextTree.cpp 31 KB

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