SemSegContextTree.cpp 58 KB

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