SemSegContextTree3D.cpp 70 KB

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