SemSegContextTree.cpp 29 KB

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