SemSegContextTree.cpp 50 KB

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