SemSegContextTree.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),cTree)].dist[channel1];
  105. double v2 = tree[cfeats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),cTree)].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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),cTree)].dist[channel1];
  125. double v2 = tree[cfeats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),cTree)].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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),cTree)].dist[channel1];
  145. double v2 = tree[cfeats.get(BOUND(x+x2,0,xsize-1),BOUND(y+y2,0,ysize-1),cTree)].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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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.get(BOUND(x+x1,0,xsize-1),BOUND(y+y1,0,ysize-1),cTree)].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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 MultiChannelImageT<int> &cfeats, const int &cTree, const std::vector<TreeNode> &tree, NICE::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 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)
  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].width();
  334. int ysize = (int)currentfeats[iCounter].height();
  335. for(int x = 0; x < xsize; x++)
  336. {
  337. for(int y = 0; y < ysize; y++)
  338. {
  339. if(currentfeats[iCounter].get(x,y,tree) == 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].width();
  366. int ysize = (int)currentfeats[iCounter].height();
  367. for(int x = 0; x < xsize; x++)
  368. {
  369. for(int y = 0; y < ysize; y++)
  370. {
  371. if(currentfeats[iCounter].get(x,y,tree) == 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)forest[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, forest[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. inline double SemSegContextTree::getMeanProb(const int &x,const int &y,const int &channel, const MultiChannelImageT<int> &currentfeats)
  541. {
  542. double val = 0.0;
  543. for(int tree = 0; tree < nbTrees; tree++)
  544. {
  545. val += forest[tree][currentfeats.get(x,y,tree)].dist[channel];
  546. }
  547. return val / (double)nbTrees;
  548. }
  549. void SemSegContextTree::computeIntegralImage(const NICE::MultiChannelImageT<int> &currentfeats, NICE::MultiChannelImageT<double> &integralImage)
  550. {
  551. int xsize = currentfeats.width();
  552. int ysize = currentfeats.height();
  553. int channels = (int)labelmap.size();
  554. #pragma omp parallel for
  555. for(int c = 0; c < channels; c++)
  556. {
  557. integralImage.set(0,0,getMeanProb(0,0,c, currentfeats), c);
  558. //first column
  559. for(int y = 1; y < ysize; y++)
  560. {
  561. integralImage.set(0,y,getMeanProb(0,y,c, currentfeats)+integralImage.get(0,y,c), c);
  562. }
  563. //first row
  564. for(int x = 1; x < xsize; x++)
  565. {
  566. integralImage.set(x,0,getMeanProb(x,0,c, currentfeats)+integralImage.get(x,0,c), c);
  567. }
  568. //rest
  569. for(int y = 1; y < ysize; y++)
  570. {
  571. for(int x = 1; x < xsize; x++)
  572. {
  573. 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);
  574. integralImage.set(x, y, val, c);
  575. }
  576. }
  577. }
  578. }
  579. void SemSegContextTree::train ( const MultiDataset *md )
  580. {
  581. const LabeledSet train = * ( *md ) ["train"];
  582. const LabeledSet *trainp = &train;
  583. ProgressBar pb ( "compute feats" );
  584. pb.show();
  585. //TODO: Speichefresser!, lohnt sich sparse?
  586. vector<MultiChannelImageT<double> > allfeats;
  587. vector<MultiChannelImageT<int> > currentfeats;
  588. vector<MatrixT<int> > labels;
  589. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  590. if ( forbidden_classes_s == "" )
  591. {
  592. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  593. }
  594. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  595. int imgcounter = 0;
  596. LOOP_ALL_S ( *trainp )
  597. {
  598. EACH_INFO ( classno,info );
  599. NICE::ColorImage img;
  600. std::string currentFile = info.img();
  601. CachedExample *ce = new CachedExample ( currentFile );
  602. const LocalizationResult *locResult = info.localization();
  603. if ( locResult->size() <= 0 )
  604. {
  605. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  606. currentFile.c_str() );
  607. continue;
  608. }
  609. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  610. int xsize, ysize;
  611. ce->getImageSize ( xsize, ysize );
  612. MultiChannelImageT<int> tmp(xsize, ysize, nbTrees);
  613. MatrixT<int> tmpMat(xsize,ysize);
  614. currentfeats.push_back(tmp);
  615. labels.push_back(tmpMat);
  616. try {
  617. img = ColorImage(currentFile);
  618. } catch (Exception) {
  619. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  620. continue;
  621. }
  622. Globals::setCurrentImgFN ( currentFile );
  623. //TODO: resize image?!
  624. MultiChannelImageT<double> feats;
  625. allfeats.push_back(feats);
  626. #ifdef LOCALFEATS
  627. lfcw->getFeats(img, allfeats[imgcounter]);
  628. #else
  629. allfeats[imgcounter].reInit(xsize, ysize, 3, true);
  630. for(int x = 0; x < xsize; x++)
  631. {
  632. for(int y = 0; y < ysize; y++)
  633. {
  634. for(int r = 0; r < 3; r++)
  635. {
  636. allfeats[imgcounter].set(x,y,img.getPixel(x,y,r),r);
  637. }
  638. }
  639. }
  640. #endif
  641. // getting groundtruth
  642. NICE::Image pixelLabels (xsize, ysize);
  643. pixelLabels.set(0);
  644. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  645. for(int x = 0; x < xsize; x++)
  646. {
  647. for(int y = 0; y < ysize; y++)
  648. {
  649. classno = pixelLabels.getPixel(x, y);
  650. labels[imgcounter](x,y) = classno;
  651. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  652. continue;
  653. labelcounter[classno]++;
  654. }
  655. }
  656. imgcounter++;
  657. pb.update ( trainp->count());
  658. delete ce;
  659. }
  660. pb.hide();
  661. map<int,int>::iterator mapit;
  662. int classes = 0;
  663. for(mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  664. {
  665. labelmap[mapit->first] = classes;
  666. labelmapback[classes] = mapit->first;
  667. classes++;
  668. }
  669. //balancing
  670. int featcounter = 0;
  671. a = vector<double>(classes,0.0);
  672. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  673. {
  674. int xsize = (int)currentfeats[iCounter].width();
  675. int ysize = (int)currentfeats[iCounter].height();
  676. for(int x = 0; x < xsize; x++)
  677. {
  678. for(int y = 0; y < ysize; y++)
  679. {
  680. featcounter++;
  681. int cn = labels[iCounter](x,y);
  682. a[labelmap[cn]] ++;
  683. }
  684. }
  685. }
  686. for(int i = 0; i < (int)a.size(); i++)
  687. {
  688. a[i] /= (double)featcounter;
  689. }
  690. #ifdef DEBUG
  691. for(int i = 0; i < (int)a.size(); i++)
  692. {
  693. cout << "a["<<i<<"]: " << a[i] << endl;
  694. }
  695. cout << "a.size: " << a.size() << endl;
  696. #endif
  697. int depth = 0;
  698. for(int t = 0; t < nbTrees; t++)
  699. {
  700. vector<TreeNode> tree;
  701. tree.push_back(TreeNode());
  702. tree[0].dist = vector<double>(classes,0.0);
  703. tree[0].depth = depth;
  704. forest.push_back(tree);
  705. }
  706. vector<int> startnode(nbTrees,0);
  707. bool allleaf = false;
  708. //int baseFeatSize = allfeats[0].size();
  709. vector<MultiChannelImageT<double> > integralImgs(imgcounter,MultiChannelImageT<double>());
  710. while(!allleaf && depth < maxDepth)
  711. {
  712. allleaf = true;
  713. for(int tree = 0; tree < nbTrees; tree++)
  714. {
  715. int t = (int) forest[tree].size();
  716. int s = startnode[tree];
  717. startnode[tree] = t;
  718. vector<MultiChannelImageT<int> > lastfeats = currentfeats;
  719. //TODO vielleicht parallel wenn nächste schleife trotzdem noch parallelsiert würde, die hat mehr gewicht
  720. //#pragma omp parallel for
  721. for(int i = s; i < t; i++)
  722. {
  723. if(!forest[tree][i].isleaf && forest[tree][i].left < 0)
  724. {
  725. Operation *splitfeat = NULL;
  726. double splitval;
  727. double bestig = getBestSplit(allfeats, lastfeats, integralImgs, labels, i, splitfeat, splitval, tree);
  728. forest[tree][i].feat = splitfeat;
  729. forest[tree][i].decision = splitval;
  730. if(splitfeat != NULL)
  731. {
  732. allleaf = false;
  733. int left = forest[tree].size();
  734. forest[tree].push_back(TreeNode());
  735. forest[tree].push_back(TreeNode());
  736. int right = left+1;
  737. forest[tree][i].left = left;
  738. forest[tree][i].right = right;
  739. forest[tree][left].dist = vector<double>(classes, 0.0);
  740. forest[tree][right].dist = vector<double>(classes, 0.0);
  741. forest[tree][left].depth = depth+1;
  742. forest[tree][right].depth = depth+1;
  743. #pragma omp parallel for
  744. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  745. {
  746. int xsize = currentfeats[iCounter].width();
  747. int ysize = currentfeats[iCounter].height();
  748. for(int x = 0; x < xsize; x++)
  749. {
  750. for(int y = 0; y < ysize; y++)
  751. {
  752. if(currentfeats[iCounter].get(x, y, t) == i)
  753. {
  754. double val = splitfeat->getVal(allfeats[iCounter],lastfeats[iCounter], tree, forest[tree], integralImgs[iCounter],x,y);
  755. if(val < splitval)
  756. {
  757. currentfeats[iCounter].set(x,y,left,t);
  758. forest[tree][left].dist[labelmap[labels[iCounter](x,y)]]++;
  759. }
  760. else
  761. {
  762. currentfeats[iCounter].set(x,y,right,t);
  763. forest[tree][right].dist[labelmap[labels[iCounter](x,y)]]++;
  764. }
  765. }
  766. }
  767. }
  768. }
  769. double lcounter = 0.0, rcounter = 0.0;
  770. for(uint d = 0; d < forest[tree][left].dist.size(); d++)
  771. {
  772. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  773. {
  774. forest[tree][left].dist[d] = 0;
  775. forest[tree][right].dist[d] = 0;
  776. }
  777. else
  778. {
  779. forest[tree][left].dist[d]/=a[d];
  780. lcounter +=forest[tree][left].dist[d];
  781. forest[tree][right].dist[d]/=a[d];
  782. rcounter +=forest[tree][right].dist[d];
  783. }
  784. }
  785. if(lcounter <= 0 || rcounter <= 0)
  786. {
  787. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  788. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  789. cout << "bestig: " << bestig << endl;
  790. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  791. {
  792. int xsize = currentfeats[iCounter].width();
  793. int ysize = currentfeats[iCounter].height();
  794. int counter = 0;
  795. for(int x = 0; x < xsize; x++)
  796. {
  797. for(int y = 0; y < ysize; y++)
  798. {
  799. if(lastfeats[iCounter].get(x,y,tree) == i)
  800. {
  801. if(++counter > 30)
  802. break;
  803. double val = splitfeat->getVal(allfeats[iCounter],lastfeats[iCounter], tree, forest[tree], integralImgs[iCounter],x,y);
  804. cout << "splitval: " << splitval << " val: " << val << endl;
  805. }
  806. }
  807. }
  808. }
  809. assert(lcounter > 0 && rcounter > 0);
  810. }
  811. for(uint d = 0; d < forest[tree][left].dist.size(); d++)
  812. {
  813. forest[tree][left].dist[d]/=lcounter;
  814. forest[tree][right].dist[d]/=rcounter;
  815. }
  816. }
  817. else
  818. {
  819. forest[tree][i].isleaf = true;
  820. }
  821. }
  822. }
  823. //TODO: features neu berechnen!
  824. //compute integral image
  825. int channels = (int)labelmap.size();
  826. if(integralImgs[0].width() == 0)
  827. {
  828. for(int i = 0; i < imgcounter; i++)
  829. {
  830. int xsize = allfeats[i].width();
  831. int ysize = allfeats[i].height();
  832. integralImgs[i].reInit(xsize, ysize, channels);
  833. }
  834. }
  835. for(int i = 0; i < imgcounter; i++)
  836. {
  837. computeIntegralImage(currentfeats[i],integralImgs[i]);
  838. }
  839. depth++;
  840. #ifdef DEBUG
  841. cout << "depth: " << depth << endl;
  842. #endif
  843. }
  844. }
  845. #ifdef DEBUG
  846. for(int tree = 0; tree < nbTrees; tree++)
  847. {
  848. int t = (int) forest[tree].size();
  849. for(int i = 0; i < t; i++)
  850. {
  851. printf("tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right);
  852. if(!forest[tree][i].isleaf && forest[tree][i].left != -1)
  853. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  854. for(int d = 0; d < (int)forest[tree][i].dist.size(); d++)
  855. {
  856. cout << " " << forest[tree][i].dist[d];
  857. }
  858. cout << endl;
  859. }
  860. }
  861. #endif
  862. }
  863. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult,NICE::MultiChannelImageT<double> & probabilities )
  864. {
  865. int xsize;
  866. int ysize;
  867. ce->getImageSize ( xsize, ysize );
  868. int numClasses = classNames->numClasses();
  869. fprintf (stderr, "ContextTree classification !\n");
  870. probabilities.reInit ( xsize, ysize, numClasses, true );
  871. probabilities.setAll ( 0 );
  872. NICE::ColorImage img;
  873. std::string currentFile = Globals::getCurrentImgFN();
  874. try {
  875. img = ColorImage(currentFile);
  876. } catch (Exception) {
  877. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  878. return;
  879. }
  880. //TODO: resize image?!
  881. MultiChannelImageT<double> feats;
  882. #ifdef LOCALFEATS
  883. lfcw->getFeats(img, feats);
  884. #else
  885. feats.reInit (xsize, ysize, 3, true);
  886. for(int x = 0; x < xsize; x++)
  887. {
  888. for(int y = 0; y < ysize; y++)
  889. {
  890. for(int r = 0; r < 3; r++)
  891. {
  892. feats.set(x,y,img.getPixel(x,y,r),r);
  893. }
  894. }
  895. }
  896. #endif
  897. bool allleaf = false;
  898. MultiChannelImageT<double> integralImg;
  899. MultiChannelImageT<int> currentfeats(xsize, ysize, nbTrees);
  900. int depth = 0;
  901. while(!allleaf)
  902. {
  903. allleaf = true;
  904. //TODO vielleicht parallel wenn nächste schleife auch noch parallelsiert würde, die hat mehr gewicht
  905. //#pragma omp parallel for
  906. MultiChannelImageT<int> lastfeats = currentfeats;
  907. for(int x = 0; x < xsize; x++)
  908. {
  909. for(int y = 0; y < ysize; y++)
  910. {
  911. int t = currentfeats.get(x,y,tree);
  912. if(tree[t].left > 0)
  913. {
  914. allleaf = false;
  915. double val = tree[t].feat->getVal(feats,lastfeats,tree, forest[tree], integralImg,x,y);
  916. if(val < tree[t].decision)
  917. {
  918. currentfeats.set(x, y, tree[t].left, tree);
  919. }
  920. else
  921. {
  922. currentfeats.set(x, y, tree[t].right, tree);
  923. }
  924. }
  925. }
  926. }
  927. //compute integral image
  928. int channels = (int)labelmap.size();
  929. if(integralImg.width() == 0)
  930. {
  931. int xsize = feats.width();
  932. int ysize = feats.height();
  933. integralImg.reInit(xsize, ysize, channels);
  934. }
  935. computeIntegralImage(currentfeats,integralImg);
  936. depth++;
  937. }
  938. if(pixelWiseLabeling)
  939. {
  940. //finales labeln:
  941. long int offset = 0;
  942. for(int x = 0; x < xsize; x++)
  943. {
  944. for(int y = 0; y < ysize; y++,offset++)
  945. {
  946. int t = currentfeats.get(x,y,tree);
  947. double maxvalue = - numeric_limits<double>::max(); //TODO: das muss nur pro knoten gemacht werden, nicht pro pixel
  948. int maxindex = 0;
  949. for(uint i = 0; i < tree[i].dist.size(); i++)
  950. {
  951. probabilities.data[labelmapback[i]][offset] = tree[t].dist[i];
  952. if(tree[t].dist[i] > maxvalue)
  953. {
  954. maxvalue = tree[t].dist[i];
  955. maxindex = labelmapback[i];
  956. }
  957. segresult.setPixel(x,y,maxindex);
  958. }
  959. }
  960. }
  961. }
  962. else
  963. {
  964. //final labeling using segmentation
  965. //TODO: segmentation
  966. Matrix regions;
  967. int regionNumber = segmentation->segRegions(img,regions);
  968. cout << "regions: " << regionNumber << endl;
  969. int dSize = (int)labelmap.size();
  970. vector<vector<double> > regionProbs(regionNumber, vector<double>(dSize,0.0));
  971. vector<int> bestlabels(regionNumber, 0);
  972. for(int y = 0; y < img.height(); y++)
  973. {
  974. for(int x = 0; x < img.width(); x++)
  975. {
  976. int cnode = currentfeats.get(x, y, tree);
  977. int cregion = regions(x,y);
  978. for(int d = 0; d < dSize; d++)
  979. {
  980. regionProbs[cregion][d]+=tree[cnode].dist[d];
  981. }
  982. }
  983. }
  984. for(int r = 0; r < regionNumber; r++)
  985. {
  986. double maxval = regionProbs[r][0];
  987. for(int d = 1; d < dSize; d++)
  988. {
  989. if(maxval < regionProbs[r][d])
  990. {
  991. maxval = regionProbs[r][d];
  992. bestlabels[r] = d;
  993. }
  994. }
  995. bestlabels[r] = labelmapback[bestlabels[r]];
  996. }
  997. for(int y = 0; y < img.height(); y++)
  998. {
  999. for(int x = 0; x < img.width(); x++)
  1000. {
  1001. segresult.setPixel(x,y,bestlabels[regions(x,y)]);
  1002. }
  1003. }
  1004. }
  1005. }