SemSegContextTree.cpp 46 KB

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