SemSegContextTree.cpp 50 KB

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