SemSegContextTree.cpp 13 KB

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