SemSegContextTree3D.cpp 79 KB

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