SemSegContextTree3D.cpp 65 KB

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