SemSegContextTree.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #include <objrec/nice.h>
  2. #include <iostream>
  3. #include "SemSegContextTree.h"
  4. #include "objrec/baselib/Globals.h"
  5. #include "objrec/baselib/ProgressBar.h"
  6. #include "objrec/baselib/StringTools.h"
  7. #include "objrec/baselib/Globals.h"
  8. #include "objrec/cbaselib/CachedExample.h"
  9. #include "objrec/cbaselib/PascalResults.h"
  10. #include <omp.h>
  11. #define BOUND(x,min,max) (((x)<(min))?(min):((x)>(max)?(max):(x)))
  12. using namespace OBJREC;
  13. using namespace std;
  14. using namespace NICE;
  15. SemSegContextTree::SemSegContextTree( const Config *conf, const MultiDataset *md )
  16. : SemanticSegmentation ( conf, &(md->getClassNames("train")) )
  17. {
  18. string section = "SSContextTree";
  19. lfcw = new LFColorWeijer(conf);
  20. grid = conf->gI(section, "grid", 10 );
  21. maxSamples = conf->gI(section, "max_samples", 2000 );
  22. minFeats = conf->gI(section, "min_feats", 50 );
  23. maxDepth = conf->gI(section, "max_depth", 10 );
  24. windowSize = conf->gI(section, "window_size", 16);
  25. featsPerSplit = conf->gI(section, "feats_per_split", 200);
  26. ops.push_back(new Minus());
  27. ops.push_back(new MinusAbs());
  28. ops.push_back(new Addition());
  29. ///////////////////////////////////
  30. // Train Segmentation Context Trees
  31. //////////////////////////////////
  32. train ( md );
  33. }
  34. SemSegContextTree::~SemSegContextTree()
  35. {
  36. }
  37. void SemSegContextTree::getBestSplit(const vector<vector<vector<vector<double> > > > &feats, vector<vector<vector<int> > > &currentfeats,const vector<vector<vector<int> > > &labels, int node, int &splitfeat, double &splitval)
  38. {
  39. int imgCount, featsize;
  40. try
  41. {
  42. imgCount = (int)feats.size();
  43. featsize = feats[0][0][0].size();
  44. }
  45. catch(Exception)
  46. {
  47. cerr << "no features computed?" << endl;
  48. }
  49. double bestig = -numeric_limits< double >::max();
  50. splitfeat = -1;
  51. splitval = -1.0;
  52. set<vector<int> >selFeats;
  53. map<int,int> e;
  54. int featcounter = 0;
  55. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  56. {
  57. int xsize = (int)currentfeats[iCounter].size();
  58. int ysize = (int)currentfeats[iCounter][0].size();
  59. for(int x = 0; x < xsize; x++)
  60. {
  61. for(int y = 0; y < ysize; y++)
  62. {
  63. if(currentfeats[iCounter][x][y] == node)
  64. {
  65. featcounter++;
  66. }
  67. }
  68. }
  69. }
  70. vector<double> fraction(a.size(),0.0);
  71. for(uint i = 0; i < fraction.size(); i++)
  72. {
  73. fraction[i] = ((double)maxSamples)/(a[i]*(double)featcounter*8);
  74. //cout << "fraction["<<i<<"]: "<< fraction[i] << endl;
  75. }
  76. featcounter = 0;
  77. for(int iCounter = 0; iCounter < imgCount; iCounter++)
  78. {
  79. int xsize = (int)currentfeats[iCounter].size();
  80. int ysize = (int)currentfeats[iCounter][0].size();
  81. for(int x = 0; x < xsize; x++)
  82. {
  83. for(int y = 0; y < ysize; y++)
  84. {
  85. if(currentfeats[iCounter][x][y] == node)
  86. {
  87. int cn = labels[iCounter][x][y];
  88. double randD = (double)rand()/(double)RAND_MAX;
  89. if(randD < fraction[labelmap[cn]])
  90. {
  91. vector<int> tmp(3,0);
  92. tmp[0] = iCounter;
  93. tmp[1] = x;
  94. tmp[2] = y;
  95. featcounter++;
  96. selFeats.insert(tmp);
  97. e[cn]++;
  98. }
  99. }
  100. }
  101. }
  102. }
  103. //cout << "size: " << selFeats.size() << endl;
  104. map<int,int>::iterator mapit;
  105. double globent = 0.0;
  106. for ( mapit=e.begin() ; mapit != e.end(); mapit++ )
  107. {
  108. //cout << "class: " << mapit->first << ": " << mapit->second << endl;
  109. double p = (double)(*mapit).second/(double)featcounter;
  110. globent += p*log2(p);
  111. }
  112. globent = -globent;
  113. if(globent < 0.5)
  114. {
  115. cout << "globent to small: " << globent << endl;
  116. return;
  117. }
  118. if(featcounter < minFeats)
  119. {
  120. cout << "only " << featcounter << " feats in current node -> it's a leaf" << endl;
  121. return;
  122. }
  123. vector<int> featsubset;
  124. for(int i = 0; i < featsPerSplit; i++)
  125. {
  126. int randI = ((double)rand()/(double)RAND_MAX*(double)allfeatsize);
  127. featsubset.push_back(randI);
  128. }
  129. #pragma omp parallel for private(mapit)
  130. for(int f = 0; f < featsPerSplit; f++)
  131. {
  132. int x1 = featsel[featsubset[f]][0];
  133. int y1 = featsel[featsubset[f]][1];
  134. int x2 = featsel[featsubset[f]][2];
  135. int y2 = featsel[featsubset[f]][3];
  136. int chan = featsel[featsubset[f]][4];
  137. int o = featsel[featsubset[f]][5];
  138. double l_bestig = -numeric_limits< double >::max();
  139. double l_splitval = -1.0;
  140. set<vector<int> >::iterator it;
  141. vector<double> vals;
  142. for ( it=selFeats.begin() ; it != selFeats.end(); it++ )
  143. {
  144. int xsize = (int)feats[(*it)[0]].size();
  145. int ysize = (int)feats[(*it)[0]][0].size();
  146. double val1 = feats[(*it)[0]][BOUND((*it)[1]+x1,0,xsize-1)][BOUND((*it)[2]+y1,0,ysize-1)][chan];
  147. double val2 = feats[(*it)[0]][BOUND((*it)[1]+x2,0,xsize-1)][BOUND((*it)[2]+y2,0,ysize-1)][chan];
  148. vals.push_back(ops[o]->getVal(val1,val2));
  149. }
  150. int counter = 0;
  151. for ( it=selFeats.begin() ; it != selFeats.end(); it++ , counter++)
  152. {
  153. set<vector<int> >::iterator it2;
  154. double val = vals[counter];
  155. map<int,int> eL, eR;
  156. int counterL = 0, counterR = 0;
  157. int counter2 = 0;
  158. for ( it2=selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  159. {
  160. int cn = labels[(*it2)[0]][(*it2)[1]][(*it2)[2]];
  161. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  162. if(vals[counter2] < val)
  163. {
  164. //left entropie:
  165. eL[cn] = eL[cn]+1;
  166. counterL++;
  167. }
  168. else
  169. {
  170. //right entropie:
  171. eR[cn] = eR[cn]+1;
  172. counterR++;
  173. }
  174. }
  175. double leftent = 0.0;
  176. for ( mapit=eL.begin() ; mapit != eL.end(); mapit++ )
  177. {
  178. double p = (double)(*mapit).second/(double)counterL;
  179. leftent += p*log2(p);
  180. }
  181. leftent = -leftent;
  182. double rightent = 0.0;
  183. for ( mapit=eR.begin() ; mapit != eR.end(); mapit++ )
  184. {
  185. double p = (double)(*mapit).second/(double)counterR;
  186. rightent += p*log2(p);
  187. }
  188. rightent = -rightent;
  189. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  190. double ig = globent - rightent - leftent;
  191. if(ig > l_bestig)
  192. {
  193. l_bestig = ig;
  194. l_splitval = val;
  195. }
  196. }
  197. #pragma omp critical
  198. {
  199. //cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  200. //cout << "globent: " << globent << " l_bestig " << l_bestig << " f: " << p << " l_splitval: " << l_splitval << endl;
  201. //cout << "p: " << featsubset[f] << endl;
  202. if(l_bestig > bestig)
  203. {
  204. bestig = l_bestig;
  205. splitfeat = featsubset[f];
  206. splitval = l_splitval;
  207. }
  208. }
  209. }
  210. cout << "globent: " << globent << " bestig " << bestig << " splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  211. }
  212. void SemSegContextTree::train ( const MultiDataset *md )
  213. {
  214. const LabeledSet train = * ( *md ) ["train"];
  215. const LabeledSet *trainp = &train;
  216. ProgressBar pb ( "compute feats" );
  217. pb.show();
  218. //TODO: Speichefresser!, lohnt sich sparse?
  219. vector<vector<vector<vector<double> > > > allfeats;
  220. vector<vector<vector<int> > > currentfeats;
  221. vector<vector<vector<int> > > labels;
  222. int imgcounter = 0;
  223. LOOP_ALL_S ( *trainp )
  224. {
  225. EACH_INFO ( classno,info );
  226. NICE::ColorImage img;
  227. std::string currentFile = info.img();
  228. CachedExample *ce = new CachedExample ( currentFile );
  229. const LocalizationResult *locResult = info.localization();
  230. if ( locResult->size() <= 0 )
  231. {
  232. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  233. currentFile.c_str() );
  234. continue;
  235. }
  236. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  237. int xsize, ysize;
  238. ce->getImageSize ( xsize, ysize );
  239. vector<vector<int> > tmp = vector<vector<int> >(xsize, vector<int>(ysize,0));
  240. currentfeats.push_back(tmp);
  241. labels.push_back(tmp);
  242. try {
  243. img = ColorImage(currentFile);
  244. } catch (Exception) {
  245. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  246. continue;
  247. }
  248. Globals::setCurrentImgFN ( currentFile );
  249. //TODO: resize image?!
  250. vector<vector<vector<double> > > feats;
  251. #if 0
  252. lfcw->getFeats(img, feats);
  253. #else
  254. feats = vector<vector<vector<double> > >(xsize,vector<vector<double> >(ysize,vector<double>(3,0.0)));
  255. for(int x = 0; x < xsize; x++)
  256. {
  257. for(int y = 0; y < ysize; y++)
  258. {
  259. for(int r = 0; r < 3; r++)
  260. {
  261. feats[x][y][r] = img.getPixel(x,y,r);
  262. }
  263. }
  264. }
  265. #endif
  266. allfeats.push_back(feats);
  267. // getting groundtruth
  268. NICE::Image pixelLabels (xsize, ysize);
  269. pixelLabels.set(0);
  270. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  271. for(int x = 0; x < xsize; x++)
  272. {
  273. for(int y = 0; y < ysize; y++)
  274. {
  275. classno = pixelLabels.getPixel(x, y);
  276. labels[imgcounter][x][y] = classno;
  277. labelcounter[classno]++;
  278. //if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  279. //continue;
  280. }
  281. }
  282. imgcounter++;
  283. pb.update ( trainp->count());
  284. delete ce;
  285. }
  286. pb.hide();
  287. int opsize = (int)ops.size();
  288. int featdim = (int)allfeats[0][0][0].size();
  289. allfeatsize = windowSize*windowSize*windowSize*windowSize*featdim*opsize;
  290. for(int x1 = -windowSize/2; x1 < windowSize/2+1; x1++)
  291. {
  292. for(int y1 = -windowSize/2; y1 < windowSize/2+1; y1++)
  293. {
  294. for(int x2 = -windowSize/2; x2 < windowSize/2+1; x2++)
  295. {
  296. for(int y2 = -windowSize/2; y2 < windowSize/2+1; y2++)
  297. {
  298. for(int f = 0; f < featdim; f++)
  299. {
  300. for(int o = 0; o < opsize; o++)
  301. {
  302. vector<int> tmp(6,0);
  303. tmp[0] = x1;
  304. tmp[1] = y1;
  305. tmp[2] = x2;
  306. tmp[3] = y2;
  307. tmp[4] = f;
  308. tmp[5] = o;
  309. featsel.push_back(tmp);
  310. }
  311. }
  312. }
  313. }
  314. }
  315. }
  316. map<int,int>::iterator mapit;
  317. int classes = 0;
  318. for(mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  319. {
  320. labelmap[mapit->first] = classes;
  321. labelmapback[classes] = mapit->first;
  322. classes++;
  323. }
  324. //balancing
  325. int featcounter = 0;
  326. a = vector<double>(classes,0.0);
  327. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  328. {
  329. int xsize = (int)currentfeats[iCounter].size();
  330. int ysize = (int)currentfeats[iCounter][0].size();
  331. for(int x = 0; x < xsize; x++)
  332. {
  333. for(int y = 0; y < ysize; y++)
  334. {
  335. featcounter++;
  336. int cn = labels[iCounter][x][y];
  337. a[labelmap[cn]] ++;
  338. }
  339. }
  340. }
  341. for(int i = 0; i < (int)a.size(); i++)
  342. {
  343. a[i] /= (double)featcounter;
  344. cout << "a["<<i<<"]: " << a[i] << endl;
  345. }
  346. tree.push_back(Node());
  347. tree[0].dist = vector<double>(classes,0.0);
  348. int depth = 0;
  349. tree[0].depth = depth;
  350. bool allleaf = false;
  351. while(!allleaf && depth < maxDepth)
  352. {
  353. allleaf = true;
  354. //TODO vielleicht parallel wenn nächste schleife auch noch parallelsiert würde, die hat mehr gewicht
  355. //#pragma omp parallel for
  356. int t = (int) tree.size();
  357. for(int i = 0; i < t; i++)
  358. {
  359. printf("tree[%i]: left: %i, right: %i ", i, tree[i].left, tree[i].right);
  360. for(int d = 0; d < (int)tree[i].dist.size(); d++)
  361. {
  362. cout << " " << tree[i].dist[d];
  363. }
  364. cout << endl;
  365. if(!tree[i].isleaf && tree[i].left < 0)
  366. {
  367. int splitfeat;
  368. double splitval;
  369. getBestSplit(allfeats, currentfeats,labels, i, splitfeat, splitval);
  370. tree[i].feat = splitfeat;
  371. tree[i].decision = splitval;
  372. cout << "splitfeat: " << splitfeat << " splitval: " << splitval << endl;
  373. if(splitfeat >= 0)
  374. {
  375. int x1 = featsel[splitfeat][0];
  376. int y1 = featsel[splitfeat][1];
  377. int x2 = featsel[splitfeat][2];
  378. int y2 = featsel[splitfeat][3];
  379. int p = featsel[splitfeat][4];
  380. int o = featsel[splitfeat][5];
  381. allleaf = false;
  382. int left = tree.size();
  383. tree.push_back(Node());
  384. tree.push_back(Node());
  385. int right = left+1;
  386. tree[i].left = left;
  387. tree[i].right = right;
  388. tree[left].dist = vector<double>(classes, 0.0);
  389. tree[right].dist = vector<double>(classes, 0.0);
  390. tree[left].depth = depth+1;
  391. tree[right].depth = depth+1;
  392. #pragma omp parallel for
  393. for(int iCounter = 0; iCounter < imgcounter; iCounter++)
  394. {
  395. int xsize = currentfeats[iCounter].size();
  396. int ysize = currentfeats[iCounter][0].size();
  397. for(int x = 0; x < xsize; x++)
  398. {
  399. for(int y = 0; y < ysize; y++)
  400. {
  401. if(currentfeats[iCounter][x][y] == i)
  402. {
  403. int xsize = (int)allfeats[iCounter].size();
  404. int ysize = (int)allfeats[iCounter][0].size();
  405. double val1 = allfeats[iCounter][BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)][p];
  406. double val2 = allfeats[iCounter][BOUND(x+x2,0,xsize-1)][BOUND(y+y2,0,ysize-1)][p];
  407. double val = ops[o]->getVal(val1,val2);
  408. if(val < splitval)
  409. {
  410. currentfeats[iCounter][x][y] = left;
  411. tree[left].dist[labelmap[labels[iCounter][x][y]]]++;
  412. }
  413. else
  414. {
  415. currentfeats[iCounter][x][y] = right;
  416. tree[right].dist[labelmap[labels[iCounter][x][y]]]++;
  417. }
  418. }
  419. }
  420. }
  421. }
  422. double lcounter = 0.0, rcounter = 0.0;
  423. for(uint d = 0; d < tree[left].dist.size(); d++)
  424. {
  425. tree[left].dist[d]/=a[d];
  426. lcounter +=tree[left].dist[d];
  427. tree[right].dist[d]/=a[d];
  428. rcounter +=tree[right].dist[d];
  429. }
  430. assert(lcounter > 0 && rcounter > 0);
  431. for(uint d = 0; d < tree[left].dist.size(); d++)
  432. {
  433. tree[left].dist[d]/=lcounter;
  434. tree[right].dist[d]/=rcounter;
  435. }
  436. }
  437. else
  438. {
  439. tree[i].isleaf = true;
  440. }
  441. //TODO: probability ermitteln
  442. }
  443. }
  444. //TODO: features neu berechnen!
  445. depth++;
  446. cout << "d: " << depth << endl;
  447. }
  448. }
  449. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult,GenericImage<double> & probabilities )
  450. {
  451. int xsize;
  452. int ysize;
  453. ce->getImageSize ( xsize, ysize );
  454. int numClasses = classNames->numClasses();
  455. fprintf (stderr, "ContextTree classification !\n");
  456. probabilities.reInit ( xsize, ysize, numClasses, true );
  457. probabilities.setAll ( 0 );
  458. NICE::ColorImage img;
  459. std::string currentFile = Globals::getCurrentImgFN();
  460. try {
  461. img = ColorImage(currentFile);
  462. } catch (Exception) {
  463. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  464. return;
  465. }
  466. //TODO: resize image?!
  467. vector<vector<vector<double> > > feats;
  468. #if 0
  469. lfcw->getFeats(img, feats);
  470. #else
  471. feats = vector<vector<vector<double> > >(xsize,vector<vector<double> >(ysize,vector<double>(3,0.0)));
  472. for(int x = 0; x < xsize; x++)
  473. {
  474. for(int y = 0; y < ysize; y++)
  475. {
  476. for(int r = 0; r < 3; r++)
  477. {
  478. feats[x][y][r] = img.getPixel(x,y,r);
  479. }
  480. }
  481. }
  482. #endif
  483. bool allleaf = false;
  484. vector<vector<int> > currentfeats = vector<vector<int> >(xsize, vector<int>(ysize,0));
  485. int depth = 0;
  486. while(!allleaf)
  487. {
  488. allleaf = true;
  489. //TODO vielleicht parallel wenn nächste schleife auch noch parallelsiert würde, die hat mehr gewicht
  490. //#pragma omp parallel for
  491. int t = (int) tree.size();
  492. for(int i = 0; i < t; i++)
  493. {
  494. for(int x = 0; x < xsize; x++)
  495. {
  496. for(int y = 0; y < ysize; y++)
  497. {
  498. int t = currentfeats[x][y];
  499. if(tree[t].left > 0)
  500. {
  501. allleaf = false;
  502. int splitfeat = tree[t].feat;
  503. int x1 = featsel[splitfeat][0];
  504. int y1 = featsel[splitfeat][1];
  505. int x2 = featsel[splitfeat][2];
  506. int y2 = featsel[splitfeat][3];
  507. int p = featsel[splitfeat][4];
  508. int o = featsel[splitfeat][5];
  509. double val1 = feats[BOUND(x+x1,0,xsize-1)][BOUND(y+y1,0,ysize-1)][p];
  510. double val2 = feats[BOUND(x+x2,0,xsize-1)][BOUND(y+y2,0,ysize-1)][p];
  511. double val = ops[o]->getVal(val1,val2);
  512. if(val < tree[t].decision)
  513. {
  514. currentfeats[x][y] = tree[t].left;
  515. }
  516. else
  517. {
  518. currentfeats[x][y] = tree[t].right;
  519. }
  520. }
  521. }
  522. }
  523. }
  524. //TODO: features neu berechnen! analog zum training
  525. depth++;
  526. }
  527. //finales labeln:
  528. long int offset = 0;
  529. for(int x = 0; x < xsize; x++)
  530. {
  531. for(int y = 0; y < ysize; y++,offset++)
  532. {
  533. int t = currentfeats[x][y];
  534. double maxvalue = - numeric_limits<double>::max(); //TODO: das muss nur pro knoten gemacht werden, nicht pro pixel
  535. int maxindex = 0;
  536. for(uint i = 0; i < tree[i].dist.size(); i++)
  537. {
  538. probabilities.data[labelmapback[i]][offset] = tree[t].dist[i];
  539. if(tree[t].dist[i] > maxvalue)
  540. {
  541. maxvalue = tree[t].dist[i];
  542. maxindex = labelmapback[i];
  543. }
  544. segresult.setPixel(x,y,maxindex);
  545. }
  546. }
  547. }
  548. }