SemSegContextTree.cpp 51 KB

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