SemSegContextTree.cpp 49 KB

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