SemSegContextTree.cpp 51 KB

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