SemSegContextTree.cpp 51 KB

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