SemSegContextTree.cpp 48 KB

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