SemSegContextTree3D.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  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 FPCGPHIK ( 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 || useFeat4)
  553. feats ( x, y, z, firstChannel + c ) = val;
  554. }
  555. feats.calcIntegral ( firstChannel + c );
  556. }
  557. }
  558. inline double computeWeight ( const int &d, const int &dim )
  559. {
  560. if (d == 0)
  561. return 0.0;
  562. else
  563. return 1.0 / ( pow ( 2, ( double ) ( dim - d + 1 ) ) );
  564. }
  565. void SemSegContextTree3D::train ( const MultiDataset *md )
  566. {
  567. const LabeledSet *trainp = ( *md ) ["train"];
  568. if ( saveLoadData )
  569. {
  570. if ( FileMgt::fileExists ( fileLocation ) )
  571. read ( fileLocation );
  572. else
  573. {
  574. train ( trainp );
  575. write ( fileLocation );
  576. }
  577. }
  578. else
  579. {
  580. train ( trainp );
  581. }
  582. }
  583. void SemSegContextTree3D::train ( const LabeledSet * trainp )
  584. {
  585. int shortsize = numeric_limits<short>::max();
  586. Timer timer;
  587. timer.start();
  588. vector<int> zsizeVec;
  589. getDepthVector ( trainp, zsizeVec, run3Dseg );
  590. //FIXME: memory usage
  591. vector<MultiChannelImage3DT<double> > allfeats; // Feature Werte
  592. vector<MultiChannelImage3DT<unsigned short int> > nodeIndices; // Zuordnung Knoten/Baum für jeden Pixel
  593. vector<MultiChannelImageT<int> > labels;
  594. // für externen Klassifikator
  595. vector<SparseVector*> globalCategorFeats;
  596. vector<map<int,int> > classesPerImage;
  597. vector<vector<int> > rSize; // anzahl der pixel je region
  598. vector<int> amountRegionpI; // ANZAHL der regionen pro bild (von unsupervised segmentation)
  599. int imgCounter = 0;
  600. int amountPixels = 0;
  601. // How many channels of non-integral type do we have?
  602. if ( imagetype == IMAGETYPE_RGB )
  603. rawChannels = 3;
  604. else
  605. rawChannels = 1;
  606. if ( useGradient )
  607. rawChannels *= 3; // gx, gy, gz
  608. if ( useWeijer ) // Weijer Colornames
  609. rawChannels += 11;
  610. if ( useHoiemFeatures ) // geometrische Kontextmerkmale
  611. rawChannels += 8;
  612. if ( useAdditionalLayer ) // beliebige Merkmale in extra Bilddateien
  613. rawChannels += 1;
  614. ///////////////////////////// read input data /////////////////////////////////
  615. ///////////////////////////////////////////////////////////////////////////////
  616. int depthCount = 0;
  617. vector< string > filelist;
  618. NICE::MultiChannelImageT<int> pixelLabels;
  619. std::map<int, bool> labelExist;
  620. for (LabeledSet::const_iterator it = trainp->begin(); it != trainp->end(); it++)
  621. {
  622. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  623. jt != it->second.end(); jt++)
  624. {
  625. int classno = it->first;
  626. ImageInfo & info = *(*jt);
  627. std::string file = info.img();
  628. filelist.push_back ( file );
  629. depthCount++;
  630. const LocalizationResult *locResult = info.localization();
  631. // getting groundtruth
  632. NICE::ImageT<int> pL;
  633. pL.resize ( locResult->xsize, locResult->ysize );
  634. pL.set ( 0 );
  635. locResult->calcLabeledImage ( pL, ( *classNames ).getBackgroundClass() );
  636. pixelLabels.addChannel ( pL );
  637. if ( locResult->size() <= 0 )
  638. {
  639. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  640. file.c_str() );
  641. continue;
  642. }
  643. fprintf ( stderr, "SSContext: Collecting pixel examples from localization info: %s\n", file.c_str() );
  644. int depthBoundary = 0;
  645. if ( run3Dseg )
  646. {
  647. depthBoundary = zsizeVec[imgCounter];
  648. }
  649. if ( depthCount < depthBoundary ) continue;
  650. // all image slices collected -> make a 3d image
  651. NICE::MultiChannelImage3DT<double> imgData;
  652. make3DImage ( filelist, imgData );
  653. int xsize = imgData.width();
  654. int ysize = imgData.height();
  655. int zsize = imgData.depth();
  656. amountPixels += xsize * ysize * zsize;
  657. MultiChannelImageT<int> tmpMat ( xsize, ysize, ( uint ) zsize );
  658. labels.push_back ( tmpMat );
  659. nodeIndices.push_back ( MultiChannelImage3DT<unsigned short int> ( xsize, ysize, zsize, nbTrees ) );
  660. nodeIndices[imgCounter].setAll ( 0 );
  661. int amountRegions;
  662. // convert color to L*a*b, add selected feature channels
  663. addFeatureMaps ( imgData, filelist, amountRegions );
  664. allfeats.push_back(imgData);
  665. if ( useFeat1 )
  666. {
  667. amountRegionpI.push_back ( amountRegions );
  668. rSize.push_back ( vector<int> ( amountRegions, 0 ) );
  669. }
  670. if ( useCategorization )
  671. {
  672. globalCategorFeats.push_back ( new SparseVector() );
  673. classesPerImage.push_back ( map<int,int>() );
  674. }
  675. for ( int x = 0; x < xsize; x++ )
  676. for ( int y = 0; y < ysize; y++ )
  677. for ( int z = 0; z < zsize; z++ )
  678. {
  679. if ( useFeat1 )
  680. rSize[imgCounter][allfeats[imgCounter] ( x, y, z, rawChannels ) ]++;
  681. if ( run3Dseg )
  682. classno = pixelLabels ( x, y, ( uint ) z );
  683. else
  684. classno = pL.getPixelQuick ( x,y );
  685. labels[imgCounter].set ( x, y, classno, ( uint ) z );
  686. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  687. continue;
  688. labelExist[classno] = true;
  689. if ( useCategorization )
  690. classesPerImage[imgCounter][classno] = 1;
  691. }
  692. filelist.clear();
  693. pixelLabels.reInit ( 0,0,0 );
  694. depthCount = 0;
  695. imgCounter++;
  696. }
  697. }
  698. int classes = 0;
  699. for ( map<int, bool>::const_iterator mapit = labelExist.begin();
  700. mapit != labelExist.end(); mapit++ )
  701. {
  702. labelmap[mapit->first] = classes;
  703. labelmapback[classes] = mapit->first;
  704. classes++;
  705. }
  706. ////////////////////////// channel type configuration /////////////////////////
  707. ///////////////////////////////////////////////////////////////////////////////
  708. unsigned char shift = 0;
  709. std::vector<int> rawChannelsIdx, numClassesIdx;
  710. int idx = 0;
  711. for ( int i = 0; i < rawChannels; i++, idx++ )
  712. rawChannelsIdx.push_back ( idx );
  713. for ( int i = 0; i < classes; i++, idx++ )
  714. numClassesIdx.push_back ( idx );
  715. /** Type 0: single pixel & pixel-comparison features on gray value channels */
  716. // actual values derived from integral values
  717. channelsPerType.push_back ( rawChannelsIdx );
  718. /** Type 1: region channel with unsupervised segmentation */
  719. if ( useFeat1 )
  720. {
  721. channelsPerType.push_back ( vector<int>(1, rawChannels) );
  722. shift = 1;
  723. }
  724. else
  725. channelsPerType.push_back ( vector<int>() );
  726. /** Type 2: rectangular and Haar-like features on gray value integral channels */
  727. if ( useFeat2 )
  728. channelsPerType.push_back ( rawChannelsIdx );
  729. else
  730. channelsPerType.push_back ( vector<int>() );
  731. /** Type 3: type 2 features on integral probability channels (context) */
  732. if ( useFeat3 )
  733. channelsPerType.push_back ( numClassesIdx );
  734. else
  735. channelsPerType.push_back ( vector<int>() );
  736. /** Type 4: type 0 features on probability channels (context) */
  737. // Type 4 channels are now INTEGRAL
  738. // This remains for compatibility reasons.
  739. if ( useFeat4 )
  740. channelsPerType.push_back ( numClassesIdx );
  741. else
  742. channelsPerType.push_back ( vector<int>() );
  743. ///////////////////////////////////////////////////////////////////////////////
  744. ///////////////////////////////////////////////////////////////////////////////
  745. vector<vector<vector<double> > > regionProbs;
  746. if ( useFeat1 )
  747. {
  748. for ( int i = 0; i < imgCounter; i++ )
  749. {
  750. regionProbs.push_back ( vector<vector<double> > ( amountRegionpI[i], vector<double> ( classes, 0.0 ) ) );
  751. }
  752. }
  753. //balancing
  754. a = vector<double> ( classes, 0.0 );
  755. int selectionCounter = 0;
  756. for ( int iCounter = 0; iCounter < imgCounter; iCounter++ )
  757. {
  758. int xsize = ( int ) nodeIndices[iCounter].width();
  759. int ysize = ( int ) nodeIndices[iCounter].height();
  760. int zsize = ( int ) nodeIndices[iCounter].depth();
  761. for ( int x = 0; x < xsize; x++ )
  762. for ( int y = 0; y < ysize; y++ )
  763. for ( int z = 0; z < zsize; z++ )
  764. {
  765. int cn = labels[iCounter] ( x, y, ( uint ) z );
  766. if ( labelmap.find ( cn ) == labelmap.end() )
  767. continue;
  768. a[labelmap[cn]] ++;
  769. selectionCounter++;
  770. }
  771. }
  772. for ( int i = 0; i < ( int ) a.size(); i++ )
  773. a[i] /= ( double ) selectionCounter;
  774. #ifdef VERBOSE
  775. cout << "\nDistribution:" << endl;
  776. for ( int i = 0; i < ( int ) a.size(); i++ )
  777. cout << "class '" << classNames->code(labelmapback[i]) << "': "
  778. << a[i] << endl;
  779. #endif
  780. depth = 0;
  781. uniquenumber = 0;
  782. //initialize random forest
  783. for ( int t = 0; t < nbTrees; t++ )
  784. {
  785. vector<TreeNode> singletree;
  786. singletree.push_back ( TreeNode() );
  787. singletree[0].dist = vector<double> ( classes, 0.0 );
  788. singletree[0].depth = depth;
  789. singletree[0].featcounter = amountPixels;
  790. singletree[0].nodeNumber = uniquenumber;
  791. uniquenumber++;
  792. forest.push_back ( singletree );
  793. }
  794. vector<int> startnode ( nbTrees, 0 );
  795. bool noNewSplit = false;
  796. timer.stop();
  797. cout << "\nTime for Pre-Processing: " << timer.getLastAbsolute() << " seconds\n" << endl;
  798. //////////////////////////// train the classifier ///////////////////////////
  799. /////////////////////////////////////////////////////////////////////////////
  800. timer.start();
  801. while ( !noNewSplit && (depth < maxDepth) )
  802. {
  803. depth++;
  804. #ifdef DEBUG
  805. cout << "depth: " << depth << endl;
  806. #endif
  807. noNewSplit = true;
  808. vector<MultiChannelImage3DT<unsigned short int> > lastNodeIndices = nodeIndices;
  809. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  810. if ( useFeat1 )
  811. for ( int i = 0; i < imgCounter; i++ )
  812. {
  813. int numRegions = (int) regionProbs[i].size();
  814. for ( int r = 0; r < numRegions; r++ )
  815. for ( int c = 0; c < classes; c++ )
  816. regionProbs[i][r][c] = 0.0;
  817. }
  818. // initialize & update context channels
  819. for ( int i = 0; i < imgCounter; i++)
  820. if ( useFeat3 || useFeat4 )
  821. this->updateProbabilityMaps ( nodeIndices[i], allfeats[i], rawChannels + shift );
  822. #ifdef VERBOSE
  823. Timer timerDepth;
  824. timerDepth.start();
  825. #endif
  826. double weight = computeWeight ( depth, maxDepth )
  827. - computeWeight ( depth - 1, maxDepth );
  828. #pragma omp parallel for
  829. // for each tree
  830. for ( int tree = 0; tree < nbTrees; tree++ )
  831. {
  832. const int t = ( int ) forest[tree].size();
  833. const int s = startnode[tree];
  834. startnode[tree] = t;
  835. double bestig;
  836. // for each node
  837. for ( int node = s; node < t; node++ )
  838. {
  839. if ( !forest[tree][node].isleaf && forest[tree][node].left < 0 )
  840. {
  841. // find best split
  842. Operation3D *splitfeat = NULL;
  843. double splitval;
  844. bestig = getBestSplit ( allfeats, lastNodeIndices, labels, node,
  845. splitfeat, splitval, tree, lastRegionProbs );
  846. forest[tree][node].feat = splitfeat;
  847. forest[tree][node].decision = splitval;
  848. // split the node
  849. if ( splitfeat != NULL )
  850. {
  851. noNewSplit = false;
  852. int left;
  853. #pragma omp critical
  854. {
  855. left = forest[tree].size();
  856. forest[tree].push_back ( TreeNode() );
  857. forest[tree].push_back ( TreeNode() );
  858. }
  859. int right = left + 1;
  860. forest[tree][node].left = left;
  861. forest[tree][node].right = right;
  862. forest[tree][left].init( depth, classes, uniquenumber);
  863. int leftu = uniquenumber;
  864. uniquenumber++;
  865. forest[tree][right].init( depth, classes, uniquenumber);
  866. int rightu = uniquenumber;
  867. uniquenumber++;
  868. #pragma omp parallel for
  869. for ( int i = 0; i < imgCounter; i++ )
  870. {
  871. int xsize = nodeIndices[i].width();
  872. int ysize = nodeIndices[i].height();
  873. int zsize = nodeIndices[i].depth();
  874. for ( int x = 0; x < xsize; x++ )
  875. {
  876. for ( int y = 0; y < ysize; y++ )
  877. {
  878. for ( int z = 0; z < zsize; z++ )
  879. {
  880. if ( nodeIndices[i].get ( x, y, z, tree ) == node )
  881. {
  882. // get feature value
  883. Features feat;
  884. feat.feats = &allfeats[i];
  885. feat.rProbs = &lastRegionProbs[i];
  886. double val = 0.0;
  887. val = splitfeat->getVal ( feat, x, y, z );
  888. if ( !isfinite ( val ) ) val = 0.0;
  889. #pragma omp critical
  890. {
  891. int curLabel = labels[i] ( x, y, ( uint ) z );
  892. // traverse to left child
  893. if ( val < splitval )
  894. {
  895. nodeIndices[i].set ( x, y, z, left, tree );
  896. if ( labelmap.find ( curLabel ) != labelmap.end() )
  897. forest[tree][left].dist[labelmap[curLabel]]++;
  898. forest[tree][left].featcounter++;
  899. if ( useCategorization && leftu < shortsize )
  900. ( *globalCategorFeats[i] ) [leftu]+=weight;
  901. }
  902. // traverse to right child
  903. else
  904. {
  905. nodeIndices[i].set ( x, y, z, right, tree );
  906. if ( labelmap.find ( curLabel ) != labelmap.end() )
  907. forest[tree][right].dist[labelmap[curLabel]]++;
  908. forest[tree][right].featcounter++;
  909. if ( useCategorization && rightu < shortsize )
  910. ( *globalCategorFeats[i] ) [rightu]+=weight;
  911. }
  912. }
  913. }
  914. }
  915. }
  916. }
  917. }
  918. // normalize distributions in child leaves
  919. double lcounter = 0.0, rcounter = 0.0;
  920. for ( int c = 0; c < (int)forest[tree][left].dist.size(); c++ )
  921. {
  922. if ( forbidden_classes.find ( labelmapback[c] ) != forbidden_classes.end() )
  923. {
  924. forest[tree][left].dist[c] = 0;
  925. forest[tree][right].dist[c] = 0;
  926. }
  927. else
  928. {
  929. forest[tree][left].dist[c] /= a[c];
  930. lcounter += forest[tree][left].dist[c];
  931. forest[tree][right].dist[c] /= a[c];
  932. rcounter += forest[tree][right].dist[c];
  933. }
  934. }
  935. assert ( lcounter > 0 && rcounter > 0 );
  936. for ( int c = 0; c < classes; c++ )
  937. {
  938. forest[tree][left].dist[c] /= lcounter;
  939. forest[tree][right].dist[c] /= rcounter;
  940. }
  941. }
  942. else
  943. {
  944. forest[tree][node].isleaf = true;
  945. }
  946. }
  947. }
  948. }
  949. if ( useFeat1 )
  950. {
  951. for ( int i = 0; i < imgCounter; i++ )
  952. {
  953. int xsize = nodeIndices[i].width();
  954. int ysize = nodeIndices[i].height();
  955. int zsize = nodeIndices[i].depth();
  956. #pragma omp parallel for
  957. // set region probability distribution
  958. for ( int x = 0; x < xsize; x++ )
  959. {
  960. for ( int y = 0; y < ysize; y++ )
  961. {
  962. for ( int z = 0; z < zsize; z++ )
  963. {
  964. for ( int tree = 0; tree < nbTrees; tree++ )
  965. {
  966. int node = nodeIndices[i].get ( x, y, z, tree );
  967. for ( int c = 0; c < classes; c++ )
  968. {
  969. int r = (int) ( allfeats[i] ( x, y, z, rawChannels ) );
  970. regionProbs[i][r][c] += forest[tree][node].dist[c];
  971. }
  972. }
  973. }
  974. }
  975. }
  976. // normalize distribution
  977. int numRegions = (int) regionProbs[i].size();
  978. for ( int r = 0; r < numRegions; r++ )
  979. {
  980. for ( int c = 0; c < classes; c++ )
  981. {
  982. regionProbs[i][r][c] /= ( double ) ( rSize[i][r] );
  983. }
  984. }
  985. }
  986. }
  987. if ( firstiteration ) firstiteration = false;
  988. #ifdef VERBOSE
  989. timerDepth.stop();
  990. cout << "Depth " << depth << ": " << timerDepth.getLastAbsolute() << " seconds" <<endl;
  991. #endif
  992. lastNodeIndices.clear();
  993. lastRegionProbs.clear();
  994. }
  995. timer.stop();
  996. cout << "Time for Learning: " << timer.getLastAbsolute() << " seconds\n" << endl;
  997. //////////////////////// classification using HIK ///////////////////////////
  998. /////////////////////////////////////////////////////////////////////////////
  999. if ( useCategorization && fasthik != NULL )
  1000. {
  1001. timer.start();
  1002. uniquenumber = std::min ( shortsize, uniquenumber );
  1003. for ( uint i = 0; i < globalCategorFeats.size(); i++ )
  1004. {
  1005. globalCategorFeats[i]->setDim ( uniquenumber );
  1006. globalCategorFeats[i]->normalize();
  1007. }
  1008. map<int,Vector> ys;
  1009. int cCounter = 0;
  1010. for ( map<int,int>::const_iterator it = labelmap.begin();
  1011. it != labelmap.end(); it++, cCounter++ )
  1012. {
  1013. ys[cCounter] = Vector ( globalCategorFeats.size() );
  1014. for ( int i = 0; i < imgCounter; i++ )
  1015. {
  1016. if ( classesPerImage[i].find ( it->first ) != classesPerImage[i].end() )
  1017. {
  1018. ys[cCounter][i] = 1;
  1019. }
  1020. else
  1021. {
  1022. ys[cCounter][i] = -1;
  1023. }
  1024. }
  1025. }
  1026. fasthik->train( reinterpret_cast<vector<const NICE::SparseVector *>&>(globalCategorFeats), ys);
  1027. timer.stop();
  1028. cerr << "Time for Categorization: " << timer.getLastAbsolute() << " seconds\n" << endl;
  1029. }
  1030. #ifdef VERBOSE
  1031. cout << "\nFEATURE USAGE" << endl;
  1032. cout << "#############\n" << endl;
  1033. // amount of used features per feature type
  1034. std::map<int, int> featTypeCounter;
  1035. for ( int tree = 0; tree < nbTrees; tree++ )
  1036. {
  1037. int t = ( int ) forest[tree].size();
  1038. for ( int node = 0; node < t; node++ )
  1039. {
  1040. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  1041. {
  1042. featTypeCounter[ forest[tree][node].feat->getFeatType() ] += 1;
  1043. }
  1044. }
  1045. }
  1046. cout << "Types:" << endl;
  1047. for ( map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++ )
  1048. cout << it->first << ": " << it->second << endl;
  1049. cout << "\nOperations - All:" << endl;
  1050. // used operations
  1051. vector<int> opOverview ( NBOPERATIONS, 0 );
  1052. // relative use of context vs raw features per tree level
  1053. vector<vector<double> > contextOverview ( maxDepth, vector<double> ( 2, 0.0 ) );
  1054. for ( int tree = 0; tree < nbTrees; tree++ )
  1055. {
  1056. int t = ( int ) forest[tree].size();
  1057. for ( int node = 0; node < t; node++ )
  1058. {
  1059. #ifdef DEBUG
  1060. printf ( "tree[%i]: left: %i, right: %i", node, forest[tree][node].left, forest[tree][node].right );
  1061. #endif
  1062. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  1063. {
  1064. cout << forest[tree][node].feat->writeInfos() << endl;
  1065. opOverview[ forest[tree][node].feat->getOps() ]++;
  1066. contextOverview[forest[tree][node].depth][ ( int ) forest[tree][node].feat->getContext() ]++;
  1067. }
  1068. #ifdef DEBUG
  1069. for ( int d = 0; d < ( int ) forest[tree][node].dist.size(); d++ )
  1070. {
  1071. cout << " " << forest[tree][node].dist[d];
  1072. }
  1073. cout << endl;
  1074. #endif
  1075. }
  1076. }
  1077. // amount of used features per operation type
  1078. cout << "\nOperations - Summary:" << endl;
  1079. for ( int t = 0; t < ( int ) opOverview.size(); t++ )
  1080. {
  1081. cout << "Ops " << t << ": " << opOverview[ t ] << endl;
  1082. }
  1083. // ratio of used context features per depth level
  1084. cout << "\nContext-Ratio:" << endl;
  1085. for ( int d = 0; d < maxDepth; d++ )
  1086. {
  1087. double sum = contextOverview[d][0] + contextOverview[d][1];
  1088. if ( sum == 0 )
  1089. sum = 1;
  1090. contextOverview[d][0] /= sum;
  1091. contextOverview[d][1] /= sum;
  1092. cout << "Depth [" << d+1 << "] Normal: " << contextOverview[d][0] << " Context: " << contextOverview[d][1] << endl;
  1093. }
  1094. #endif
  1095. }
  1096. void SemSegContextTree3D::addFeatureMaps (
  1097. NICE::MultiChannelImage3DT<double> &imgData,
  1098. const vector<string> &filelist,
  1099. int &amountRegions )
  1100. {
  1101. int xsize = imgData.width();
  1102. int ysize = imgData.height();
  1103. int zsize = imgData.depth();
  1104. amountRegions = 0;
  1105. // RGB to Lab
  1106. if ( imagetype == IMAGETYPE_RGB )
  1107. {
  1108. for ( int z = 0; z < zsize; z++ )
  1109. for ( int y = 0; y < ysize; y++ )
  1110. for ( int x = 0; x < xsize; x++ )
  1111. {
  1112. double R, G, B, X, Y, Z, L, a, b;
  1113. R = ( double )imgData.get( x, y, z, 0 ) / 255.0;
  1114. G = ( double )imgData.get( x, y, z, 1 ) / 255.0;
  1115. B = ( double )imgData.get( x, y, z, 2 ) / 255.0;
  1116. if ( useAltTristimulus )
  1117. {
  1118. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 4 );
  1119. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 4 );
  1120. }
  1121. else
  1122. {
  1123. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
  1124. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 0 );
  1125. }
  1126. imgData.set( x, y, z, L, 0 );
  1127. imgData.set( x, y, z, a, 1 );
  1128. imgData.set( x, y, z, b, 2 );
  1129. }
  1130. }
  1131. // Gradient layers
  1132. if ( useGradient )
  1133. {
  1134. int currentsize = imgData.channels();
  1135. imgData.addChannel ( 2*currentsize );
  1136. for ( int z = 0; z < zsize; z++ )
  1137. for ( int c = 0; c < currentsize; c++ )
  1138. {
  1139. ImageT<double> tmp = imgData.getChannelT(z, c);
  1140. ImageT<double> sobX( xsize, ysize );
  1141. ImageT<double> sobY( xsize, ysize );
  1142. NICE::FilterT<double, double, double>::sobelX ( tmp, sobX );
  1143. NICE::FilterT<double, double, double>::sobelY ( tmp, sobY );
  1144. for ( int y = 0; y < ysize; y++ )
  1145. for ( int x = 0; x < xsize; x++ )
  1146. {
  1147. imgData.set( x, y, z, sobX.getPixelQuick(x,y), c+currentsize );
  1148. imgData.set( x, y, z, sobY.getPixelQuick(x,y), c+(currentsize*2) );
  1149. }
  1150. }
  1151. }
  1152. // Weijer color names
  1153. if ( useWeijer )
  1154. {
  1155. if ( imagetype == IMAGETYPE_RGB )
  1156. {
  1157. int currentsize = imgData.channels();
  1158. imgData.addChannel ( 11 );
  1159. for ( int z = 0; z < zsize; z++ )
  1160. {
  1161. NICE::ColorImage img = imgData.getColor ( z );
  1162. NICE::MultiChannelImageT<double> cfeats;
  1163. lfcw->getFeats ( img, cfeats );
  1164. for ( int c = 0; c < cfeats.channels(); c++)
  1165. for ( int y = 0; y < ysize; y++ )
  1166. for ( int x = 0; x < xsize; x++ )
  1167. imgData.set(x, y, z, cfeats.get(x,y,(uint)c), c+currentsize);
  1168. }
  1169. }
  1170. else
  1171. {
  1172. cerr << "Can't compute weijer features of a grayscale image." << endl;
  1173. }
  1174. }
  1175. // arbitrary additional layer as image
  1176. if ( useAdditionalLayer )
  1177. {
  1178. int currentsize = imgData.channels();
  1179. imgData.addChannel ( 1 );
  1180. for ( int z = 0; z < zsize; z++ )
  1181. {
  1182. vector<string> list;
  1183. StringTools::split ( filelist[z], '/', list );
  1184. string layerPath = StringTools::trim ( filelist[z], list.back() ) + "addlayer/" + list.back();
  1185. NICE::Image layer ( layerPath );
  1186. for ( int y = 0; y < ysize; y++ )
  1187. for ( int x = 0; x < xsize; x++ )
  1188. imgData.set(x, y, z, layer.getPixelQuick(x,y), currentsize);
  1189. }
  1190. }
  1191. // read the geometric cues produced by Hoiem et al.
  1192. if ( useHoiemFeatures )
  1193. {
  1194. string hoiemDirectory = conf->gS ( "Features", "hoiem_directory" );
  1195. // we could also give the following set as a config option
  1196. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  1197. vector<string> hoiemClasses;
  1198. StringTools::split ( hoiemClasses_s, ' ', hoiemClasses );
  1199. int currentsize = imgData.channels();
  1200. imgData.addChannel ( hoiemClasses.size() );
  1201. for ( int z = 0; z < zsize; z++ )
  1202. {
  1203. FileName fn ( filelist[z] );
  1204. fn.removeExtension();
  1205. FileName fnBase = fn.extractFileName();
  1206. for ( vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentsize++ )
  1207. {
  1208. string hoiemClass = *i;
  1209. FileName fnConfidenceImage ( hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png" );
  1210. if ( ! fnConfidenceImage.fileExists() )
  1211. {
  1212. fthrow ( Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << filelist[z] << ")" );
  1213. }
  1214. else
  1215. {
  1216. Image confidenceImage ( fnConfidenceImage.str() );
  1217. if ( confidenceImage.width() != xsize || confidenceImage.height() != ysize )
  1218. {
  1219. fthrow ( Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str() );
  1220. }
  1221. // copy standard image to double image
  1222. for ( int y = 0 ; y < confidenceImage.height(); y++ )
  1223. for ( int x = 0 ; x < confidenceImage.width(); x++ )
  1224. imgData ( x, y, z, currentsize ) = ( double ) confidenceImage ( x, y );
  1225. currentsize++;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. // region feature (unsupervised segmentation)
  1231. int shift = 0;
  1232. if ( useFeat1 )
  1233. {
  1234. shift = 1;
  1235. MultiChannelImageT<int> regions;
  1236. regions.reInit( xsize, ysize, zsize );
  1237. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1238. int currentsize = imgData.channels();
  1239. imgData.addChannel ( 1 );
  1240. for ( int z = 0; z < ( int ) regions.channels(); z++ )
  1241. for ( int y = 0; y < regions.height(); y++ )
  1242. for ( int x = 0; x < regions.width(); x++ )
  1243. imgData.set ( x, y, z, regions ( x, y, ( uint ) z ), currentsize );
  1244. }
  1245. // intergal images of raw channels
  1246. if ( useFeat2 )
  1247. {
  1248. #pragma omp parallel for
  1249. for ( int i = 0; i < rawChannels; i++ )
  1250. imgData.calcIntegral ( i );
  1251. }
  1252. int classes = classNames->numClasses() - forbidden_classes.size();
  1253. if ( useFeat3 || useFeat4 )
  1254. imgData.addChannel ( classes );
  1255. }
  1256. void SemSegContextTree3D::classify (
  1257. const std::vector<std::string> & filelist,
  1258. NICE::MultiChannelImageT<int> & segresult,
  1259. NICE::MultiChannelImage3DT<double> & probabilities )
  1260. {
  1261. ///////////////////////// build MCI3DT from files ///////////////////////////
  1262. /////////////////////////////////////////////////////////////////////////////
  1263. NICE::MultiChannelImage3DT<double> imgData;
  1264. this->make3DImage( filelist, imgData );
  1265. int xsize = imgData.width();
  1266. int ysize = imgData.height();
  1267. int zsize = imgData.depth();
  1268. ////////////////////////// initialize variables /////////////////////////////
  1269. /////////////////////////////////////////////////////////////////////////////
  1270. firstiteration = true;
  1271. depth = 0;
  1272. // anytime classification ability
  1273. int classificationDepth = conf->gI( "SSContextTree", "classification_depth", maxDepth );
  1274. if (classificationDepth > maxDepth || classificationDepth < 1 )
  1275. classificationDepth = maxDepth;
  1276. Timer timer;
  1277. timer.start();
  1278. // classes occurred during training step
  1279. int classes = labelmapback.size();
  1280. // classes defined in config file
  1281. int numClasses = classNames->numClasses();
  1282. // class probabilities by pixel
  1283. probabilities.reInit ( xsize, ysize, zsize, numClasses );
  1284. probabilities.setAll ( 0 );
  1285. // class probabilities by region
  1286. vector<vector<double> > regionProbs;
  1287. // affiliation: pixel <-> (tree,node)
  1288. MultiChannelImage3DT<unsigned short int> nodeIndices ( xsize, ysize, zsize, nbTrees );
  1289. nodeIndices.setAll ( 0 );
  1290. // for categorization
  1291. SparseVector *globalCategorFeat;
  1292. globalCategorFeat = new SparseVector();
  1293. /////////////////////////// get feature values //////////////////////////////
  1294. /////////////////////////////////////////////////////////////////////////////
  1295. // Basic Features
  1296. int amountRegions;
  1297. addFeatureMaps ( imgData, filelist, amountRegions );
  1298. vector<int> rSize;
  1299. int shift = 0;
  1300. if ( useFeat1 )
  1301. {
  1302. shift = 1;
  1303. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1304. rSize = vector<int> ( amountRegions, 0 );
  1305. for ( int z = 0; z < zsize; z++ )
  1306. {
  1307. for ( int y = 0; y < ysize; y++ )
  1308. {
  1309. for ( int x = 0; x < xsize; x++ )
  1310. {
  1311. rSize[imgData ( x, y, z, rawChannels ) ]++;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. ////////////////// traverse image example through trees /////////////////////
  1317. /////////////////////////////////////////////////////////////////////////////
  1318. bool noNewSplit = false;
  1319. for ( int d = 0; d < classificationDepth && !noNewSplit; d++ )
  1320. {
  1321. depth++;
  1322. vector<vector<double> > lastRegionProbs = regionProbs;
  1323. if ( useFeat1 )
  1324. {
  1325. int numRegions = ( int ) regionProbs.size();
  1326. for ( int r = 0; r < numRegions; r++ )
  1327. for ( int c = 0; c < classes; c++ )
  1328. regionProbs[r][c] = 0.0;
  1329. }
  1330. if ( depth < classificationDepth )
  1331. {
  1332. int firstChannel = rawChannels + shift;
  1333. if ( useFeat3 || useFeat4 )
  1334. this->updateProbabilityMaps ( nodeIndices, imgData, firstChannel );
  1335. }
  1336. double weight = computeWeight ( depth, maxDepth )
  1337. - computeWeight ( depth - 1, maxDepth );
  1338. noNewSplit = true;
  1339. int tree;
  1340. #pragma omp parallel for private(tree)
  1341. for ( tree = 0; tree < nbTrees; tree++ )
  1342. for ( int x = 0; x < xsize; x=x+labelIncrement )
  1343. for ( int y = 0; y < ysize; y=y+labelIncrement )
  1344. for ( int z = 0; z < zsize; z++ )
  1345. {
  1346. int node = nodeIndices.get ( x, y, z, tree );
  1347. if ( forest[tree][node].left > 0 )
  1348. {
  1349. noNewSplit = false;
  1350. Features feat;
  1351. feat.feats = &imgData;
  1352. feat.rProbs = &lastRegionProbs;
  1353. double val = forest[tree][node].feat->getVal ( feat, x, y, z );
  1354. if ( !isfinite ( val ) ) val = 0.0;
  1355. // traverse to left child
  1356. if ( val < forest[tree][node].decision )
  1357. {
  1358. int left = forest[tree][node].left;
  1359. for ( int n = 0; n < labelIncrement; n++ )
  1360. for ( int m = 0; m < labelIncrement; m++ )
  1361. if (x+m < xsize && y+n < ysize)
  1362. nodeIndices.set ( x+m, y+n, z, left, tree );
  1363. #pragma omp critical
  1364. {
  1365. if ( fasthik != NULL
  1366. && useCategorization
  1367. && forest[tree][left].nodeNumber < uniquenumber )
  1368. ( *globalCategorFeat ) [forest[tree][left].nodeNumber] += weight;
  1369. }
  1370. }
  1371. // traverse to right child
  1372. else
  1373. {
  1374. int right = forest[tree][node].right;
  1375. for ( int n = 0; n < labelIncrement; n++ )
  1376. for ( int m = 0; m < labelIncrement; m++ )
  1377. if (x+m < xsize && y+n < ysize)
  1378. nodeIndices.set ( x+m, y+n, z, right, tree );
  1379. #pragma omp critical
  1380. {
  1381. if ( fasthik != NULL
  1382. && useCategorization
  1383. && forest[tree][right].nodeNumber < uniquenumber )
  1384. ( *globalCategorFeat ) [forest[tree][right].nodeNumber] += weight;
  1385. }
  1386. }
  1387. }
  1388. }
  1389. if ( useFeat1 )
  1390. {
  1391. int xsize = nodeIndices.width();
  1392. int ysize = nodeIndices.height();
  1393. int zsize = nodeIndices.depth();
  1394. #pragma omp parallel for
  1395. for ( int x = 0; x < xsize; x++ )
  1396. for ( int y = 0; y < ysize; y++ )
  1397. for ( int z = 0; z < zsize; z++ )
  1398. for ( int tree = 0; tree < nbTrees; tree++ )
  1399. {
  1400. int node = nodeIndices.get ( x, y, z, tree );
  1401. for ( uint c = 0; c < forest[tree][node].dist.size(); c++ )
  1402. {
  1403. int r = (int) imgData ( x, y, z, rawChannels );
  1404. regionProbs[r][c] += forest[tree][node].dist[c];
  1405. }
  1406. }
  1407. int numRegions = (int) regionProbs.size();
  1408. for ( int r = 0; r < numRegions; r++ )
  1409. for ( int c = 0; c < (int) classes; c++ )
  1410. regionProbs[r][c] /= ( double ) ( rSize[r] );
  1411. }
  1412. if ( (depth < classificationDepth) && firstiteration ) firstiteration = false;
  1413. }
  1414. vector<int> classesInImg;
  1415. if ( useCategorization )
  1416. {
  1417. if ( cndir != "" )
  1418. {
  1419. for ( int z = 0; z < zsize; z++ )
  1420. {
  1421. vector< string > list;
  1422. StringTools::split ( filelist[z], '/', list );
  1423. string orgname = list.back();
  1424. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1425. while ( !infile.eof() && infile.good() )
  1426. {
  1427. int tmp;
  1428. infile >> tmp;
  1429. assert ( tmp >= 0 && tmp < numClasses );
  1430. classesInImg.push_back ( tmp );
  1431. }
  1432. }
  1433. }
  1434. else
  1435. {
  1436. globalCategorFeat->setDim ( uniquenumber );
  1437. globalCategorFeat->normalize();
  1438. ClassificationResult cr = fasthik->classify( globalCategorFeat);
  1439. for ( uint i = 0; i < ( uint ) classes; i++ )
  1440. {
  1441. cerr << cr.scores[i] << " ";
  1442. if ( cr.scores[i] > 0.0/*-0.3*/ )
  1443. {
  1444. classesInImg.push_back ( i );
  1445. }
  1446. }
  1447. }
  1448. cerr << "amount of classes: " << classes << " used classes: " << classesInImg.size() << endl;
  1449. }
  1450. if ( classesInImg.size() == 0 )
  1451. {
  1452. for ( uint i = 0; i < ( uint ) classes; i++ )
  1453. {
  1454. classesInImg.push_back ( i );
  1455. }
  1456. }
  1457. // final labeling step
  1458. if ( pixelWiseLabeling )
  1459. {
  1460. for ( int x = 0; x < xsize; x++ )
  1461. for ( int y = 0; y < ysize; y++ )
  1462. for ( int z = 0; z < zsize; z++ )
  1463. {
  1464. double maxProb = - numeric_limits<double>::max();
  1465. int maxClass = 0;
  1466. for ( uint c = 0; c < classesInImg.size(); c++ )
  1467. {
  1468. int i = classesInImg[c];
  1469. double curProb = getMeanProb ( x, y, z, i, nodeIndices );
  1470. probabilities.set ( x, y, z, curProb, labelmapback[i] );
  1471. if ( curProb > maxProb )
  1472. {
  1473. maxProb = curProb;
  1474. maxClass = labelmapback[i];
  1475. }
  1476. }
  1477. assert(maxProb <= 1);
  1478. // copy pixel labeling into segresults (output)
  1479. segresult.set ( x, y, maxClass, ( uint ) z );
  1480. }
  1481. #ifdef VISUALIZE
  1482. getProbabilityMap( probabilities );
  1483. #endif
  1484. }
  1485. else
  1486. {
  1487. // labeling by region
  1488. NICE::MultiChannelImageT<int> regions;
  1489. int xsize = imgData.width();
  1490. int ysize = imgData.height();
  1491. int zsize = imgData.depth();
  1492. regions.reInit ( xsize, ysize, zsize );
  1493. if ( useFeat1 )
  1494. {
  1495. for ( int z = 0; z < zsize; z++ )
  1496. for ( int y = 0; y < ysize; y++ )
  1497. for ( int x = 0; x < xsize; x++ )
  1498. regions.set ( x, y, imgData ( x, y, z, rawChannels ), ( uint ) z );
  1499. }
  1500. else
  1501. {
  1502. amountRegions = segmentation->segRegions ( imgData, regions, imagetype );
  1503. #ifdef DEBUG
  1504. for ( unsigned int z = 0; z < ( uint ) zsize; z++ )
  1505. {
  1506. NICE::Matrix regmask;
  1507. NICE::ColorImage colorimg ( xsize, ysize );
  1508. NICE::ColorImage marked ( xsize, ysize );
  1509. regmask.resize ( xsize, ysize );
  1510. for ( int y = 0; y < ysize; y++ )
  1511. {
  1512. for ( int x = 0; x < xsize; x++ )
  1513. {
  1514. regmask ( x,y ) = regions ( x,y,z );
  1515. colorimg.setPixelQuick ( x, y, 0, imgData.get ( x,y,z,0 ) );
  1516. colorimg.setPixelQuick ( x, y, 1, imgData.get ( x,y,z,0 ) );
  1517. colorimg.setPixelQuick ( x, y, 2, imgData.get ( x,y,z,0 ) );
  1518. }
  1519. }
  1520. vector<int> colorvals;
  1521. colorvals.push_back ( 255 );
  1522. colorvals.push_back ( 0 );
  1523. colorvals.push_back ( 0 );
  1524. segmentation->markContours ( colorimg, regmask, colorvals, marked );
  1525. std::vector<string> list;
  1526. StringTools::split ( filelist[z], '/', list );
  1527. string savePath = StringTools::trim ( filelist[z], list.back() ) + "marked/" + list.back();
  1528. marked.write ( savePath );
  1529. }
  1530. #endif
  1531. }
  1532. regionProbs.clear();
  1533. regionProbs = vector<vector<double> > ( amountRegions, vector<double> ( classes, 0.0 ) );
  1534. vector<vector<double> > regionProbsCount ( amountRegions, vector<double> ( classes, 0.0 ) );
  1535. vector<int> bestlabels ( amountRegions, labelmapback[classesInImg[0]] );
  1536. for ( int z = 0; z < zsize; z++ )
  1537. {
  1538. for ( int y = 0; y < ysize; y++ )
  1539. {
  1540. for ( int x = 0; x < xsize; x++ )
  1541. {
  1542. int r = regions ( x, y, ( uint ) z );
  1543. for ( uint i = 0; i < classesInImg.size(); i++ )
  1544. {
  1545. int c = classesInImg[i];
  1546. // get mean voting of all trees
  1547. regionProbs[r][c] += getMeanProb ( x, y, z, c, nodeIndices );
  1548. regionProbsCount[r][c]++;
  1549. }
  1550. }
  1551. }
  1552. }
  1553. for ( int r = 0; r < amountRegions; r++ )
  1554. for ( int c = 0; c < classes; c++ )
  1555. regionProbs[r][c] /= regionProbsCount[r][c];
  1556. for ( int r = 0; r < amountRegions; r++ )
  1557. {
  1558. double maxProb = regionProbs[r][classesInImg[0]];
  1559. bestlabels[r] = classesInImg[0];
  1560. for ( int c = 1; c < classes; c++ )
  1561. if ( maxProb < regionProbs[r][c] )
  1562. {
  1563. maxProb = regionProbs[r][c];
  1564. bestlabels[r] = c;
  1565. }
  1566. bestlabels[r] = labelmapback[bestlabels[r]];
  1567. }
  1568. // copy region labeling into segresults (output)
  1569. for ( int z = 0; z < zsize; z++ )
  1570. for ( int y = 0; y < ysize; y++ )
  1571. for ( int x = 0; x < xsize; x++ )
  1572. {
  1573. int r = regions ( x,y, (uint) z );
  1574. int l = bestlabels[ r ];
  1575. segresult.set ( x, y, l, (uint) z );
  1576. for ( int c = 0; c < classes; c++ )
  1577. {
  1578. double curProb = regionProbs[r][c];
  1579. probabilities.set( x, y, z, curProb, c );
  1580. }
  1581. }
  1582. #ifdef WRITEREGIONS
  1583. for ( int z = 0; z < zsize; z++ )
  1584. {
  1585. RegionGraph rg;
  1586. NICE::ColorImage img ( xsize,ysize );
  1587. if ( imagetype == IMAGETYPE_RGB )
  1588. {
  1589. img = imgData.getColor ( z );
  1590. }
  1591. else
  1592. {
  1593. NICE::Image gray = imgData.getChannel ( z );
  1594. for ( int y = 0; y < ysize; y++ )
  1595. {
  1596. for ( int x = 0; x < xsize; x++ )
  1597. {
  1598. int val = gray.getPixelQuick ( x,y );
  1599. img.setPixelQuick ( x, y, val, val, val );
  1600. }
  1601. }
  1602. }
  1603. Matrix regions_tmp ( xsize,ysize );
  1604. for ( int y = 0; y < ysize; y++ )
  1605. {
  1606. for ( int x = 0; x < xsize; x++ )
  1607. {
  1608. regions_tmp ( x,y ) = regions ( x,y, ( uint ) z );
  1609. }
  1610. }
  1611. segmentation->getGraphRepresentation ( img, regions_tmp, rg );
  1612. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1613. {
  1614. rg[pos]->setProbs ( regionProbs[pos] );
  1615. }
  1616. std::string s;
  1617. std::stringstream out;
  1618. std::vector< std::string > list;
  1619. StringTools::split ( filelist[z], '/', list );
  1620. out << "rgout/" << list.back() << ".graph";
  1621. string writefile = out.str();
  1622. rg.write ( writefile );
  1623. }
  1624. #endif
  1625. }
  1626. timer.stop();
  1627. cout << "\nTime for Classification: " << timer.getLastAbsolute() << endl;
  1628. // CLEANING UP
  1629. // TODO: operations in "forest"
  1630. while( !ops.empty() )
  1631. {
  1632. vector<Operation3D*> &tops = ops.back();
  1633. while ( !tops.empty() )
  1634. tops.pop_back();
  1635. ops.pop_back();
  1636. }
  1637. delete globalCategorFeat;
  1638. }
  1639. void SemSegContextTree3D::store ( std::ostream & os, int format ) const
  1640. {
  1641. os.precision ( numeric_limits<double>::digits10 + 1 );
  1642. os << nbTrees << endl;
  1643. classnames.store ( os );
  1644. map<int, int>::const_iterator it;
  1645. os << labelmap.size() << endl;
  1646. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1647. os << ( *it ).first << " " << ( *it ).second << endl;
  1648. os << labelmapback.size() << endl;
  1649. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1650. os << ( *it ).first << " " << ( *it ).second << endl;
  1651. int trees = forest.size();
  1652. os << trees << endl;
  1653. for ( int t = 0; t < trees; t++ )
  1654. {
  1655. int nodes = forest[t].size();
  1656. os << nodes << endl;
  1657. for ( int n = 0; n < nodes; n++ )
  1658. {
  1659. 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;
  1660. os << forest[t][n].dist << endl;
  1661. if ( forest[t][n].feat == NULL )
  1662. os << -1 << endl;
  1663. else
  1664. {
  1665. os << forest[t][n].feat->getOps() << endl;
  1666. forest[t][n].feat->store ( os );
  1667. }
  1668. }
  1669. }
  1670. vector<int> channelType;
  1671. if ( useFeat0 )
  1672. channelType.push_back(0);
  1673. if ( useFeat1 )
  1674. channelType.push_back(1);
  1675. if ( useFeat2 )
  1676. channelType.push_back(2);
  1677. if ( useFeat3 )
  1678. channelType.push_back(3);
  1679. if ( useFeat4 )
  1680. channelType.push_back(4);
  1681. os << channelType.size() << endl;
  1682. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  1683. {
  1684. os << channelType[i] << " ";
  1685. }
  1686. os << endl;
  1687. os << rawChannels << endl;
  1688. os << uniquenumber << endl;
  1689. }
  1690. void SemSegContextTree3D::restore ( std::istream & is, int format )
  1691. {
  1692. is >> nbTrees;
  1693. classnames.restore ( is );
  1694. int lsize;
  1695. is >> lsize;
  1696. labelmap.clear();
  1697. for ( int l = 0; l < lsize; l++ )
  1698. {
  1699. int first, second;
  1700. is >> first;
  1701. is >> second;
  1702. labelmap[first] = second;
  1703. }
  1704. is >> lsize;
  1705. labelmapback.clear();
  1706. for ( int l = 0; l < lsize; l++ )
  1707. {
  1708. int first, second;
  1709. is >> first;
  1710. is >> second;
  1711. labelmapback[first] = second;
  1712. }
  1713. int trees;
  1714. is >> trees;
  1715. forest.clear();
  1716. for ( int t = 0; t < trees; t++ )
  1717. {
  1718. vector<TreeNode> tmptree;
  1719. forest.push_back ( tmptree );
  1720. int nodes;
  1721. is >> nodes;
  1722. for ( int n = 0; n < nodes; n++ )
  1723. {
  1724. TreeNode tmpnode;
  1725. forest[t].push_back ( tmpnode );
  1726. is >> forest[t][n].left;
  1727. is >> forest[t][n].right;
  1728. is >> forest[t][n].decision;
  1729. is >> forest[t][n].isleaf;
  1730. is >> forest[t][n].depth;
  1731. is >> forest[t][n].featcounter;
  1732. is >> forest[t][n].nodeNumber;
  1733. is >> forest[t][n].dist;
  1734. int feattype;
  1735. is >> feattype;
  1736. assert ( feattype < NBOPERATIONS );
  1737. forest[t][n].feat = NULL;
  1738. if ( feattype >= 0 )
  1739. {
  1740. for ( uint o = 0; o < ops.size(); o++ )
  1741. {
  1742. for ( uint o2 = 0; o2 < ops[o].size(); o2++ )
  1743. {
  1744. if ( forest[t][n].feat == NULL )
  1745. {
  1746. if ( ops[o][o2]->getOps() == feattype )
  1747. {
  1748. forest[t][n].feat = ops[o][o2]->clone();
  1749. break;
  1750. }
  1751. }
  1752. }
  1753. }
  1754. assert ( forest[t][n].feat != NULL );
  1755. forest[t][n].feat->restore ( is );
  1756. }
  1757. }
  1758. }
  1759. // channel type configuration
  1760. int ctsize;
  1761. is >> ctsize;
  1762. for ( int i = 0; i < ctsize; i++ )
  1763. {
  1764. int tmp;
  1765. is >> tmp;
  1766. switch (tmp)
  1767. {
  1768. case 0: useFeat0 = true; break;
  1769. case 1: useFeat1 = true; break;
  1770. case 2: useFeat2 = true; break;
  1771. case 3: useFeat3 = true; break;
  1772. case 4: useFeat4 = true; break;
  1773. }
  1774. }
  1775. is >> rawChannels;
  1776. is >> uniquenumber;
  1777. }