SemSegContextTree.cpp 51 KB

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