SemSegContextTree.cpp 49 KB

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