SemSegContextTree.cpp 66 KB

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