SemSegContextTree3D.cpp 71 KB

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