SemSegContextTree.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  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 = conf->gB (section, "use_region_feat", 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 RegionFeat());
  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, vector<vector<vector<double> > > &regionProbs)
  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 (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. if(ft == 1)
  240. {
  241. if(depth < 8)
  242. {
  243. ft = 0;
  244. }
  245. }
  246. x1 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  247. x2 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  248. y1 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  249. y2 = (int)((double)rand() / (double)RAND_MAX * (double)tmpws) - tmpws / 2;
  250. int f1 = (int)((double)rand() / (double)RAND_MAX * (double)channelsPerType[ft].size());
  251. int f2 = f1;
  252. if ((double)rand() / (double)RAND_MAX > 0.5)
  253. f2 = (int)((double)rand() / (double)RAND_MAX * (double)channelsPerType[ft].size());
  254. int o = (int)((double)rand() / (double)RAND_MAX * (double)ops[ft].size());
  255. f1 = channelsPerType[ft][f1];
  256. f2 = channelsPerType[ft][f2];
  257. if(ft == 1)
  258. {
  259. int classes = (int)regionProbs[0][0].size();
  260. f2 = (int)((double)rand() / (double)RAND_MAX * (double)classes);
  261. }
  262. Operation *op = ops[ft][o]->clone();
  263. op->set(x1, y1, x2, y2, f1, f2, calcVal[ft]);
  264. op->setFeatType(ft);
  265. if (ft == 3 || ft == 4)
  266. op->setContext(true);
  267. else
  268. op->setContext(false);
  269. featsel.push_back (op);
  270. }
  271. for (int f = 0; f < featsPerSplit; f++)
  272. {
  273. double l_bestig = -numeric_limits< double >::max();
  274. double l_splitval = -1.0;
  275. set<vector<int> >::iterator it;
  276. vector<double> vals;
  277. double maxval = -numeric_limits<double>::max();
  278. double minval = numeric_limits<double>::max();
  279. for (it = selFeats.begin() ; it != selFeats.end(); it++)
  280. {
  281. Features feat;
  282. feat.feats = &feats[ (*it) [0]];
  283. feat.cfeats = &currentfeats[ (*it) [0]];
  284. feat.cTree = tree;
  285. feat.tree = &forest[tree];
  286. feat.rProbs = &regionProbs[(*it) [0]];
  287. double val = featsel[f]->getVal (feat, (*it) [1], (*it) [2]);
  288. vals.push_back (val);
  289. maxval = std::max (val, maxval);
  290. minval = std::min (val, minval);
  291. }
  292. if (minval == maxval)
  293. continue;
  294. double scale = maxval - minval;
  295. vector<double> splits;
  296. for (int r = 0; r < randomTests; r++)
  297. {
  298. splits.push_back (((double)rand() / (double)RAND_MAX*scale) + minval);
  299. }
  300. for (int run = 0 ; run < randomTests; run++)
  301. {
  302. set<vector<int> >::iterator it2;
  303. double val = splits[run];
  304. map<int, int> eL, eR;
  305. int counterL = 0, counterR = 0;
  306. int counter2 = 0;
  307. for (it2 = selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++)
  308. {
  309. int cn = labels[ (*it2) [0]] ((*it2) [1], (*it2) [2]);
  310. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  311. if (vals[counter2] < val)
  312. {
  313. //left entropie:
  314. eL[cn] = eL[cn] + 1;
  315. counterL++;
  316. }
  317. else
  318. {
  319. //right entropie:
  320. eR[cn] = eR[cn] + 1;
  321. counterR++;
  322. }
  323. }
  324. double leftent = 0.0;
  325. for (mapit = eL.begin() ; mapit != eL.end(); mapit++)
  326. {
  327. double p = (double)(*mapit).second / (double)counterL;
  328. leftent -= p * log2 (p);
  329. }
  330. double rightent = 0.0;
  331. for (mapit = eR.begin() ; mapit != eR.end(); mapit++)
  332. {
  333. double p = (double)(*mapit).second / (double)counterR;
  334. rightent -= p * log2 (p);
  335. }
  336. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  337. double pl = (double)counterL / (double)(counterL + counterR);
  338. double ig = globent - (1.0 - pl) * rightent - pl * leftent;
  339. //double ig = globent - rightent - leftent;
  340. if (useShannonEntropy)
  341. {
  342. double esplit = - (pl * log (pl) + (1 - pl) * log (1 - pl));
  343. ig = 2 * ig / (globent + esplit);
  344. }
  345. if (ig > l_bestig)
  346. {
  347. l_bestig = ig;
  348. l_splitval = val;
  349. }
  350. }
  351. if (l_bestig > bestig)
  352. {
  353. bestig = l_bestig;
  354. splitop = featsel[f];
  355. splitval = l_splitval;
  356. }
  357. }
  358. //FIXME: delete all features!
  359. /*for(int i = 0; i < featsPerSplit; i++)
  360. {
  361. if(featsel[i] != splitop)
  362. delete featsel[i];
  363. }*/
  364. #ifdef DEBUG
  365. //cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  366. #endif
  367. return bestig;
  368. }
  369. inline double SemSegContextTree::getMeanProb (const int &x, const int &y, const int &channel, const MultiChannelImageT<unsigned short int> &currentfeats)
  370. {
  371. double val = 0.0;
  372. for (int tree = 0; tree < nbTrees; tree++)
  373. {
  374. val += forest[tree][currentfeats.get (x,y,tree) ].dist[channel];
  375. }
  376. return val / (double)nbTrees;
  377. }
  378. void SemSegContextTree::computeIntegralImage (const NICE::MultiChannelImageT<SparseVectorInt> &infeats, NICE::MultiChannelImageT<SparseVectorInt> &integralImage)
  379. {
  380. int xsize = infeats.width();
  381. int ysize = infeats.height();
  382. integralImage (0, 0).add (infeats.get (0, 0));
  383. //first column
  384. for (int y = 1; y < ysize; y++)
  385. {
  386. integralImage (0, y).add (infeats.get (0, y));
  387. integralImage (0, y).add (integralImage (0, y - 1));
  388. }
  389. //first row
  390. for (int x = 1; x < xsize; x++)
  391. {
  392. integralImage (x, 0).add (infeats.get (x, 0));
  393. integralImage (x, 0).add (integralImage (x - 1, 0));
  394. }
  395. //rest
  396. for (int y = 1; y < ysize; y++)
  397. {
  398. for (int x = 1; x < xsize; x++)
  399. {
  400. integralImage (x, y).add (infeats.get (x, y));
  401. integralImage (x, y).add (integralImage (x, y - 1));
  402. integralImage (x, y).add (integralImage (x - 1, y));
  403. integralImage (x, y).sub (integralImage (x - 1, y - 1));
  404. }
  405. }
  406. }
  407. void SemSegContextTree::computeIntegralImage (const NICE::MultiChannelImageT<unsigned short int> &currentfeats, NICE::MultiChannelImageT<double> &feats, int firstChannel)
  408. {
  409. int xsize = currentfeats.width();
  410. int ysize = currentfeats.height();
  411. xsize = feats.width();
  412. ysize = feats.height();
  413. if (firstiteration)
  414. {
  415. #pragma omp parallel for
  416. for (int it = 0; it < (int)integralMap.size(); it++)
  417. {
  418. int corg = integralMap[it].first;
  419. int cint = integralMap[it].second;
  420. for (int y = 0; y < ysize; y++)
  421. {
  422. for (int x = 0; x < xsize; x++)
  423. {
  424. feats(x, y, cint) = feats(x, y, corg);
  425. }
  426. }
  427. feats.calcIntegral(cint);
  428. }
  429. }
  430. int channels = (int)forest[0][0].dist.size();
  431. #pragma omp parallel for
  432. for (int c = 0; c < channels; c++)
  433. {
  434. feats (0, 0, firstChannel + c) = getMeanProb (0, 0, c, currentfeats);
  435. //first column
  436. for (int y = 1; y < ysize; y++)
  437. {
  438. feats (0, y, firstChannel + c) = getMeanProb (0, y, c, currentfeats)
  439. + feats (0, y - 1, firstChannel + c);
  440. }
  441. //first row
  442. for (int x = 1; x < xsize; x++)
  443. {
  444. feats (x, 0, firstChannel + c) = getMeanProb (x, 0, c, currentfeats)
  445. + feats (x - 1, 0, firstChannel + c);
  446. }
  447. //rest
  448. for (int y = 1; y < ysize; y++)
  449. {
  450. for (int x = 1; x < xsize; x++)
  451. {
  452. feats (x, y, firstChannel + c) = getMeanProb (x, y, c, currentfeats)
  453. + feats (x, y - 1, firstChannel + c)
  454. + feats (x - 1, y, firstChannel + c)
  455. - feats (x - 1, y - 1, firstChannel + c);
  456. }
  457. }
  458. }
  459. }
  460. inline double computeWeight (const double &d, const double &dim)
  461. {
  462. return 1.0 / (pow (2, (double)(dim - d + 1)));
  463. }
  464. void SemSegContextTree::train (const MultiDataset *md)
  465. {
  466. Timer timer;
  467. timer.start();
  468. const LabeledSet train = * (*md) ["train"];
  469. const LabeledSet *trainp = &train;
  470. ProgressBar pb ("compute feats");
  471. pb.show();
  472. //TODO: Speichefresser!, lohnt sich sparse?
  473. vector<MultiChannelImageT<double> > allfeats;
  474. vector<MultiChannelImageT<unsigned short int> > currentfeats;
  475. vector<MatrixT<int> > labels;
  476. #ifdef TEXTONMAP
  477. vector<MultiChannelImageT<SparseVectorInt> > textonMap;
  478. vector<MultiChannelImageT<SparseVectorInt> > integralTexton;
  479. #endif
  480. std::string forbidden_classes_s = conf->gS ("analysis", "donttrain", "");
  481. vector<vector<vector<double> > > regionProbs;
  482. vector<vector<int> > rSize;
  483. vector<int> amountRegionpI;
  484. if (forbidden_classes_s == "")
  485. {
  486. forbidden_classes_s = conf->gS ("analysis", "forbidden_classes", "");
  487. }
  488. classnames.getSelection (forbidden_classes_s, forbidden_classes);
  489. int imgcounter = 0;
  490. int amountPixels = 0;
  491. ////////////////////////////////////////////////////
  492. //define which featurextraction methods should be used for each channel
  493. rawChannels = 3;
  494. // how many channels without integral image
  495. int shift = 0;
  496. if (useGradient)
  497. rawChannels *= 2;
  498. if (useWeijer)
  499. rawChannels += 11;
  500. if (useHoiemFeatures)
  501. rawChannels += 8;
  502. // gray value images
  503. for (int i = 0; i < rawChannels; i++)
  504. {
  505. channelType.push_back (0);
  506. }
  507. // regions
  508. if (useRegionFeature)
  509. {
  510. channelType.push_back (1);
  511. shift++;
  512. }
  513. ///////////////////////////////////////////////////////////////////
  514. LOOP_ALL_S (*trainp)
  515. {
  516. EACH_INFO (classno, info);
  517. NICE::ColorImage img;
  518. std::string currentFile = info.img();
  519. CachedExample *ce = new CachedExample (currentFile);
  520. const LocalizationResult *locResult = info.localization();
  521. if (locResult->size() <= 0)
  522. {
  523. fprintf (stderr, "WARNING: NO ground truth polygons found for %s !\n",
  524. currentFile.c_str());
  525. continue;
  526. }
  527. fprintf (stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str());
  528. int xsize, ysize;
  529. ce->getImageSize (xsize, ysize);
  530. amountPixels += xsize * ysize;
  531. MatrixT<int> tmpMat (xsize, ysize);
  532. currentfeats.push_back (MultiChannelImageT<unsigned short int> (xsize, ysize, nbTrees));
  533. currentfeats[imgcounter].setAll (0);
  534. #ifdef TEXTONMAP
  535. textonMap.push_back (MultiChannelImageT<SparseVectorInt> (xsize / grid + 1, ysize / grid + 1, 1));
  536. integralTexton.push_back (MultiChannelImageT<SparseVectorInt> (xsize / grid + 1, ysize / grid + 1, 1));
  537. #endif
  538. labels.push_back (tmpMat);
  539. try {
  540. img = ColorImage (currentFile);
  541. } catch (Exception) {
  542. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  543. continue;
  544. }
  545. Globals::setCurrentImgFN (currentFile);
  546. //TODO: resize image?!
  547. MultiChannelImageT<double> feats;
  548. allfeats.push_back (feats);
  549. int amountRegions;
  550. // read image and do some simple transformations
  551. extractBasicFeatures (allfeats[imgcounter], img, currentFile, amountRegions);
  552. if (useRegionFeature)
  553. {
  554. amountRegionpI.push_back(amountRegions);
  555. rSize.push_back(vector<int>(amountRegions, 0));
  556. for (int y = 0; y < ysize; y++)
  557. {
  558. for (int x = 0; x < xsize; x++)
  559. {
  560. rSize[imgcounter][allfeats[imgcounter](x, y, rawChannels)]++;
  561. }
  562. }
  563. }
  564. // getting groundtruth
  565. NICE::Image pixelLabels (xsize, ysize);
  566. pixelLabels.set (0);
  567. locResult->calcLabeledImage (pixelLabels, (*classNames).getBackgroundClass());
  568. for (int x = 0; x < xsize; x++)
  569. {
  570. for (int y = 0; y < ysize; y++)
  571. {
  572. classno = pixelLabels.getPixel (x, y);
  573. labels[imgcounter] (x, y) = classno;
  574. if (forbidden_classes.find (classno) != forbidden_classes.end())
  575. continue;
  576. labelcounter[classno]++;
  577. }
  578. }
  579. imgcounter++;
  580. pb.update (trainp->count());
  581. delete ce;
  582. }
  583. pb.hide();
  584. map<int, int>::iterator mapit;
  585. int classes = 0;
  586. for (mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++)
  587. {
  588. labelmap[mapit->first] = classes;
  589. labelmapback[classes] = mapit->first;
  590. classes++;
  591. }
  592. ///////////////////////////////////////////////////////////////////
  593. for (int i = 0; i < rawChannels; i++)
  594. {
  595. channelType.push_back (2);
  596. }
  597. // integral images
  598. for (int i = 0; i < classes; i++)
  599. {
  600. channelType.push_back (3);
  601. }
  602. integralMap.clear();
  603. int integralImageAmount = rawChannels;
  604. for (int ii = 0; ii < integralImageAmount; ii++)
  605. {
  606. integralMap.push_back (pair<int, int> (ii, ii + integralImageAmount + shift));
  607. }
  608. int amountTypes = 5;
  609. channelsPerType = vector<vector<int> > (amountTypes, vector<int>());
  610. for (int i = 0; i < (int)channelType.size(); i++)
  611. {
  612. channelsPerType[channelType[i]].push_back (i);
  613. }
  614. for (int i = 0; i < classes; i++)
  615. {
  616. channelsPerType[channelsPerType.size()-1].push_back (i);
  617. }
  618. ftypes = std::min (amountTypes, ftypes);
  619. ////////////////////////////////////////////////////
  620. if (useRegionFeature)
  621. {
  622. for (int a = 0; a < (int)amountRegionpI.size(); a++)
  623. {
  624. regionProbs.push_back(vector<vector<double> > (amountRegionpI[a], vector<double> (classes, 0.0)));
  625. }
  626. }
  627. //balancing
  628. int featcounter = 0;
  629. a = vector<double> (classes, 0.0);
  630. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  631. {
  632. int xsize = (int)currentfeats[iCounter].width();
  633. int ysize = (int)currentfeats[iCounter].height();
  634. for (int x = 0; x < xsize; x++)
  635. {
  636. for (int y = 0; y < ysize; y++)
  637. {
  638. featcounter++;
  639. int cn = labels[iCounter] (x, y);
  640. if (labelmap.find (cn) == labelmap.end())
  641. continue;
  642. a[labelmap[cn]] ++;
  643. }
  644. }
  645. }
  646. for (int i = 0; i < (int)a.size(); i++)
  647. {
  648. a[i] /= (double)featcounter;
  649. }
  650. #ifdef DEBUG
  651. for (int i = 0; i < (int)a.size(); i++)
  652. {
  653. cout << "a[" << i << "]: " << a[i] << endl;
  654. }
  655. cout << "a.size: " << a.size() << endl;
  656. #endif
  657. depth = 0;
  658. int uniquenumber = 0;
  659. for (int t = 0; t < nbTrees; t++)
  660. {
  661. vector<TreeNode> tree;
  662. tree.push_back (TreeNode());
  663. tree[0].dist = vector<double> (classes, 0.0);
  664. tree[0].depth = depth;
  665. tree[0].featcounter = amountPixels;
  666. tree[0].nodeNumber = uniquenumber;
  667. uniquenumber++;
  668. forest.push_back (tree);
  669. }
  670. vector<int> startnode (nbTrees, 0);
  671. bool allleaf = false;
  672. //int baseFeatSize = allfeats[0].size();
  673. timer.stop();
  674. cerr << "preprocessing finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  675. timer.start();
  676. while (!allleaf && depth < maxDepth)
  677. {
  678. depth++;
  679. #ifdef DEBUG
  680. cout << "depth: " << depth << endl;
  681. #endif
  682. allleaf = true;
  683. vector<MultiChannelImageT<unsigned short int> > lastfeats = currentfeats;
  684. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  685. if (useRegionFeature)
  686. {
  687. int rSize = (int)regionProbs.size();
  688. for (int a = 0; a < rSize; a++)
  689. {
  690. int rSize2 = (int)regionProbs[a].size();
  691. for (int b = 0; b < rSize2; b++)
  692. {
  693. int rSize3 = (int)regionProbs[a][b].size();
  694. for (int c = 0; c < rSize3; c++)
  695. {
  696. regionProbs[a][b][c] = 0.0;
  697. }
  698. }
  699. }
  700. }
  701. #if 1
  702. Timer timerDepth;
  703. timerDepth.start();
  704. #endif
  705. double weight = computeWeight (depth, maxDepth) - computeWeight (depth - 1, maxDepth);
  706. if (depth == 1)
  707. {
  708. weight = computeWeight (1, maxDepth);
  709. }
  710. // omp_set_dynamic(0);
  711. //#pragma omp parallel for
  712. for (int tree = 0; tree < nbTrees; tree++)
  713. {
  714. const int t = (int)forest[tree].size();
  715. const int s = startnode[tree];
  716. startnode[tree] = t;
  717. #pragma omp parallel for
  718. for (int i = s; i < t; i++)
  719. {
  720. if (!forest[tree][i].isleaf && forest[tree][i].left < 0)
  721. {
  722. Operation *splitfeat = NULL;
  723. double splitval;
  724. double bestig = getBestSplit (allfeats, lastfeats, labels, i, splitfeat, splitval, tree, lastRegionProbs);
  725. for (int ii = 0; ii < (int)lastfeats.size(); ii++)
  726. {
  727. for (int c = 0; c < lastfeats[ii].channels(); c++)
  728. {
  729. short unsigned int minv, maxv;
  730. lastfeats[ii].statistics (minv, maxv, c);
  731. }
  732. }
  733. forest[tree][i].feat = splitfeat;
  734. forest[tree][i].decision = splitval;
  735. if (splitfeat != NULL)
  736. {
  737. allleaf = false;
  738. int left;
  739. #pragma omp critical
  740. {
  741. left = forest[tree].size();
  742. forest[tree].push_back (TreeNode());
  743. forest[tree].push_back (TreeNode());
  744. }
  745. int right = left + 1;
  746. forest[tree][i].left = left;
  747. forest[tree][i].right = right;
  748. forest[tree][left].dist = vector<double> (classes, 0.0);
  749. forest[tree][right].dist = vector<double> (classes, 0.0);
  750. forest[tree][left].depth = depth;
  751. forest[tree][right].depth = depth;
  752. forest[tree][left].featcounter = 0;
  753. forest[tree][right].featcounter = 0;
  754. forest[tree][left].nodeNumber = uniquenumber;
  755. int leftu = uniquenumber;
  756. uniquenumber++;
  757. forest[tree][right].nodeNumber = uniquenumber;
  758. int rightu = uniquenumber;
  759. uniquenumber++;
  760. forest[tree][right].featcounter = 0;
  761. #pragma omp parallel for
  762. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  763. {
  764. int xsize = currentfeats[iCounter].width();
  765. int ysize = currentfeats[iCounter].height();
  766. for (int x = 0; x < xsize; x++)
  767. {
  768. for (int y = 0; y < ysize; y++)
  769. {
  770. if (currentfeats[iCounter].get (x, y, tree) == i)
  771. {
  772. Features feat;
  773. feat.feats = &allfeats[iCounter];
  774. feat.cfeats = &lastfeats[iCounter];
  775. feat.cTree = tree;
  776. feat.tree = &forest[tree];
  777. feat.rProbs = &lastRegionProbs[iCounter];
  778. double val = splitfeat->getVal (feat, x, y);
  779. //int subx = x / grid;
  780. //int suby = y / grid;
  781. #pragma omp critical
  782. if (val < splitval)
  783. {
  784. currentfeats[iCounter].set (x, y, left, tree);
  785. if (labelmap.find (labels[iCounter] (x, y)) != labelmap.end())
  786. forest[tree][left].dist[labelmap[labels[iCounter] (x, y) ]]++;
  787. forest[tree][left].featcounter++;
  788. SparseVectorInt v;
  789. v.insert (pair<int, double> (leftu, weight));
  790. #ifdef TEXTONMAP
  791. textonMap[iCounter] (subx, suby).add (v);
  792. #endif
  793. }
  794. else
  795. {
  796. currentfeats[iCounter].set (x, y, right, tree);
  797. if (labelmap.find (labels[iCounter] (x, y)) != labelmap.end())
  798. forest[tree][right].dist[labelmap[labels[iCounter] (x, y) ]]++;
  799. forest[tree][right].featcounter++;
  800. //feld im subsampled finden und in diesem rechts hochzählen
  801. SparseVectorInt v;
  802. v.insert (pair<int, double> (rightu, weight));
  803. #ifdef TEXTONMAP
  804. textonMap[iCounter] (subx, suby).add (v);
  805. #endif
  806. }
  807. }
  808. }
  809. }
  810. }
  811. double lcounter = 0.0, rcounter = 0.0;
  812. for (uint d = 0; d < forest[tree][left].dist.size(); d++)
  813. {
  814. if (forbidden_classes.find (labelmapback[d]) != forbidden_classes.end())
  815. {
  816. forest[tree][left].dist[d] = 0;
  817. forest[tree][right].dist[d] = 0;
  818. }
  819. else
  820. {
  821. forest[tree][left].dist[d] /= a[d];
  822. lcounter += forest[tree][left].dist[d];
  823. forest[tree][right].dist[d] /= a[d];
  824. rcounter += forest[tree][right].dist[d];
  825. }
  826. }
  827. if (lcounter <= 0 || rcounter <= 0)
  828. {
  829. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  830. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  831. cout << "bestig: " << bestig << endl;
  832. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  833. {
  834. int xsize = currentfeats[iCounter].width();
  835. int ysize = currentfeats[iCounter].height();
  836. int counter = 0;
  837. for (int x = 0; x < xsize; x++)
  838. {
  839. for (int y = 0; y < ysize; y++)
  840. {
  841. if (lastfeats[iCounter].get (x, y, tree) == i)
  842. {
  843. if (++counter > 30)
  844. break;
  845. Features feat;
  846. feat.feats = &allfeats[iCounter];
  847. feat.cfeats = &lastfeats[iCounter];
  848. feat.cTree = tree;
  849. feat.tree = &forest[tree];
  850. feat.rProbs = &lastRegionProbs[iCounter];
  851. double val = splitfeat->getVal (feat, x, y);
  852. cout << "splitval: " << splitval << " val: " << val << endl;
  853. }
  854. }
  855. }
  856. }
  857. assert (lcounter > 0 && rcounter > 0);
  858. }
  859. for (uint d = 0; d < forest[tree][left].dist.size(); d++)
  860. {
  861. forest[tree][left].dist[d] /= lcounter;
  862. forest[tree][right].dist[d] /= rcounter;
  863. }
  864. }
  865. else
  866. {
  867. forest[tree][i].isleaf = true;
  868. }
  869. }
  870. }
  871. }
  872. if (useRegionFeature)
  873. {
  874. for (int iCounter = 0; iCounter < imgcounter; iCounter++)
  875. {
  876. int xsize = currentfeats[iCounter].width();
  877. int ysize = currentfeats[iCounter].height();
  878. int counter = 0;
  879. #pragma omp parallel for
  880. for (int x = 0; x < xsize; x++)
  881. {
  882. for (int y = 0; y < ysize; y++)
  883. {
  884. for (int tree = 0; tree < nbTrees; tree++)
  885. {
  886. int node = currentfeats[iCounter].get(x, y, tree);
  887. for (uint d = 0; d < forest[tree][node].dist.size(); d++)
  888. {
  889. regionProbs[iCounter][(int)(allfeats[iCounter](x, y, rawChannels))][d] += forest[tree][node].dist[d];
  890. }
  891. }
  892. }
  893. }
  894. }
  895. int rSize1 = (int)regionProbs.size();
  896. for (int a = 0; a < rSize1; a++)
  897. {
  898. int rSize2 = (int)regionProbs[a].size();
  899. for (int b = 0; b < rSize2; b++)
  900. {
  901. int rSize3 = (int)regionProbs[a][b].size();
  902. for (int c = 0; c < rSize3; c++)
  903. {
  904. regionProbs[a][b][c] /= (double)(rSize[a][b]);
  905. }
  906. }
  907. }
  908. }
  909. //compute integral images
  910. if (firstiteration)
  911. {
  912. for (int i = 0; i < imgcounter; i++)
  913. {
  914. allfeats[i].addChannel ((int)(classes + rawChannels));
  915. }
  916. }
  917. for (int i = 0; i < imgcounter; i++)
  918. {
  919. computeIntegralImage (currentfeats[i], allfeats[i], channelType.size() - classes);
  920. #ifdef TEXTONMAP
  921. computeIntegralImage (textonMap[i], integralTexton[i]);
  922. #endif
  923. }
  924. if (firstiteration)
  925. {
  926. firstiteration = false;
  927. }
  928. #if 1
  929. timerDepth.stop();
  930. cout << "time for depth " << depth << ": " << timerDepth.getLastAbsolute() << endl;
  931. #endif
  932. lastfeats.clear();
  933. lastRegionProbs.clear();
  934. }
  935. timer.stop();
  936. cerr << "learning finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  937. timer.start();
  938. #ifdef WRITEGLOB
  939. ofstream outstream ("globtrain.feat");
  940. for (int i = 0; i < textonMap.size(); i++)
  941. {
  942. set<int> usedclasses;
  943. for (uint x = 0; x < labels[i].rows(); x++)
  944. {
  945. for (uint y = 0; y < labels[i].cols(); y++)
  946. {
  947. int classno = labels[i] (x, y);
  948. if (forbidden_classes.find (classno) != forbidden_classes.end())
  949. continue;
  950. usedclasses.insert (classno);
  951. }
  952. }
  953. cout << "labels.cols: " << labels[i].cols() << " labels.rows " << labels[i].rows() << endl;
  954. cout << "currentfeats : " << allfeats[i].width() << " allfeats[i].height(); " << allfeats[i].height() << endl;
  955. set<int>::iterator it;
  956. for (it = usedclasses.begin() ; it != usedclasses.end(); it++)
  957. outstream << *it << " ";
  958. outstream << endl;
  959. integralTexton[i] (integralTexton[i].width() - 1, integralTexton[i].height() - 1).store (outstream);
  960. }
  961. outstream.close();
  962. #endif
  963. cout << "uniquenumber " << uniquenumber << endl;
  964. //getchar();
  965. #ifdef DEBUG
  966. for (int tree = 0; tree < nbTrees; tree++)
  967. {
  968. int t = (int)forest[tree].size();
  969. for (int i = 0; i < t; i++)
  970. {
  971. printf ("tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right);
  972. if (!forest[tree][i].isleaf && forest[tree][i].left != -1)
  973. {
  974. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  975. opOverview[forest[tree][i].feat->getOps() ]++;
  976. contextOverview[forest[tree][i].depth][ (int)forest[tree][i].feat->getContext() ]++;
  977. }
  978. for (int d = 0; d < (int)forest[tree][i].dist.size(); d++)
  979. {
  980. cout << " " << forest[tree][i].dist[d];
  981. }
  982. cout << endl;
  983. }
  984. }
  985. std::map<int, int> featTypeCounter;
  986. for (int tree = 0; tree < nbTrees; tree++)
  987. {
  988. int t = (int)forest[tree].size();
  989. for (int i = 0; i < t; i++)
  990. {
  991. if (!forest[tree][i].isleaf && forest[tree][i].left != -1)
  992. {
  993. featTypeCounter[forest[tree][i].feat->getFeatType()] += 1;
  994. }
  995. }
  996. }
  997. cout << "evaluation of featuretypes" << endl;
  998. for (map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++)
  999. {
  1000. cerr << it->first << ": " << it->second << endl;
  1001. }
  1002. for (uint c = 0; c < ops.size(); c++)
  1003. {
  1004. for (int t = 0; t < ops[c].size(); t++)
  1005. {
  1006. cout << ops[c][t]->writeInfos() << ": " << opOverview[ops[c][t]->getOps() ] << endl;
  1007. }
  1008. }
  1009. for (int d = 0; d < maxDepth; d++)
  1010. {
  1011. double sum = contextOverview[d][0] + contextOverview[d][1];
  1012. contextOverview[d][0] /= sum;
  1013. contextOverview[d][1] /= sum;
  1014. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  1015. }
  1016. #endif
  1017. timer.stop();
  1018. cerr << "rest finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  1019. timer.start();
  1020. }
  1021. void SemSegContextTree::extractBasicFeatures (NICE::MultiChannelImageT<double> &feats, const ColorImage &img, const string &currentFile, int &amountRegions)
  1022. {
  1023. int xsize = img.width();
  1024. int ysize = img.height();
  1025. //TODO: resize image?!
  1026. feats.reInit (xsize, ysize, 3);
  1027. for (int x = 0; x < xsize; x++)
  1028. {
  1029. for (int y = 0; y < ysize; y++)
  1030. {
  1031. for (int r = 0; r < 3; r++)
  1032. {
  1033. feats.set (x, y, img.getPixel (x, y, r), r);
  1034. }
  1035. }
  1036. }
  1037. feats = ColorSpace::rgbtolab (feats);
  1038. if (useGradient)
  1039. {
  1040. int currentsize = feats.channels();
  1041. feats.addChannel (currentsize);
  1042. for (int c = 0; c < currentsize; c++)
  1043. {
  1044. ImageT<double> tmp = feats[c];
  1045. ImageT<double> tmp2 = feats[c+currentsize];
  1046. NICE::FilterT<double, double, double>::gradientStrength (tmp, tmp2);
  1047. }
  1048. }
  1049. if (useWeijer)
  1050. {
  1051. NICE::MultiChannelImageT<double> cfeats;
  1052. lfcw->getFeats (img, cfeats);
  1053. feats.addChannel (cfeats);
  1054. }
  1055. // read the geometric cues produced by Hoiem et al.
  1056. if (useHoiemFeatures)
  1057. {
  1058. // we could also give the following set as a config option
  1059. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  1060. vector<string> hoiemClasses;
  1061. StringTools::split (hoiemClasses_s, ' ', hoiemClasses);
  1062. // Now we have to do some fancy regular expressions :)
  1063. // Original image filename: basel_000083.jpg
  1064. // hoiem result: basel_000083_c_sky.png
  1065. // Fancy class of Ferid which supports string handling especially for filenames
  1066. FileName fn (currentFile);
  1067. fn.removeExtension();
  1068. FileName fnBase = fn.extractFileName();
  1069. // counter for the channel index, starts with the current size of the destination multi-channel image
  1070. int currentChannel = feats.channels();
  1071. // add a channel for each feature in advance
  1072. feats.addChannel (hoiemClasses.size());
  1073. // loop through all geometric categories and add the images
  1074. for (vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++)
  1075. {
  1076. string hoiemClass = *i;
  1077. FileName fnConfidenceImage (hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png");
  1078. if (! fnConfidenceImage.fileExists())
  1079. {
  1080. fthrow (Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << currentFile << ")");
  1081. } else {
  1082. Image confidenceImage (fnConfidenceImage.str());
  1083. // check whether the image size is consistent
  1084. if (confidenceImage.width() != feats.width() || confidenceImage.height() != feats.height())
  1085. {
  1086. fthrow (Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str());
  1087. }
  1088. ImageT<double> dst = feats[currentChannel];
  1089. // copy standard image to double image
  1090. for (uint y = 0 ; y < (uint) confidenceImage.height(); y++)
  1091. for (uint x = 0 ; x < (uint) confidenceImage.width(); x++)
  1092. feats (x, y, currentChannel) = (double)confidenceImage (x, y);
  1093. }
  1094. }
  1095. }
  1096. if (useRegionFeature)
  1097. {
  1098. //using segmentation
  1099. Matrix regions;
  1100. amountRegions = segmentation->segRegions (img, regions);
  1101. int cchannel = feats.channels();
  1102. feats.addChannel(1);
  1103. for (int y = 0; y < regions.cols(); y++)
  1104. {
  1105. for (int x = 0; x < regions.rows(); x++)
  1106. {
  1107. feats(x, y, cchannel) = regions(x, y);
  1108. }
  1109. }
  1110. }
  1111. else
  1112. {
  1113. amountRegions = -1;
  1114. }
  1115. }
  1116. void SemSegContextTree::semanticseg (CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities)
  1117. {
  1118. int xsize;
  1119. int ysize;
  1120. ce->getImageSize (xsize, ysize);
  1121. firstiteration = true;
  1122. int classes = labelmapback.size();
  1123. int numClasses = classNames->numClasses();
  1124. fprintf (stderr, "ContextTree classification !\n");
  1125. probabilities.reInit (xsize, ysize, numClasses);
  1126. probabilities.setAll (0);
  1127. #ifdef TEXTONMAP
  1128. MultiChannelImageT<SparseVectorInt> textonMap (xsize / grid + 1, ysize / grid + 1, 1);
  1129. MultiChannelImageT<SparseVectorInt> integralTexton (xsize / grid + 1, ysize / grid + 1, 1);
  1130. #endif
  1131. std::string currentFile = Globals::getCurrentImgFN();
  1132. MultiChannelImageT<double> feats;
  1133. NICE::ColorImage img;
  1134. try {
  1135. img = ColorImage (currentFile);
  1136. } catch (Exception) {
  1137. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  1138. return;
  1139. }
  1140. //TODO add to features!
  1141. int amountRegions;
  1142. extractBasicFeatures (feats, img, currentFile, amountRegions); //read image and do some simple transformations
  1143. vector<int> rSize;
  1144. if (useRegionFeature)
  1145. {
  1146. rSize = vector<int>(amountRegions, 0);
  1147. for (int y = 0; y < ysize; y++)
  1148. {
  1149. for (int x = 0; x < xsize; x++)
  1150. {
  1151. rSize[feats(x, y, rawChannels)]++;
  1152. }
  1153. }
  1154. }
  1155. bool allleaf = false;
  1156. MultiChannelImageT<unsigned short int> currentfeats (xsize, ysize, nbTrees);
  1157. currentfeats.setAll (0);
  1158. depth = 0;
  1159. vector<vector<double> > regionProbs;
  1160. if (useRegionFeature)
  1161. {
  1162. regionProbs = vector<vector<double> > (amountRegions, vector<double> (classes, 0.0));
  1163. }
  1164. for (int d = 0; d < maxDepth && !allleaf; d++)
  1165. {
  1166. depth++;
  1167. vector<vector<double> > lastRegionProbs = regionProbs;
  1168. if (useRegionFeature)
  1169. {
  1170. int rSize2 = (int)regionProbs.size();
  1171. for (int b = 0; b < rSize2; b++)
  1172. {
  1173. int rSize3 = (int)regionProbs[b].size();
  1174. for (int c = 0; c < rSize3; c++)
  1175. {
  1176. regionProbs[b][c] = 0.0;
  1177. }
  1178. }
  1179. }
  1180. #ifdef TEXTONMAP
  1181. double weight = computeWeight (depth, maxDepth) - computeWeight (depth - 1, maxDepth);
  1182. if (depth == 1)
  1183. {
  1184. weight = computeWeight (1, maxDepth);
  1185. }
  1186. #endif
  1187. allleaf = true;
  1188. MultiChannelImageT<unsigned short int> lastfeats = currentfeats;
  1189. int tree;
  1190. #pragma omp parallel for private(tree)
  1191. for (tree = 0; tree < nbTrees; tree++)
  1192. {
  1193. for (int x = 0; x < xsize; x++)
  1194. {
  1195. for (int y = 0; y < ysize; y++)
  1196. {
  1197. int t = currentfeats.get (x, y, tree);
  1198. if (forest[tree][t].left > 0)
  1199. {
  1200. allleaf = false;
  1201. Features feat;
  1202. feat.feats = &feats;
  1203. feat.cfeats = &lastfeats;
  1204. feat.cTree = tree;
  1205. feat.tree = &forest[tree];
  1206. feat.rProbs = &lastRegionProbs;
  1207. double val = forest[tree][t].feat->getVal (feat, x, y);
  1208. //int subx = x / grid;
  1209. //int suby = y / grid;
  1210. if (val < forest[tree][t].decision)
  1211. {
  1212. currentfeats.set (x, y, forest[tree][t].left, tree);
  1213. #ifdef TEXTONMAP
  1214. #pragma omp critical
  1215. {
  1216. SparseVectorInt v;
  1217. v.insert (pair<int, double> (forest[tree][forest[tree][t].left].nodeNumber, weight));
  1218. textonMap (subx, suby).add (v);
  1219. }
  1220. #endif
  1221. }
  1222. else
  1223. {
  1224. currentfeats.set (x, y, forest[tree][t].right, tree);
  1225. #ifdef TEXTONMAP
  1226. #pragma omp critical
  1227. {
  1228. SparseVectorInt v;
  1229. v.insert (pair<int, double> (forest[tree][forest[tree][t].right].nodeNumber, weight));
  1230. textonMap (subx, suby).add (v);
  1231. }
  1232. #endif
  1233. }
  1234. }
  1235. }
  1236. }
  1237. }
  1238. if (useRegionFeature)
  1239. {
  1240. int xsize = currentfeats.width();
  1241. int ysize = currentfeats.height();
  1242. int counter = 0;
  1243. #pragma omp parallel for
  1244. for (int x = 0; x < xsize; x++)
  1245. {
  1246. for (int y = 0; y < ysize; y++)
  1247. {
  1248. for (int tree = 0; tree < nbTrees; tree++)
  1249. {
  1250. int node = currentfeats.get(x, y, tree);
  1251. for (uint d = 0; d < forest[tree][node].dist.size(); d++)
  1252. {
  1253. regionProbs[(int)(feats(x, y, rawChannels))][d] += forest[tree][node].dist[d];
  1254. }
  1255. }
  1256. }
  1257. }
  1258. int rSize2 = (int)regionProbs.size();
  1259. for (int b = 0; b < rSize2; b++)
  1260. {
  1261. int rSize3 = (int)regionProbs[b].size();
  1262. for (int c = 0; c < rSize3; c++)
  1263. {
  1264. regionProbs[b][c] /= (double)(rSize[b]);
  1265. }
  1266. }
  1267. }
  1268. if (depth < maxDepth)
  1269. {
  1270. //compute integral images
  1271. if (firstiteration)
  1272. {
  1273. feats.addChannel (classes + rawChannels);
  1274. }
  1275. computeIntegralImage (currentfeats, feats, channelType.size() - classes);
  1276. #ifdef TEXTONMAP
  1277. computeIntegralImage (textonMap, integralTexton);
  1278. #endif
  1279. if (firstiteration)
  1280. {
  1281. firstiteration = false;
  1282. }
  1283. }
  1284. }
  1285. #ifdef WRITEGLOB
  1286. ofstream outstream ("globtest.feat", ofstream::app);
  1287. outstream << 0 << endl;
  1288. integralTexton (integralTexton.width() - 1, integralTexton.height() - 1).store (outstream);
  1289. outstream.close();
  1290. #endif
  1291. string cndir = conf->gS ("SSContextTree", "cndir", "");
  1292. int allClasses = (int)probabilities.channels();
  1293. vector<int> useclass (allClasses, 1);
  1294. #ifdef WRITEGLOB
  1295. std::vector< std::string > list;
  1296. StringTools::split (currentFile, '/', list);
  1297. string orgname = list.back();
  1298. ofstream ostream ("filelist.txt", ofstream::app);
  1299. ostream << orgname << ".dat" << endl;
  1300. ostream.close();
  1301. if (cndir != "")
  1302. {
  1303. useclass = vector<int> (allClasses, 0);
  1304. ifstream infile ((cndir + "/" + orgname + ".dat").c_str());
  1305. #undef OLD
  1306. #ifdef OLD
  1307. while (!infile.eof() && infile.good())
  1308. {
  1309. int tmp;
  1310. infile >> tmp;
  1311. assert (tmp >= 0 && tmp < allClasses);
  1312. useclass[tmp] = 1;
  1313. }
  1314. #else
  1315. int c = 0;
  1316. vector<double> probs (allClasses, 0.0);
  1317. while (!infile.eof() && infile.good())
  1318. {
  1319. infile >> probs[c];
  1320. c++;
  1321. }
  1322. vector<double> sorted = probs;
  1323. sort (sorted.begin(), sorted.end());
  1324. double thr = sorted[10];
  1325. if (thr < 0.0)
  1326. thr = 0.0;
  1327. for (int c = 0; c < allClasses; c++)
  1328. {
  1329. if (probs[c] < thr)
  1330. {
  1331. useclass[c] = 1;
  1332. }
  1333. }
  1334. #endif
  1335. for (int c = 0; c < allClasses; c++)
  1336. {
  1337. if (useclass[c] == 0)
  1338. {
  1339. probabilities.set (-numeric_limits< double >::max(), c);
  1340. }
  1341. }
  1342. }
  1343. #endif
  1344. if (pixelWiseLabeling)
  1345. {
  1346. //finales labeln:
  1347. //long int offset = 0;
  1348. for (int x = 0; x < xsize; x++)
  1349. {
  1350. for (int y = 0; y < ysize; y++)
  1351. {
  1352. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1353. int maxindex = 0;
  1354. for (uint i = 0; i < classes; i++)
  1355. {
  1356. int currentclass = labelmapback[i];
  1357. if (useclass[currentclass])
  1358. {
  1359. probabilities (x, y, currentclass) = getMeanProb (x, y, i, currentfeats);
  1360. if (probabilities (x, y, currentclass) > maxvalue)
  1361. {
  1362. maxvalue = probabilities (x, y, currentclass);
  1363. maxindex = currentclass;
  1364. }
  1365. }
  1366. }
  1367. segresult.setPixel (x, y, maxindex);
  1368. if (maxvalue > 1)
  1369. cout << "maxvalue: " << maxvalue << endl;
  1370. }
  1371. }
  1372. #undef VISUALIZE
  1373. #ifdef VISUALIZE
  1374. for (int j = 0 ; j < (int)probabilities.numChannels; j++)
  1375. {
  1376. //cout << "class: " << j << endl;//" " << cn.text (j) << endl;
  1377. NICE::Matrix tmp (probabilities.height(), probabilities.width());
  1378. double maxval = -numeric_limits<double>::max();
  1379. double minval = numeric_limits<double>::max();
  1380. for (int y = 0; y < probabilities.height(); y++)
  1381. for (int x = 0; x < probabilities.width(); x++)
  1382. {
  1383. double val = probabilities (x, y, j);
  1384. tmp (y, x) = val;
  1385. maxval = std::max (val, maxval);
  1386. minval = std::min (val, minval);
  1387. }
  1388. tmp (0, 0) = 1.0;
  1389. tmp (0, 1) = 0.0;
  1390. NICE::ColorImage imgrgb (probabilities.width(), probabilities.height());
  1391. ICETools::convertToRGB (tmp, imgrgb);
  1392. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text (j) << endl;
  1393. std::string s;
  1394. std::stringstream out;
  1395. out << "tmpprebmap" << j << ".ppm";
  1396. s = out.str();
  1397. imgrgb.write (s);
  1398. //showImage(imgrgb, "Ergebnis");
  1399. //getchar();
  1400. }
  1401. cout << "fertsch" << endl;
  1402. getchar();
  1403. cout << "weiter gehtsch" << endl;
  1404. #endif
  1405. }
  1406. else
  1407. {
  1408. //using segmentation
  1409. Matrix regions;
  1410. if (useRegionFeature)
  1411. {
  1412. int rchannel = -1;
  1413. for (uint i = 0; i < channelType.size(); i++)
  1414. {
  1415. if (channelType[i] == 1)
  1416. {
  1417. rchannel = i;
  1418. break;
  1419. }
  1420. }
  1421. assert(rchannel > -1);
  1422. int xsize = feats.width();
  1423. int ysize = feats.height();
  1424. regions.resize(xsize, ysize);
  1425. for (int y = 0; y < ysize; y++)
  1426. {
  1427. for (int x = 0; x < xsize; x++)
  1428. {
  1429. regions(x, y) = feats(x, y, rchannel);
  1430. }
  1431. }
  1432. }
  1433. else
  1434. {
  1435. amountRegions = segmentation->segRegions (img, regions);
  1436. }
  1437. regionProbs.clear();
  1438. regionProbs = vector<vector<double> >(amountRegions, vector<double> (classes, 0.0));
  1439. vector<int> bestlabels (amountRegions, 0);
  1440. for (int y = 0; y < img.height(); y++)
  1441. {
  1442. for (int x = 0; x < img.width(); x++)
  1443. {
  1444. int cregion = regions (x, y);
  1445. for (int d = 0; d < classes; d++)
  1446. {
  1447. regionProbs[cregion][d] += getMeanProb (x, y, d, currentfeats);
  1448. }
  1449. }
  1450. }
  1451. for (int r = 0; r < amountRegions; r++)
  1452. {
  1453. double maxval = regionProbs[r][0];
  1454. bestlabels[r] = 0;
  1455. for (int d = 1; d < classes; d++)
  1456. {
  1457. if (maxval < regionProbs[r][d])
  1458. {
  1459. maxval = regionProbs[r][d];
  1460. bestlabels[r] = d;
  1461. }
  1462. }
  1463. bestlabels[r] = labelmapback[bestlabels[r]];
  1464. }
  1465. for (int y = 0; y < img.height(); y++)
  1466. {
  1467. for (int x = 0; x < img.width(); x++)
  1468. {
  1469. segresult.setPixel (x, y, bestlabels[regions (x,y) ]);
  1470. }
  1471. }
  1472. #define WRITEREGIONS
  1473. #ifdef WRITEREGIONS
  1474. RegionGraph rg;
  1475. segmentation->getGraphRepresentation (img, regions, rg);
  1476. for (uint pos = 0; pos < regionProbs.size(); pos++)
  1477. {
  1478. rg[pos]->setProbs (regionProbs[pos]);
  1479. }
  1480. std::string s;
  1481. std::stringstream out;
  1482. std::vector< std::string > list;
  1483. StringTools::split (Globals::getCurrentImgFN (), '/', list);
  1484. out << "rgout/" << list.back() << ".graph";
  1485. string writefile = out.str();
  1486. rg.write (writefile);
  1487. #endif
  1488. }
  1489. cout << "segmentation finished" << endl;
  1490. }
  1491. void SemSegContextTree::store (std::ostream & os, int format) const
  1492. {
  1493. os.precision (numeric_limits<double>::digits10 + 1);
  1494. os << nbTrees << endl;
  1495. classnames.store (os);
  1496. map<int, int>::const_iterator it;
  1497. os << labelmap.size() << endl;
  1498. for (it = labelmap.begin() ; it != labelmap.end(); it++)
  1499. os << (*it).first << " " << (*it).second << endl;
  1500. os << labelmapback.size() << endl;
  1501. for (it = labelmapback.begin() ; it != labelmapback.end(); it++)
  1502. os << (*it).first << " " << (*it).second << endl;
  1503. int trees = forest.size();
  1504. os << trees << endl;
  1505. for (int t = 0; t < trees; t++)
  1506. {
  1507. int nodes = forest[t].size();
  1508. os << nodes << endl;
  1509. for (int n = 0; n < nodes; n++)
  1510. {
  1511. 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;
  1512. os << forest[t][n].dist << endl;
  1513. if (forest[t][n].feat == NULL)
  1514. os << -1 << endl;
  1515. else
  1516. {
  1517. os << forest[t][n].feat->getOps() << endl;
  1518. forest[t][n].feat->store (os);
  1519. }
  1520. }
  1521. }
  1522. os << channelType.size() << endl;
  1523. for (int i = 0; i < (int)channelType.size(); i++)
  1524. {
  1525. os << channelType[i] << " ";
  1526. }
  1527. os << endl;
  1528. os << integralMap.size() << endl;
  1529. for (int i = 0; i < (int)integralMap.size(); i++)
  1530. {
  1531. os << integralMap[i].first << " " << integralMap[i].second << endl;
  1532. }
  1533. os << rawChannels << endl;
  1534. }
  1535. void SemSegContextTree::restore (std::istream & is, int format)
  1536. {
  1537. is >> nbTrees;
  1538. classnames.restore (is);
  1539. int lsize;
  1540. is >> lsize;
  1541. labelmap.clear();
  1542. for (int l = 0; l < lsize; l++)
  1543. {
  1544. int first, second;
  1545. is >> first;
  1546. is >> second;
  1547. labelmap[first] = second;
  1548. }
  1549. is >> lsize;
  1550. labelmapback.clear();
  1551. for (int l = 0; l < lsize; l++)
  1552. {
  1553. int first, second;
  1554. is >> first;
  1555. is >> second;
  1556. labelmapback[first] = second;
  1557. }
  1558. int trees;
  1559. is >> trees;
  1560. forest.clear();
  1561. for (int t = 0; t < trees; t++)
  1562. {
  1563. vector<TreeNode> tmptree;
  1564. forest.push_back (tmptree);
  1565. int nodes;
  1566. is >> nodes;
  1567. //cout << "nodes: " << nodes << endl;
  1568. for (int n = 0; n < nodes; n++)
  1569. {
  1570. TreeNode tmpnode;
  1571. forest[t].push_back (tmpnode);
  1572. is >> forest[t][n].left;
  1573. is >> forest[t][n].right;
  1574. is >> forest[t][n].decision;
  1575. is >> forest[t][n].isleaf;
  1576. is >> forest[t][n].depth;
  1577. is >> forest[t][n].featcounter;
  1578. is >> forest[t][n].nodeNumber;
  1579. is >> forest[t][n].dist;
  1580. int feattype;
  1581. is >> feattype;
  1582. assert (feattype < NBOPERATIONS);
  1583. forest[t][n].feat = NULL;
  1584. if (feattype >= 0)
  1585. {
  1586. for (uint o = 0; o < ops.size(); o++)
  1587. {
  1588. for (uint o2 = 0; o2 < ops[o].size(); o2++)
  1589. {
  1590. if (forest[t][n].feat == NULL)
  1591. {
  1592. for (uint c = 0; c < ops[o].size(); c++)
  1593. {
  1594. if (ops[o][o2]->getOps() == feattype)
  1595. {
  1596. forest[t][n].feat = ops[o][o2]->clone();
  1597. break;
  1598. }
  1599. }
  1600. }
  1601. }
  1602. }
  1603. assert (forest[t][n].feat != NULL);
  1604. forest[t][n].feat->restore (is);
  1605. }
  1606. }
  1607. }
  1608. channelType.clear();
  1609. int ctsize;
  1610. is >> ctsize;
  1611. for (int i = 0; i < ctsize; i++)
  1612. {
  1613. int tmp;
  1614. is >> tmp;
  1615. channelType.push_back (tmp);
  1616. }
  1617. integralMap.clear();
  1618. int iMapSize;
  1619. is >> iMapSize;
  1620. for (int i = 0; i < iMapSize; i++)
  1621. {
  1622. int first;
  1623. int second;
  1624. is >> first;
  1625. is >> second;
  1626. integralMap.push_back (pair<int, int> (first, second));
  1627. }
  1628. is >> rawChannels;
  1629. }