SemSegContextTree.cpp 47 KB

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