SemSegContextTree.cpp 58 KB

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