SemSegContextTree3D.cpp 71 KB

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