SemSegContextTree3D.cpp 66 KB

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