SemSegContextTree.cpp 65 KB

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