SemSegContextTree.cpp 58 KB

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