SemSegContextTree.cpp 51 KB

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