SemSegContextTree.cpp 49 KB

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