SemSegContextTree.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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 "vislearning/baselib/ColorSpace.h"
  8. #include "objrec/segmentation/RSMeanShift.h"
  9. #include "objrec/segmentation/RSGraphBased.h"
  10. #include "core/basics/numerictools.h"
  11. #include "core/basics/StringTools.h"
  12. #include "core/basics/FileName.h"
  13. #include "vislearning/baselib/ICETools.h"
  14. #include "core/basics/Timer.h"
  15. #include "core/basics/vectorio.h"
  16. #include "core/image/FilterT.h"
  17. #include <omp.h>
  18. #include <iostream>
  19. #undef WRITEGLOB
  20. #undef TEXTONMAP
  21. #define DEBUG
  22. using namespace OBJREC;
  23. using namespace std;
  24. using namespace NICE;
  25. SemSegContextTree::SemSegContextTree (const Config *conf, const MultiDataset *md)
  26. : SemanticSegmentation (conf, & (md->getClassNames ("train")))
  27. {
  28. this->conf = conf;
  29. string section = "SSContextTree";
  30. lfcw = new LFColorWeijer (conf);
  31. firstiteration = true;
  32. grid = conf->gI (section, "grid", 10);
  33. maxSamples = conf->gI (section, "max_samples", 2000);
  34. minFeats = conf->gI (section, "min_feats", 50);
  35. maxDepth = conf->gI (section, "max_depth", 10);
  36. windowSize = conf->gI (section, "window_size", 16);
  37. featsPerSplit = conf->gI (section, "feats_per_split", 200);
  38. useShannonEntropy = conf->gB (section, "use_shannon_entropy", true);
  39. nbTrees = conf->gI (section, "amount_trees", 1);
  40. string segmentationtype = conf->gS (section, "segmentation_type", "meanshift");
  41. randomTests = conf->gI (section, "random_tests", 10);
  42. bool saveLoadData = conf->gB ("debug", "save_load_data", false);
  43. string fileLocation = conf->gS ("debug", "datafile", "tmp.txt");
  44. pixelWiseLabeling = false;
  45. useRegionFeature = true;
  46. if (segmentationtype == "meanshift")
  47. segmentation = new RSMeanShift (conf);
  48. else if (segmentationtype == "none")
  49. {
  50. segmentation = NULL;
  51. pixelWiseLabeling = true;
  52. useRegionFeature = false;
  53. }
  54. else if (segmentationtype == "felzenszwalb")
  55. segmentation = new RSGraphBased (conf);
  56. else
  57. throw ("no valid segmenation_type\n please choose between none, meanshift and felzenszwalb\n");
  58. ftypes = conf->gI (section, "features", 100);;
  59. string featsec = "Features";
  60. vector<Operation*> tops;
  61. if (conf->gB (featsec, "minus", true))
  62. tops.push_back (new Minus());
  63. if (conf->gB (featsec, "minus_abs", true))
  64. tops.push_back (new MinusAbs());
  65. if (conf->gB (featsec, "addition", true))
  66. tops.push_back (new Addition());
  67. if (conf->gB (featsec, "only1", true))
  68. tops.push_back (new Only1());
  69. if (conf->gB (featsec, "rel_x", true))
  70. tops.push_back (new RelativeXPosition());
  71. if (conf->gB (featsec, "rel_y", true))
  72. tops.push_back (new RelativeYPosition());
  73. ops.push_back (tops);
  74. tops.clear();
  75. tops.push_back (new Equality());
  76. ops.push_back (tops);
  77. tops.clear();
  78. if (conf->gB (featsec, "int", true))
  79. tops.push_back (new IntegralOps());
  80. if (conf->gB (featsec, "bi_int_cent", true))
  81. tops.push_back (new BiIntegralCenteredOps());
  82. if (conf->gB (featsec, "int_cent", true))
  83. tops.push_back (new IntegralCenteredOps());
  84. if (conf->gB (featsec, "haar_horz", true))
  85. tops.push_back (new HaarHorizontal());
  86. if (conf->gB (featsec, "haar_vert", true))
  87. tops.push_back (new HaarVertical());
  88. if (conf->gB (featsec, "haar_diag", true))
  89. tops.push_back (new HaarDiag());
  90. if (conf->gB (featsec, "haar3_horz", true))
  91. tops.push_back (new Haar3Horiz());
  92. if (conf->gB (featsec, "haar3_vert", true))
  93. tops.push_back (new Haar3Vert());
  94. if (conf->gB (featsec, "glob", true))
  95. tops.push_back (new GlobalFeats());
  96. ops.push_back (tops);
  97. ops.push_back (tops);
  98. tops.clear();
  99. if (conf->gB (featsec, "minus", true))
  100. tops.push_back (new Minus());
  101. if (conf->gB (featsec, "minus_abs", true))
  102. tops.push_back (new MinusAbs());
  103. if (conf->gB (featsec, "addition", true))
  104. tops.push_back (new Addition());
  105. if (conf->gB (featsec, "only1", true))
  106. tops.push_back (new Only1());
  107. if (conf->gB (featsec, "rel_x", true))
  108. tops.push_back (new RelativeXPosition());
  109. if (conf->gB (featsec, "rel_y", true))
  110. tops.push_back (new RelativeYPosition());
  111. ops.push_back (tops);
  112. useGradient = conf->gB (featsec, "use_gradient", true);
  113. useWeijer = conf->gB (featsec, "use_weijer", true);
  114. // geometric features of hoiem
  115. useHoiemFeatures = conf->gB (featsec, "use_hoiem_features", false);
  116. if (useHoiemFeatures)
  117. {
  118. hoiemDirectory = conf->gS (featsec, "hoiem_directory");
  119. }
  120. opOverview = vector<int> (NBOPERATIONS, 0);
  121. contextOverview = vector<vector<double> > (maxDepth, vector<double> (2, 0.0));
  122. calcVal.push_back (new MCImageAccess());
  123. calcVal.push_back (new MCImageAccess());
  124. calcVal.push_back (new MCImageAccess());
  125. calcVal.push_back (new MCImageAccess());
  126. calcVal.push_back (new ClassificationResultAccess());
  127. classnames = md->getClassNames ("train");
  128. ///////////////////////////////////
  129. // Train Segmentation Context Trees
  130. ///////////////////////////////////
  131. if (saveLoadData)
  132. {
  133. if (FileMgt::fileExists (fileLocation))
  134. read (fileLocation);
  135. else
  136. {
  137. train (md);
  138. write (fileLocation);
  139. }
  140. }
  141. else
  142. {
  143. train (md);
  144. }
  145. }
  146. SemSegContextTree::~SemSegContextTree()
  147. {
  148. }
  149. double SemSegContextTree::getBestSplit (std::vector<NICE::MultiChannelImageT<double> > &feats, std::vector<NICE::MultiChannelImageT<unsigned short int> > &currentfeats, const std::vector<NICE::MatrixT<int> > &labels, int node, Operation *&splitop, double &splitval, const int &tree)
  150. {
  151. Timer t;
  152. t.start();
  153. int imgCount = 0;
  154. try
  155. {
  156. imgCount = (int)feats.size();
  157. }
  158. catch (Exception)
  159. {
  160. cerr << "no features computed?" << endl;
  161. }
  162. double bestig = -numeric_limits< double >::max();
  163. splitop = NULL;
  164. splitval = -1.0;
  165. set<vector<int> >selFeats;
  166. map<int, int> e;
  167. int featcounter = forest[tree][node].featcounter;
  168. if (featcounter < minFeats)
  169. {
  170. return 0.0;
  171. }
  172. vector<double> fraction (a.size(), 0.0);
  173. for (uint i = 0; i < fraction.size(); i++)
  174. {
  175. if (forbidden_classes.find (labelmapback[i]) != forbidden_classes.end())
  176. fraction[i] = 0;
  177. else
  178. fraction[i] = ((double)maxSamples) / ((double)featcounter * a[i] * a.size());
  179. }
  180. featcounter = 0;
  181. for (int iCounter = 0; iCounter < imgCount; iCounter++)
  182. {
  183. int xsize = (int)currentfeats[iCounter].width();
  184. int ysize = (int)currentfeats[iCounter].height();
  185. for (int x = 0; x < xsize; x++)
  186. {
  187. for (int y = 0; y < ysize; y++)
  188. {
  189. if (currentfeats[iCounter].get (x, y, tree) == node)
  190. {
  191. int cn = labels[iCounter] (x, y);
  192. double randD = (double)rand() / (double)RAND_MAX;
  193. if (labelmap.find (cn) == labelmap.end())
  194. continue;
  195. if (randD < fraction[labelmap[cn]])
  196. {
  197. vector<int> tmp (3, 0);
  198. tmp[0] = iCounter;
  199. tmp[1] = x;
  200. tmp[2] = y;
  201. featcounter++;
  202. selFeats.insert (tmp);
  203. e[cn]++;
  204. }
  205. }
  206. }
  207. }
  208. }
  209. map<int, int>::iterator mapit;
  210. double globent = 0.0;
  211. for (mapit = e.begin() ; mapit != e.end(); mapit++)
  212. {
  213. double p = (double)(*mapit).second / (double)featcounter;
  214. globent += p * log2 (p);
  215. }
  216. globent = -globent;
  217. if (globent < 0.5)
  218. {
  219. return 0.0;
  220. }
  221. /** vector of all possible features */
  222. std::vector<Operation*> featsel;
  223. for (int i = 0; i < featsPerSplit; i++)
  224. {
  225. int x1, x2, y1, y2;
  226. int ft = (int)((double)rand() / (double)RAND_MAX * (double)ftypes);
  227. int tmpws = windowSize;
  228. if (ft > 1 && firstiteration)
  229. ft = 0;
  230. if (channelsPerType[ft].size() == 0)
  231. {
  232. ft = 0;
  233. }
  234. if (ft > 1)
  235. {
  236. //use larger window size for context features
  237. tmpws *= 4;
  238. }
  239. x1 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  240. x2 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  241. y1 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  242. y2 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  243. int f1 = (int)((double)rand() / (double)RAND_MAX * (double)channelsPerType[ft].size());
  244. int f2 = f1;
  245. if((double)rand() / (double)RAND_MAX > 0.5)
  246. f2 = (int)((double)rand() / (double)RAND_MAX * (double)channelsPerType[ft].size());
  247. int o = (int)((double)rand() / (double)RAND_MAX * (double)ops[ft].size());
  248. Operation *op = ops[ft][o]->clone();
  249. op->set(x1, y1, x2, y2, channelsPerType[ft][f1], channelsPerType[ft][f2], calcVal[ft]);
  250. op->setFeatType(ft);
  251. if (ft == 3 || ft == 4)
  252. op->setContext(true);
  253. else
  254. op->setContext(false);
  255. featsel.push_back (op);
  256. }
  257. for (int f = 0; f < featsPerSplit; f++)
  258. {
  259. double l_bestig = -numeric_limits< double >::max();
  260. double l_splitval = -1.0;
  261. set<vector<int> >::iterator it;
  262. vector<double> vals;
  263. double maxval = -numeric_limits<double>::max();
  264. double minval = numeric_limits<double>::max();
  265. for (it = selFeats.begin() ; it != selFeats.end(); it++)
  266. {
  267. Features feat;
  268. feat.feats = &feats[ (*it) [0]];
  269. feat.cfeats = &currentfeats[ (*it) [0]];
  270. feat.cTree = tree;
  271. feat.tree = &forest[tree];
  272. double val = featsel[f]->getVal (feat, (*it) [1], (*it) [2]);
  273. vals.push_back (val);
  274. maxval = std::max (val, maxval);
  275. minval = std::min (val, minval);
  276. }
  277. if (minval == maxval)
  278. continue;
  279. double scale = maxval - minval;
  280. vector<double> splits;
  281. for (int r = 0; r < randomTests; r++)
  282. {
  283. splits.push_back (((double)rand() / (double)RAND_MAX*scale) + minval);
  284. }
  285. for (int run = 0 ; run < randomTests; run++)
  286. {
  287. set<vector<int> >::iterator it2;
  288. double val = splits[run];
  289. map<int, int> eL, eR;
  290. int counterL = 0, counterR = 0;
  291. int counter2 = 0;
  292. for (it2 = selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++)
  293. {
  294. int cn = labels[ (*it2) [0]] ((*it2) [1], (*it2) [2]);
  295. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  296. if (vals[counter2] < val)
  297. {
  298. //left entropie:
  299. eL[cn] = eL[cn] + 1;
  300. counterL++;
  301. }
  302. else
  303. {
  304. //right entropie:
  305. eR[cn] = eR[cn] + 1;
  306. counterR++;
  307. }
  308. }
  309. double leftent = 0.0;
  310. for (mapit = eL.begin() ; mapit != eL.end(); mapit++)
  311. {
  312. double p = (double)(*mapit).second / (double)counterL;
  313. leftent -= p * log2 (p);
  314. }
  315. double rightent = 0.0;
  316. for (mapit = eR.begin() ; mapit != eR.end(); mapit++)
  317. {
  318. double p = (double)(*mapit).second / (double)counterR;
  319. rightent -= p * log2 (p);
  320. }
  321. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  322. double pl = (double)counterL / (double)(counterL + counterR);
  323. double ig = globent - (1.0 - pl) * rightent - pl * leftent;
  324. //double ig = globent - rightent - leftent;
  325. if (useShannonEntropy)
  326. {
  327. double esplit = - (pl * log (pl) + (1 - pl) * log (1 - pl));
  328. ig = 2 * ig / (globent + esplit);
  329. }
  330. if (ig > l_bestig)
  331. {
  332. l_bestig = ig;
  333. l_splitval = val;
  334. }
  335. }
  336. if (l_bestig > bestig)
  337. {
  338. bestig = l_bestig;
  339. splitop = featsel[f];
  340. splitval = l_splitval;
  341. }
  342. }
  343. //FIXME: delete all features!
  344. /*for(int i = 0; i < featsPerSplit; i++)
  345. {
  346. if(featsel[i] != splitop)
  347. delete featsel[i];
  348. }*/
  349. #ifdef DEBUG
  350. //cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  351. #endif
  352. return bestig;
  353. }
  354. inline double SemSegContextTree::getMeanProb (const int &x, const int &y, const int &channel, const MultiChannelImageT<unsigned short int> &currentfeats)
  355. {
  356. double val = 0.0;
  357. for (int tree = 0; tree < nbTrees; tree++)
  358. {
  359. val += forest[tree][currentfeats.get (x,y,tree) ].dist[channel];
  360. }
  361. return val / (double)nbTrees;
  362. }
  363. void SemSegContextTree::computeIntegralImage (const NICE::MultiChannelImageT<SparseVectorInt> &infeats, NICE::MultiChannelImageT<SparseVectorInt> &integralImage)
  364. {
  365. int xsize = infeats.width();
  366. int ysize = infeats.height();
  367. integralImage (0, 0).add (infeats.get (0, 0));
  368. //first column
  369. for (int y = 1; y < ysize; y++)
  370. {
  371. integralImage (0, y).add (infeats.get (0, y));
  372. integralImage (0, y).add (integralImage (0, y - 1));
  373. }
  374. //first row
  375. for (int x = 1; x < xsize; x++)
  376. {
  377. integralImage (x, 0).add (infeats.get (x, 0));
  378. integralImage (x, 0).add (integralImage (x - 1, 0));
  379. }
  380. //rest
  381. for (int y = 1; y < ysize; y++)
  382. {
  383. for (int x = 1; x < xsize; x++)
  384. {
  385. integralImage (x, y).add (infeats.get (x, y));
  386. integralImage (x, y).add (integralImage (x, y - 1));
  387. integralImage (x, y).add (integralImage (x - 1, y));
  388. integralImage (x, y).sub (integralImage (x - 1, y - 1));
  389. }
  390. }
  391. }
  392. void SemSegContextTree::computeIntegralImage (const NICE::MultiChannelImageT<unsigned short int> &currentfeats, NICE::MultiChannelImageT<double> &feats, int firstChannel)
  393. {
  394. int xsize = currentfeats.width();
  395. int ysize = currentfeats.height();
  396. xsize = feats.width();
  397. ysize = feats.height();
  398. if (firstiteration)
  399. {
  400. #pragma omp parallel for
  401. for (int it = 0; it < (int)integralMap.size(); it++)
  402. {
  403. int corg = integralMap[it].first;
  404. int cint = integralMap[it].second;
  405. for (int y = 0; y < ysize; y++)
  406. {
  407. for (int x = 0; x < xsize; x++)
  408. {
  409. feats(x,y,cint) = feats(x,y,corg);
  410. }
  411. }
  412. feats.calcIntegral(cint);
  413. }
  414. }
  415. int channels = (int)forest[0][0].dist.size();
  416. #pragma omp parallel for
  417. for (int c = 0; c < channels; c++)
  418. {
  419. feats (0, 0, firstChannel + c) = getMeanProb (0, 0, c, currentfeats);
  420. //first column
  421. for (int y = 1; y < ysize; y++)
  422. {
  423. feats (0, y, firstChannel + c) = getMeanProb (0, y, c, currentfeats)
  424. + feats (0, y - 1, firstChannel + c);
  425. }
  426. //first row
  427. for (int x = 1; x < xsize; x++)
  428. {
  429. feats (x, 0, firstChannel + c) = getMeanProb (x, 0, c, currentfeats)
  430. + feats (x - 1, 0, firstChannel + c);
  431. }
  432. //rest
  433. for (int y = 1; y < ysize; y++)
  434. {
  435. for (int x = 1; x < xsize; x++)
  436. {
  437. feats (x, y, firstChannel + c) = getMeanProb (x, y, c, currentfeats)
  438. + feats (x, y - 1, firstChannel + c)
  439. + feats (x - 1, y, firstChannel + c)
  440. - feats (x - 1, y - 1, firstChannel + c);
  441. }
  442. }
  443. }
  444. }
  445. inline double computeWeight (const double &d, const double &dim)
  446. {
  447. return 1.0 / (pow (2, (double)(dim - d + 1)));
  448. }
  449. void SemSegContextTree::train (const MultiDataset *md)
  450. {
  451. Timer timer;
  452. timer.start();
  453. const LabeledSet train = * (*md) ["train"];
  454. const LabeledSet *trainp = &train;
  455. ProgressBar pb ("compute feats");
  456. pb.show();
  457. //TODO: Speichefresser!, lohnt sich sparse?
  458. vector<MultiChannelImageT<double> > allfeats;
  459. vector<MultiChannelImageT<unsigned short int> > currentfeats;
  460. vector<MatrixT<int> > labels;
  461. #ifdef TEXTONMAP
  462. vector<MultiChannelImageT<SparseVectorInt> > textonMap;
  463. vector<MultiChannelImageT<SparseVectorInt> > integralTexton;
  464. #endif
  465. std::string forbidden_classes_s = conf->gS ("analysis", "donttrain", "");
  466. if (forbidden_classes_s == "")
  467. {
  468. forbidden_classes_s = conf->gS ("analysis", "forbidden_classes", "");
  469. }
  470. classnames.getSelection (forbidden_classes_s, forbidden_classes);
  471. int imgcounter = 0;
  472. int amountPixels = 0;
  473. LOOP_ALL_S (*trainp)
  474. {
  475. EACH_INFO (classno, info);
  476. NICE::ColorImage img;
  477. std::string currentFile = info.img();
  478. CachedExample *ce = new CachedExample (currentFile);
  479. const LocalizationResult *locResult = info.localization();
  480. if (locResult->size() <= 0)
  481. {
  482. fprintf (stderr, "WARNING: NO ground truth polygons found for %s !\n",
  483. currentFile.c_str());
  484. continue;
  485. }
  486. fprintf (stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str());
  487. int xsize, ysize;
  488. ce->getImageSize (xsize, ysize);
  489. amountPixels += xsize * ysize;
  490. MatrixT<int> tmpMat (xsize, ysize);
  491. currentfeats.push_back (MultiChannelImageT<unsigned short int> (xsize, ysize, nbTrees));
  492. currentfeats[imgcounter].setAll (0);
  493. #ifdef TEXTONMAP
  494. textonMap.push_back (MultiChannelImageT<SparseVectorInt> (xsize / grid + 1, ysize / grid + 1, 1));
  495. integralTexton.push_back (MultiChannelImageT<SparseVectorInt> (xsize / grid + 1, ysize / grid + 1, 1));
  496. #endif
  497. labels.push_back (tmpMat);
  498. try {
  499. img = ColorImage (currentFile);
  500. } catch (Exception) {
  501. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  502. continue;
  503. }
  504. Globals::setCurrentImgFN (currentFile);
  505. //TODO: resize image?!
  506. MultiChannelImageT<double> feats;
  507. allfeats.push_back (feats);
  508. // read image and do some simple transformations
  509. extractBasicFeatures (allfeats[imgcounter], img, currentFile);
  510. // getting groundtruth
  511. NICE::Image pixelLabels (xsize, ysize);
  512. pixelLabels.set (0);
  513. locResult->calcLabeledImage (pixelLabels, (*classNames).getBackgroundClass());
  514. for (int x = 0; x < xsize; x++)
  515. {
  516. for (int y = 0; y < ysize; y++)
  517. {
  518. classno = pixelLabels.getPixel (x, y);
  519. labels[imgcounter] (x, y) = classno;
  520. if (forbidden_classes.find (classno) != forbidden_classes.end())
  521. continue;
  522. labelcounter[classno]++;
  523. }
  524. }
  525. imgcounter++;
  526. pb.update (trainp->count());
  527. delete ce;
  528. }
  529. pb.hide();
  530. map<int, int>::iterator mapit;
  531. int classes = 0;
  532. for (mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  533. {
  534. labelmap[mapit->first] = classes;
  535. labelmapback[classes] = mapit->first;
  536. classes++;
  537. }
  538. ////////////////////////////////////////////////////
  539. //define which featurextraction methods should be used for each channel
  540. rawChannels = 3;
  541. // how many channels without integral image
  542. int shift = 0;
  543. if (useGradient)
  544. rawChannels *= 2;
  545. if (useWeijer)
  546. rawChannels += 11;
  547. if (useHoiemFeatures)
  548. rawChannels += 8;
  549. // gray value images
  550. for (int i = 0; i < rawChannels; i++)
  551. {
  552. channelType.push_back (0);
  553. }
  554. // regions
  555. if (useRegionFeature)
  556. {
  557. channelType.push_back (1);
  558. shift++;
  559. }
  560. for (int i = 0; i < rawChannels; i++)
  561. {
  562. channelType.push_back (2);
  563. }
  564. // integral images
  565. for (int i = 0; i < classes; i++)
  566. {
  567. channelType.push_back (3);
  568. }
  569. integralMap.clear();
  570. int integralImageAmount = rawChannels;
  571. for (int ii = 0; ii < integralImageAmount; ii++)
  572. {
  573. integralMap.push_back (pair<int, int> (ii, ii + integralImageAmount + shift));
  574. }
  575. int amountTypes = 5;
  576. channelsPerType = vector<vector<int> > (amountTypes, vector<int>());
  577. for (int i = 0; i < (int)channelType.size(); i++)
  578. {
  579. channelsPerType[channelType[i]].push_back (i);
  580. }
  581. for (int i = 0; i < classes; i++)
  582. {
  583. channelsPerType[channelsPerType.size()-1].push_back (i);
  584. }
  585. ftypes = std::min (amountTypes, ftypes);
  586. ////////////////////////////////////////////////////
  587. //balancing
  588. int featcounter = 0;
  589. a = vector<double> (classes, 0.0);
  590. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  591. {
  592. int xsize = (int)currentfeats[iCounter].width();
  593. int ysize = (int)currentfeats[iCounter].height();
  594. for (int x = 0; x < xsize; x++)
  595. {
  596. for (int y = 0; y < ysize; y++)
  597. {
  598. featcounter++;
  599. int cn = labels[iCounter] (x, y);
  600. if (labelmap.find (cn) == labelmap.end())
  601. continue;
  602. a[labelmap[cn]] ++;
  603. }
  604. }
  605. }
  606. for (int i = 0; i < (int)a.size(); i++)
  607. {
  608. a[i] /= (double)featcounter;
  609. }
  610. #ifdef DEBUG
  611. for (int i = 0; i < (int)a.size(); i++)
  612. {
  613. cout << "a[" << i << "]: " << a[i] << endl;
  614. }
  615. cout << "a.size: " << a.size() << endl;
  616. #endif
  617. depth = 0;
  618. int uniquenumber = 0;
  619. for (int t = 0; t < nbTrees; t++)
  620. {
  621. vector<TreeNode> tree;
  622. tree.push_back (TreeNode());
  623. tree[0].dist = vector<double> (classes, 0.0);
  624. tree[0].depth = depth;
  625. tree[0].featcounter = amountPixels;
  626. tree[0].nodeNumber = uniquenumber;
  627. uniquenumber++;
  628. forest.push_back (tree);
  629. }
  630. vector<int> startnode (nbTrees, 0);
  631. bool allleaf = false;
  632. //int baseFeatSize = allfeats[0].size();
  633. timer.stop();
  634. cerr << "preprocessing finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  635. timer.start();
  636. while (!allleaf && depth < maxDepth)
  637. {
  638. depth++;
  639. #ifdef DEBUG
  640. cout << "depth: " << depth << endl;
  641. #endif
  642. allleaf = true;
  643. vector<MultiChannelImageT<unsigned short int> > lastfeats = currentfeats;
  644. #if 1
  645. Timer timerDepth;
  646. timerDepth.start();
  647. #endif
  648. double weight = computeWeight (depth, maxDepth) - computeWeight (depth - 1, maxDepth);
  649. if (depth == 1)
  650. {
  651. weight = computeWeight (1, maxDepth);
  652. }
  653. // omp_set_dynamic(0);
  654. //#pragma omp parallel for
  655. for (int tree = 0; tree < nbTrees; tree++)
  656. {
  657. const int t = (int)forest[tree].size();
  658. const int s = startnode[tree];
  659. startnode[tree] = t;
  660. #pragma omp parallel for
  661. for (int i = s; i < t; i++)
  662. {
  663. if (!forest[tree][i].isleaf && forest[tree][i].left < 0)
  664. {
  665. Operation *splitfeat = NULL;
  666. double splitval;
  667. double bestig = getBestSplit (allfeats, lastfeats, labels, i, splitfeat, splitval, tree);
  668. for (int ii = 0; ii < (int)lastfeats.size(); ii++)
  669. {
  670. for (int c = 0; c < lastfeats[ii].channels(); c++)
  671. {
  672. short unsigned int minv, maxv;
  673. lastfeats[ii].statistics (minv, maxv, c);
  674. }
  675. }
  676. forest[tree][i].feat = splitfeat;
  677. forest[tree][i].decision = splitval;
  678. if (splitfeat != NULL)
  679. {
  680. allleaf = false;
  681. int left;
  682. #pragma omp critical
  683. {
  684. left = forest[tree].size();
  685. forest[tree].push_back (TreeNode());
  686. forest[tree].push_back (TreeNode());
  687. }
  688. int right = left + 1;
  689. forest[tree][i].left = left;
  690. forest[tree][i].right = right;
  691. forest[tree][left].dist = vector<double> (classes, 0.0);
  692. forest[tree][right].dist = vector<double> (classes, 0.0);
  693. forest[tree][left].depth = depth;
  694. forest[tree][right].depth = depth;
  695. forest[tree][left].featcounter = 0;
  696. forest[tree][right].featcounter = 0;
  697. forest[tree][left].nodeNumber = uniquenumber;
  698. int leftu = uniquenumber;
  699. uniquenumber++;
  700. forest[tree][right].nodeNumber = uniquenumber;
  701. int rightu = uniquenumber;
  702. uniquenumber++;
  703. forest[tree][right].featcounter = 0;
  704. #pragma omp parallel for
  705. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  706. {
  707. int xsize = currentfeats[iCounter].width();
  708. int ysize = currentfeats[iCounter].height();
  709. for (int x = 0; x < xsize; x++)
  710. {
  711. for (int y = 0; y < ysize; y++)
  712. {
  713. if (currentfeats[iCounter].get (x, y, tree) == i)
  714. {
  715. Features feat;
  716. feat.feats = &allfeats[iCounter];
  717. feat.cfeats = &lastfeats[iCounter];
  718. feat.cTree = tree;
  719. feat.tree = &forest[tree];
  720. double val = splitfeat->getVal (feat, x, y);
  721. //int subx = x / grid;
  722. //int suby = y / grid;
  723. #pragma omp critical
  724. if (val < splitval)
  725. {
  726. currentfeats[iCounter].set (x, y, left, tree);
  727. if (labelmap.find (labels[iCounter] (x, y)) != labelmap.end())
  728. forest[tree][left].dist[labelmap[labels[iCounter] (x, y) ]]++;
  729. forest[tree][left].featcounter++;
  730. SparseVectorInt v;
  731. v.insert (pair<int, double> (leftu, weight));
  732. #ifdef TEXTONMAP
  733. textonMap[iCounter] (subx, suby).add (v);
  734. #endif
  735. }
  736. else
  737. {
  738. currentfeats[iCounter].set (x, y, right, tree);
  739. if (labelmap.find (labels[iCounter] (x, y)) != labelmap.end())
  740. forest[tree][right].dist[labelmap[labels[iCounter] (x, y) ]]++;
  741. forest[tree][right].featcounter++;
  742. //feld im subsampled finden und in diesem rechts hochzählen
  743. SparseVectorInt v;
  744. v.insert (pair<int, double> (rightu, weight));
  745. #ifdef TEXTONMAP
  746. textonMap[iCounter] (subx, suby).add (v);
  747. #endif
  748. }
  749. }
  750. }
  751. }
  752. }
  753. double lcounter = 0.0, rcounter = 0.0;
  754. for (uint d = 0; d < forest[tree][left].dist.size(); d++)
  755. {
  756. if (forbidden_classes.find (labelmapback[d]) != forbidden_classes.end())
  757. {
  758. forest[tree][left].dist[d] = 0;
  759. forest[tree][right].dist[d] = 0;
  760. }
  761. else
  762. {
  763. forest[tree][left].dist[d] /= a[d];
  764. lcounter += forest[tree][left].dist[d];
  765. forest[tree][right].dist[d] /= a[d];
  766. rcounter += forest[tree][right].dist[d];
  767. }
  768. }
  769. if (lcounter <= 0 || rcounter <= 0)
  770. {
  771. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  772. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  773. cout << "bestig: " << bestig << endl;
  774. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  775. {
  776. int xsize = currentfeats[iCounter].width();
  777. int ysize = currentfeats[iCounter].height();
  778. int counter = 0;
  779. for (int x = 0; x < xsize; x++)
  780. {
  781. for (int y = 0; y < ysize; y++)
  782. {
  783. if (lastfeats[iCounter].get (x, y, tree) == i)
  784. {
  785. if (++counter > 30)
  786. break;
  787. Features feat;
  788. feat.feats = &allfeats[iCounter];
  789. feat.cfeats = &lastfeats[iCounter];
  790. feat.cTree = tree;
  791. feat.tree = &forest[tree];
  792. double val = splitfeat->getVal (feat, x, y);
  793. cout << "splitval: " << splitval << " val: " << val << endl;
  794. }
  795. }
  796. }
  797. }
  798. assert (lcounter > 0 && rcounter > 0);
  799. }
  800. for (uint d = 0; d < forest[tree][left].dist.size(); d++)
  801. {
  802. forest[tree][left].dist[d] /= lcounter;
  803. forest[tree][right].dist[d] /= rcounter;
  804. }
  805. }
  806. else
  807. {
  808. forest[tree][i].isleaf = true;
  809. }
  810. }
  811. }
  812. }
  813. //compute integral images
  814. if (firstiteration)
  815. {
  816. for (int i = 0; i < imgcounter; i++)
  817. {
  818. allfeats[i].addChannel ((int)(classes + rawChannels));
  819. }
  820. }
  821. for (int i = 0; i < imgcounter; i++)
  822. {
  823. computeIntegralImage (currentfeats[i], allfeats[i], channelType.size() - classes);
  824. #ifdef TEXTONMAP
  825. computeIntegralImage (textonMap[i], integralTexton[i]);
  826. #endif
  827. }
  828. if(firstiteration)
  829. {
  830. firstiteration = false;
  831. }
  832. #if 1
  833. timerDepth.stop();
  834. cout << "time for depth " << depth << ": " << timerDepth.getLastAbsolute() << endl;
  835. #endif
  836. }
  837. timer.stop();
  838. cerr << "learning finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  839. timer.start();
  840. #ifdef WRITEGLOB
  841. ofstream outstream ("globtrain.feat");
  842. for (int i = 0; i < textonMap.size(); i++)
  843. {
  844. set<int> usedclasses;
  845. for (uint x = 0; x < labels[i].rows(); x++)
  846. {
  847. for (uint y = 0; y < labels[i].cols(); y++)
  848. {
  849. int classno = labels[i] (x, y);
  850. if (forbidden_classes.find (classno) != forbidden_classes.end())
  851. continue;
  852. usedclasses.insert (classno);
  853. }
  854. }
  855. cout << "labels.cols: " << labels[i].cols() << " labels.rows " << labels[i].rows() << endl;
  856. cout << "currentfeats : " << allfeats[i].width() << " allfeats[i].height(); " << allfeats[i].height() << endl;
  857. set<int>::iterator it;
  858. for (it = usedclasses.begin() ; it != usedclasses.end(); it++)
  859. outstream << *it << " ";
  860. outstream << endl;
  861. integralTexton[i] (integralTexton[i].width() - 1, integralTexton[i].height() - 1).store (outstream);
  862. }
  863. outstream.close();
  864. #endif
  865. cout << "uniquenumber " << uniquenumber << endl;
  866. //getchar();
  867. #ifdef DEBUG
  868. for (int tree = 0; tree < nbTrees; tree++)
  869. {
  870. int t = (int)forest[tree].size();
  871. for (int i = 0; i < t; i++)
  872. {
  873. printf ("tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right);
  874. if (!forest[tree][i].isleaf && forest[tree][i].left != -1)
  875. {
  876. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  877. opOverview[forest[tree][i].feat->getOps() ]++;
  878. contextOverview[forest[tree][i].depth][ (int)forest[tree][i].feat->getContext() ]++;
  879. }
  880. for (int d = 0; d < (int)forest[tree][i].dist.size(); d++)
  881. {
  882. cout << " " << forest[tree][i].dist[d];
  883. }
  884. cout << endl;
  885. }
  886. }
  887. std::map<int,int> featTypeCounter;
  888. for (int tree = 0; tree < nbTrees; tree++)
  889. {
  890. int t = (int)forest[tree].size();
  891. for (int i = 0; i < t; i++)
  892. {
  893. if (!forest[tree][i].isleaf && forest[tree][i].left != -1)
  894. {
  895. featTypeCounter[forest[tree][i].feat->getFeatType()]+=1;
  896. }
  897. }
  898. }
  899. cout << "evaluation of featuretypes" << endl;
  900. for(map<int,int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++)
  901. {
  902. cerr << it->first << ": " << it->second << endl;
  903. }
  904. for (uint c = 0; c < ops.size(); c++)
  905. {
  906. for (int t = 0; t < ops[c].size(); t++)
  907. {
  908. cout << ops[c][t]->writeInfos() << ": " << opOverview[ops[c][t]->getOps() ] << endl;
  909. }
  910. }
  911. for (int d = 0; d < maxDepth; d++)
  912. {
  913. double sum = contextOverview[d][0] + contextOverview[d][1];
  914. contextOverview[d][0] /= sum;
  915. contextOverview[d][1] /= sum;
  916. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  917. }
  918. #endif
  919. timer.stop();
  920. cerr << "rest finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  921. timer.start();
  922. }
  923. void SemSegContextTree::extractBasicFeatures (NICE::MultiChannelImageT<double> &feats, const ColorImage &img, const string &currentFile)
  924. {
  925. int xsize = img.width();
  926. int ysize = img.height();
  927. //TODO: resize image?!
  928. feats.reInit (xsize, ysize, 3);
  929. for (int x = 0; x < xsize; x++)
  930. {
  931. for (int y = 0; y < ysize; y++)
  932. {
  933. for (int r = 0; r < 3; r++)
  934. {
  935. feats.set (x, y, img.getPixel (x, y, r), r);
  936. }
  937. }
  938. }
  939. feats = ColorSpace::rgbtolab (feats);
  940. if (useGradient)
  941. {
  942. int currentsize = feats.channels();
  943. feats.addChannel (currentsize);
  944. for (int c = 0; c < currentsize; c++)
  945. {
  946. ImageT<double> tmp = feats[c];
  947. ImageT<double> tmp2 = feats[c+currentsize];
  948. NICE::FilterT<double, double, double>::gradientStrength (tmp, tmp2);
  949. }
  950. }
  951. if (useWeijer)
  952. {
  953. NICE::MultiChannelImageT<double> cfeats;
  954. lfcw->getFeats (img, cfeats);
  955. feats.addChannel (cfeats);
  956. }
  957. // read the geometric cues produced by Hoiem et al.
  958. if (useHoiemFeatures)
  959. {
  960. // we could also give the following set as a config option
  961. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  962. vector<string> hoiemClasses;
  963. StringTools::split (hoiemClasses_s, ' ', hoiemClasses);
  964. // Now we have to do some fancy regular expressions :)
  965. // Original image filename: basel_000083.jpg
  966. // hoiem result: basel_000083_c_sky.png
  967. // Fancy class of Ferid which supports string handling especially for filenames
  968. FileName fn (currentFile);
  969. fn.removeExtension();
  970. FileName fnBase = fn.extractFileName();
  971. // counter for the channel index, starts with the current size of the destination multi-channel image
  972. int currentChannel = feats.channels();
  973. // add a channel for each feature in advance
  974. feats.addChannel (hoiemClasses.size());
  975. // loop through all geometric categories and add the images
  976. for (vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++)
  977. {
  978. string hoiemClass = *i;
  979. FileName fnConfidenceImage (hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png");
  980. if (! fnConfidenceImage.fileExists())
  981. {
  982. fthrow (Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << currentFile << ")");
  983. } else {
  984. Image confidenceImage (fnConfidenceImage.str());
  985. // check whether the image size is consistent
  986. if (confidenceImage.width() != feats.width() || confidenceImage.height() != feats.height())
  987. {
  988. fthrow (Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str());
  989. }
  990. ImageT<double> dst = feats[currentChannel];
  991. // copy standard image to double image
  992. for (uint y = 0 ; y < (uint) confidenceImage.height(); y++)
  993. for (uint x = 0 ; x < (uint) confidenceImage.width(); x++)
  994. feats (x, y, currentChannel) = (double)confidenceImage (x, y);
  995. }
  996. }
  997. }
  998. }
  999. void SemSegContextTree::semanticseg (CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities)
  1000. {
  1001. int xsize;
  1002. int ysize;
  1003. ce->getImageSize (xsize, ysize);
  1004. firstiteration = true;
  1005. int classes = labelmapback.size();
  1006. int numClasses = classNames->numClasses();
  1007. fprintf (stderr, "ContextTree classification !\n");
  1008. probabilities.reInit (xsize, ysize, numClasses);
  1009. probabilities.setAll (0);
  1010. #ifdef TEXTONMAP
  1011. MultiChannelImageT<SparseVectorInt> textonMap (xsize / grid + 1, ysize / grid + 1, 1);
  1012. MultiChannelImageT<SparseVectorInt> integralTexton (xsize / grid + 1, ysize / grid + 1, 1);
  1013. #endif
  1014. std::string currentFile = Globals::getCurrentImgFN();
  1015. MultiChannelImageT<double> feats;
  1016. NICE::ColorImage img;
  1017. try {
  1018. img = ColorImage (currentFile);
  1019. } catch (Exception) {
  1020. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  1021. return;
  1022. }
  1023. extractBasicFeatures (feats, img, currentFile); //read image and do some simple transformations
  1024. bool allleaf = false;
  1025. MultiChannelImageT<unsigned short int> currentfeats (xsize, ysize, nbTrees);
  1026. currentfeats.setAll (0);
  1027. depth = 0;
  1028. for (int d = 0; d < maxDepth && !allleaf; d++)
  1029. {
  1030. depth++;
  1031. #ifdef TEXTONMAP
  1032. double weight = computeWeight (depth, maxDepth) - computeWeight (depth - 1, maxDepth);
  1033. if (depth == 1)
  1034. {
  1035. weight = computeWeight (1, maxDepth);
  1036. }
  1037. #endif
  1038. allleaf = true;
  1039. MultiChannelImageT<unsigned short int> lastfeats = currentfeats;
  1040. int tree;
  1041. #pragma omp parallel for private(tree)
  1042. for (tree = 0; tree < nbTrees; tree++)
  1043. {
  1044. for (int x = 0; x < xsize; x++)
  1045. {
  1046. for (int y = 0; y < ysize; y++)
  1047. {
  1048. int t = currentfeats.get (x, y, tree);
  1049. if (forest[tree][t].left > 0)
  1050. {
  1051. allleaf = false;
  1052. Features feat;
  1053. feat.feats = &feats;
  1054. feat.cfeats = &lastfeats;
  1055. feat.cTree = tree;
  1056. feat.tree = &forest[tree];
  1057. double val = forest[tree][t].feat->getVal (feat, x, y);
  1058. //int subx = x / grid;
  1059. //int suby = y / grid;
  1060. if (val < forest[tree][t].decision)
  1061. {
  1062. currentfeats.set (x, y, forest[tree][t].left, tree);
  1063. #ifdef TEXTONMAP
  1064. #pragma omp critical
  1065. {
  1066. SparseVectorInt v;
  1067. v.insert (pair<int, double> (forest[tree][forest[tree][t].left].nodeNumber, weight));
  1068. textonMap (subx, suby).add (v);
  1069. }
  1070. #endif
  1071. }
  1072. else
  1073. {
  1074. currentfeats.set (x, y, forest[tree][t].right, tree);
  1075. #ifdef TEXTONMAP
  1076. #pragma omp critical
  1077. {
  1078. SparseVectorInt v;
  1079. v.insert (pair<int, double> (forest[tree][forest[tree][t].right].nodeNumber, weight));
  1080. textonMap (subx, suby).add (v);
  1081. }
  1082. #endif
  1083. }
  1084. }
  1085. }
  1086. }
  1087. }
  1088. if (depth < maxDepth)
  1089. {
  1090. //compute integral images
  1091. if (firstiteration)
  1092. {
  1093. feats.addChannel (classes + rawChannels);
  1094. }
  1095. computeIntegralImage (currentfeats, feats, channelType.size() - classes);
  1096. #ifdef TEXTONMAP
  1097. computeIntegralImage (textonMap, integralTexton);
  1098. #endif
  1099. if(firstiteration)
  1100. {
  1101. firstiteration = false;
  1102. }
  1103. }
  1104. }
  1105. #ifdef WRITEGLOB
  1106. ofstream outstream ("globtest.feat", ofstream::app);
  1107. outstream << 0 << endl;
  1108. integralTexton (integralTexton.width() - 1, integralTexton.height() - 1).store (outstream);
  1109. outstream.close();
  1110. #endif
  1111. string cndir = conf->gS ("SSContextTree", "cndir", "");
  1112. int allClasses = (int)probabilities.channels();
  1113. vector<int> useclass (allClasses, 1);
  1114. #ifdef WRITEGLOB
  1115. std::vector< std::string > list;
  1116. StringTools::split (currentFile, '/', list);
  1117. string orgname = list.back();
  1118. ofstream ostream ("filelist.txt", ofstream::app);
  1119. ostream << orgname << ".dat" << endl;
  1120. ostream.close();
  1121. if (cndir != "")
  1122. {
  1123. useclass = vector<int> (allClasses, 0);
  1124. ifstream infile ((cndir + "/" + orgname + ".dat").c_str());
  1125. #undef OLD
  1126. #ifdef OLD
  1127. while (!infile.eof() && infile.good())
  1128. {
  1129. int tmp;
  1130. infile >> tmp;
  1131. assert (tmp >= 0 && tmp < allClasses);
  1132. useclass[tmp] = 1;
  1133. }
  1134. #else
  1135. int c = 0;
  1136. vector<double> probs (allClasses, 0.0);
  1137. while (!infile.eof() && infile.good())
  1138. {
  1139. infile >> probs[c];
  1140. c++;
  1141. }
  1142. vector<double> sorted = probs;
  1143. sort (sorted.begin(), sorted.end());
  1144. double thr = sorted[10];
  1145. if (thr < 0.0)
  1146. thr = 0.0;
  1147. for (int c = 0; c < allClasses; c++)
  1148. {
  1149. if (probs[c] < thr)
  1150. {
  1151. useclass[c] = 1;
  1152. }
  1153. }
  1154. #endif
  1155. for (int c = 0; c < allClasses; c++)
  1156. {
  1157. if (useclass[c] == 0)
  1158. {
  1159. probabilities.set (-numeric_limits< double >::max(), c);
  1160. }
  1161. }
  1162. }
  1163. #endif
  1164. if (pixelWiseLabeling)
  1165. {
  1166. //finales labeln:
  1167. //long int offset = 0;
  1168. for (int x = 0; x < xsize; x++)
  1169. {
  1170. for (int y = 0; y < ysize; y++)
  1171. {
  1172. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1173. int maxindex = 0;
  1174. uint s = forest[0][0].dist.size();
  1175. for (uint i = 0; i < s; i++)
  1176. {
  1177. int currentclass = labelmapback[i];
  1178. if (useclass[currentclass])
  1179. {
  1180. probabilities (x, y, currentclass) = getMeanProb (x, y, i, currentfeats);
  1181. if (probabilities (x, y, currentclass) > maxvalue)
  1182. {
  1183. maxvalue = probabilities (x, y, currentclass);
  1184. maxindex = currentclass;
  1185. }
  1186. }
  1187. }
  1188. segresult.setPixel (x, y, maxindex);
  1189. if (maxvalue > 1)
  1190. cout << "maxvalue: " << maxvalue << endl;
  1191. }
  1192. }
  1193. #undef VISUALIZE
  1194. #ifdef VISUALIZE
  1195. for (int j = 0 ; j < (int)probabilities.numChannels; j++)
  1196. {
  1197. //cout << "class: " << j << endl;//" " << cn.text (j) << endl;
  1198. NICE::Matrix tmp (probabilities.height(), probabilities.width());
  1199. double maxval = -numeric_limits<double>::max();
  1200. double minval = numeric_limits<double>::max();
  1201. for (int y = 0; y < probabilities.height(); y++)
  1202. for (int x = 0; x < probabilities.width(); x++)
  1203. {
  1204. double val = probabilities (x, y, j);
  1205. tmp (y, x) = val;
  1206. maxval = std::max (val, maxval);
  1207. minval = std::min (val, minval);
  1208. }
  1209. tmp (0, 0) = 1.0;
  1210. tmp (0, 1) = 0.0;
  1211. NICE::ColorImage imgrgb (probabilities.width(), probabilities.height());
  1212. ICETools::convertToRGB (tmp, imgrgb);
  1213. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text (j) << endl;
  1214. std::string s;
  1215. std::stringstream out;
  1216. out << "tmpprebmap" << j << ".ppm";
  1217. s = out.str();
  1218. imgrgb.write (s);
  1219. //showImage(imgrgb, "Ergebnis");
  1220. //getchar();
  1221. }
  1222. cout << "fertsch" << endl;
  1223. getchar();
  1224. cout << "weiter gehtsch" << endl;
  1225. #endif
  1226. }
  1227. else
  1228. {
  1229. //final labeling using segmentation
  1230. Matrix regions;
  1231. //showImage(img);
  1232. int regionNumber = segmentation->segRegions (img, regions);
  1233. cout << "regions: " << regionNumber << endl;
  1234. int dSize = forest[0][0].dist.size();
  1235. vector<vector<double> > regionProbs (regionNumber, vector<double> (dSize, 0.0));
  1236. vector<int> bestlabels (regionNumber, 0);
  1237. for (int y = 0; y < img.height(); y++)
  1238. {
  1239. for (int x = 0; x < img.width(); x++)
  1240. {
  1241. int cregion = regions (x, y);
  1242. for (int d = 0; d < dSize; d++)
  1243. {
  1244. regionProbs[cregion][d] += getMeanProb (x, y, d, currentfeats);
  1245. }
  1246. }
  1247. }
  1248. for (int r = 0; r < regionNumber; r++)
  1249. {
  1250. double maxval = regionProbs[r][0];
  1251. bestlabels[r] = 0;
  1252. for (int d = 1; d < dSize; d++)
  1253. {
  1254. if (maxval < regionProbs[r][d])
  1255. {
  1256. maxval = regionProbs[r][d];
  1257. bestlabels[r] = d;
  1258. }
  1259. }
  1260. bestlabels[r] = labelmapback[bestlabels[r]];
  1261. }
  1262. for (int y = 0; y < img.height(); y++)
  1263. {
  1264. for (int x = 0; x < img.width(); x++)
  1265. {
  1266. segresult.setPixel (x, y, bestlabels[regions (x,y) ]);
  1267. }
  1268. }
  1269. #define WRITEREGIONS
  1270. #ifdef WRITEREGIONS
  1271. RegionGraph rg;
  1272. segmentation->getGraphRepresentation (img, regions, rg);
  1273. for (uint pos = 0; pos < regionProbs.size(); pos++)
  1274. {
  1275. rg[pos]->setProbs (regionProbs[pos]);
  1276. }
  1277. std::string s;
  1278. std::stringstream out;
  1279. std::vector< std::string > list;
  1280. StringTools::split (Globals::getCurrentImgFN (), '/', list);
  1281. out << "rgout/" << list.back() << ".graph";
  1282. string writefile = out.str();
  1283. rg.write (writefile);
  1284. #endif
  1285. }
  1286. cout << "segmentation finished" << endl;
  1287. }
  1288. void SemSegContextTree::store (std::ostream & os, int format) const
  1289. {
  1290. os.precision (numeric_limits<double>::digits10 + 1);
  1291. os << nbTrees << endl;
  1292. classnames.store (os);
  1293. map<int, int>::const_iterator it;
  1294. os << labelmap.size() << endl;
  1295. for (it = labelmap.begin() ; it != labelmap.end(); it++)
  1296. os << (*it).first << " " << (*it).second << endl;
  1297. os << labelmapback.size() << endl;
  1298. for (it = labelmapback.begin() ; it != labelmapback.end(); it++)
  1299. os << (*it).first << " " << (*it).second << endl;
  1300. int trees = forest.size();
  1301. os << trees << endl;
  1302. for (int t = 0; t < trees; t++)
  1303. {
  1304. int nodes = forest[t].size();
  1305. os << nodes << endl;
  1306. for (int n = 0; n < nodes; n++)
  1307. {
  1308. os << forest[t][n].left << " " << forest[t][n].right << " " << forest[t][n].decision << " " << forest[t][n].isleaf << " " << forest[t][n].depth << " " << forest[t][n].featcounter << " " << forest[t][n].nodeNumber << endl;
  1309. os << forest[t][n].dist << endl;
  1310. if (forest[t][n].feat == NULL)
  1311. os << -1 << endl;
  1312. else
  1313. {
  1314. os << forest[t][n].feat->getOps() << endl;
  1315. forest[t][n].feat->store (os);
  1316. }
  1317. }
  1318. }
  1319. os << channelType.size() << endl;
  1320. for (int i = 0; i < (int)channelType.size(); i++)
  1321. {
  1322. os << channelType[i] << " ";
  1323. }
  1324. os << endl;
  1325. os << integralMap.size() << endl;
  1326. for (int i = 0; i < (int)integralMap.size(); i++)
  1327. {
  1328. os << integralMap[i].first << " " << integralMap[i].second << endl;
  1329. }
  1330. os << rawChannels << endl;
  1331. }
  1332. void SemSegContextTree::restore (std::istream & is, int format)
  1333. {
  1334. is >> nbTrees;
  1335. classnames.restore (is);
  1336. int lsize;
  1337. is >> lsize;
  1338. labelmap.clear();
  1339. for (int l = 0; l < lsize; l++)
  1340. {
  1341. int first, second;
  1342. is >> first;
  1343. is >> second;
  1344. labelmap[first] = second;
  1345. }
  1346. is >> lsize;
  1347. labelmapback.clear();
  1348. for (int l = 0; l < lsize; l++)
  1349. {
  1350. int first, second;
  1351. is >> first;
  1352. is >> second;
  1353. labelmapback[first] = second;
  1354. }
  1355. int trees;
  1356. is >> trees;
  1357. forest.clear();
  1358. for (int t = 0; t < trees; t++)
  1359. {
  1360. vector<TreeNode> tmptree;
  1361. forest.push_back (tmptree);
  1362. int nodes;
  1363. is >> nodes;
  1364. //cout << "nodes: " << nodes << endl;
  1365. for (int n = 0; n < nodes; n++)
  1366. {
  1367. TreeNode tmpnode;
  1368. forest[t].push_back (tmpnode);
  1369. is >> forest[t][n].left;
  1370. is >> forest[t][n].right;
  1371. is >> forest[t][n].decision;
  1372. is >> forest[t][n].isleaf;
  1373. is >> forest[t][n].depth;
  1374. is >> forest[t][n].featcounter;
  1375. is >> forest[t][n].nodeNumber;
  1376. is >> forest[t][n].dist;
  1377. int feattype;
  1378. is >> feattype;
  1379. assert (feattype < NBOPERATIONS);
  1380. forest[t][n].feat = NULL;
  1381. if (feattype >= 0)
  1382. {
  1383. for (uint o = 0; o < ops.size(); o++)
  1384. {
  1385. for (uint o2 = 0; o2 < ops[o].size(); o2++)
  1386. {
  1387. if (forest[t][n].feat == NULL)
  1388. {
  1389. for (uint c = 0; c < ops[o].size(); c++)
  1390. {
  1391. if (ops[o][o2]->getOps() == feattype)
  1392. {
  1393. forest[t][n].feat = ops[o][o2]->clone();
  1394. break;
  1395. }
  1396. }
  1397. }
  1398. }
  1399. }
  1400. assert (forest[t][n].feat != NULL);
  1401. forest[t][n].feat->restore (is);
  1402. }
  1403. }
  1404. }
  1405. channelType.clear();
  1406. int ctsize;
  1407. is >> ctsize;
  1408. for (int i = 0; i < ctsize; i++)
  1409. {
  1410. int tmp;
  1411. is >> tmp;
  1412. channelType.push_back (tmp);
  1413. }
  1414. integralMap.clear();
  1415. int iMapSize;
  1416. is >> iMapSize;
  1417. for (int i = 0; i < iMapSize; i++)
  1418. {
  1419. int first;
  1420. int second;
  1421. is >> first;
  1422. is >> second;
  1423. integralMap.push_back (pair<int, int> (first, second));
  1424. }
  1425. is >> rawChannels;
  1426. }