SemSegContextTree.cpp 50 KB

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