SemSegContextTree.cpp 65 KB

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