SemSegContextTree.cpp 52 KB

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