SemSegContextTree3D.cpp 76 KB

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