SemSegContextTree3D.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  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->featsPerSplit = 200;
  40. this->useShannonEntropy = true;
  41. this->nbTrees = 10;
  42. this->randomTests = 10;
  43. this->useAltTristimulus = false;
  44. this->useGradient = true;
  45. this->useWeijer = false;
  46. this->useAdditionalLayer = false;
  47. this->useHoiemFeatures = false;
  48. this->useCategorization = false;
  49. this->cndir = "";
  50. this->fasthik = NULL;
  51. this->saveLoadData = false;
  52. this->fileLocation = "tmp.txt";
  53. this->pixelWiseLabeling = true;
  54. this->segmentation = NULL;
  55. this->useFeat0 = true;
  56. this->useFeat1 = false;
  57. this->useFeat2 = true;
  58. this->useFeat3 = true;
  59. this->useFeat4 = false;
  60. this->labelIncrement = 1;
  61. if (coarseMode)
  62. this->labelIncrement = 6;
  63. srand(time(NULL));
  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->featsPerSplit = conf->gI ( section, "feats_per_split", 200 );
  81. this->useShannonEntropy = conf->gB ( section, "use_shannon_entropy", true );
  82. this->nbTrees = conf->gI ( section, "amount_trees", 10 );
  83. this->randomTests = conf->gI ( section, "random_tests", 10 );
  84. this->useAltTristimulus = conf->gB ( featsec, "use_alt_trist", false );
  85. this->useGradient = conf->gB ( featsec, "use_gradient", true );
  86. this->useWeijer = conf->gB ( featsec, "use_weijer", true );
  87. this->useAdditionalLayer = conf->gB ( featsec, "use_additional_layer", false );
  88. this->useHoiemFeatures = conf->gB ( featsec, "use_hoiem_features", false );
  89. this->useCategorization = conf->gB ( section, "use_categorization", false );
  90. this->cndir = conf->gS ( "SSContextTree", "cndir", "" );
  91. this->saveLoadData = conf->gB ( "debug", "save_load_data", false );
  92. this->fileLocation = conf->gS ( "debug", "datafile", "tmp.txt" );
  93. this->pixelWiseLabeling = conf->gB ( section, "pixelWiseLabeling", false );
  94. if (coarseMode)
  95. this->labelIncrement = conf->gI ( section, "label_increment", 6 );
  96. else
  97. this->labelIncrement = 1;
  98. if ( useCategorization && cndir == "" )
  99. this->fasthik = new FPCGPHIK ( conf );
  100. else
  101. this->fasthik = NULL;
  102. if ( useWeijer )
  103. this->lfcw = new LocalFeatureColorWeijer ( conf );
  104. this->classnames = (*classNames);
  105. string forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  106. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  107. // feature types
  108. this->useFeat0 = conf->gB ( section, "use_feat_0", true); // pixel pair features
  109. this->useFeat1 = conf->gB ( section, "use_feat_1", false); // region feature
  110. this->useFeat2 = conf->gB ( section, "use_feat_2", true); // integral features
  111. this->useFeat3 = conf->gB ( section, "use_feat_3", true); // integral contex features
  112. this->useFeat4 = conf->gB ( section, "use_feat_4", false); // pixel pair context features
  113. string segmentationtype = conf->gS ( section, "segmentation_type", "none" );
  114. if ( segmentationtype == "meanshift" )
  115. this->segmentation = new RSMeanShift ( conf );
  116. else if ( segmentationtype == "felzenszwalb" )
  117. this->segmentation = new RSGraphBased ( conf );
  118. else if ( segmentationtype == "slic" )
  119. this->segmentation = new RSSlic ( conf );
  120. else if ( segmentationtype == "none" )
  121. {
  122. this->segmentation = NULL;
  123. this->pixelWiseLabeling = true;
  124. this->useFeat1 = false;
  125. }
  126. else
  127. throw ( "no valid segmenation_type\n please choose between none, meanshift, slic and felzenszwalb\n" );
  128. if ( useFeat0 )
  129. this->featTypes.push_back(0);
  130. if ( useFeat1 )
  131. this->featTypes.push_back(1);
  132. if ( useFeat2 )
  133. this->featTypes.push_back(2);
  134. if ( useFeat3 )
  135. this->featTypes.push_back(3);
  136. if ( useFeat4 )
  137. this->featTypes.push_back(4);
  138. srand(time(NULL));
  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 = featTypes[ (int)(rand() % featTypes.size()) ];
  365. }
  366. while ( channelsPerType[ft].size() == 0 );
  367. /* random window positions */
  368. x1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  369. x2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  370. y1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  371. y2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  372. z1 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  373. z2 = ( int ) ( rand() % windowSize ) - windowSize / 2 ;
  374. /* random feature maps (channels) */
  375. int f1, f2;
  376. f1 = ( int ) ( rand() % channelsPerType[ft].size() );
  377. if ( (rand() % 2) == 0 )
  378. f2 = ( int ) ( rand() % channelsPerType[ft].size() );
  379. else
  380. f2 = f1;
  381. f1 = channelsPerType[ft][f1];
  382. f2 = channelsPerType[ft][f2];
  383. if ( ft == 1 )
  384. {
  385. int classes = ( int ) regionProbs[0][0].size();
  386. f2 = ( int ) ( rand() % classes );
  387. }
  388. /* random extraction method (operation) */
  389. int o = ( int ) ( rand() % ops[ft].size() );
  390. Operation3D *op = ops[ft][o]->clone();
  391. if ( ft == 3 || ft == 4 )
  392. op->setContext ( true );
  393. else
  394. op->setContext ( false );
  395. op->set ( x1, y1, z1, x2, y2, z2, f1, f2, ft );
  396. op->setWSize( windowSize );
  397. featsel.push_back ( op );
  398. }
  399. // do actual split tests
  400. for ( int f = 0; f < featsPerSplit; f++ )
  401. {
  402. double l_bestig = -numeric_limits< double >::max();
  403. double l_splitval = -1.0;
  404. vector<double> vals;
  405. double maxval = -numeric_limits<double>::max();
  406. double minval = numeric_limits<double>::max();
  407. int counter = 0;
  408. for ( vector<quadruplet<int,int,int,int> >::const_iterator it = selFeats.begin();
  409. it != selFeats.end(); it++ )
  410. {
  411. Features feat;
  412. feat.feats = &feats[ ( *it ).first ];
  413. feat.rProbs = &regionProbs[ ( *it ).first ];
  414. assert ( forest.size() > ( uint ) tree );
  415. assert ( forest[tree][0].dist.size() > 0 );
  416. double val = 0.0;
  417. val = featsel[f]->getVal ( feat, ( *it ).second, ( *it ).third, ( *it ).fourth );
  418. if ( !isfinite ( val ) )
  419. {
  420. #ifdef DEBUG
  421. cerr << "feat " << feat.feats->width() << " " << feat.feats->height() << " " << feat.feats->depth() << endl;
  422. cerr << "non finite value " << val << " for " << featsel[f]->writeInfos() << endl << (*it).second << " " << (*it).third << " " << (*it).fourth << endl;
  423. #endif
  424. val = 0.0;
  425. }
  426. vals.push_back ( val );
  427. maxval = std::max ( val, maxval );
  428. minval = std::min ( val, minval );
  429. }
  430. if ( minval == maxval )
  431. continue;
  432. // split values
  433. for ( int run = 0 ; run < randomTests; run++ )
  434. {
  435. // choose threshold randomly
  436. double sval = 0.0;
  437. sval = ( (double) rand() / (double) RAND_MAX*(maxval-minval) ) + minval;
  438. map<int, int> eL, eR;
  439. int counterL = 0, counterR = 0;
  440. counter = 0;
  441. for ( vector<quadruplet<int,int,int,int> >::const_iterator it2 = selFeats.begin();
  442. it2 != selFeats.end(); it2++, counter++ )
  443. {
  444. int cn = labels[ ( *it2 ).first ].get ( ( *it2 ).second, ( *it2 ).third, ( *it2 ).fourth );
  445. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  446. if ( vals[counter] < sval )
  447. {
  448. //left entropie:
  449. eL[cn] = eL[cn] + 1;
  450. counterL++;
  451. }
  452. else
  453. {
  454. //right entropie:
  455. eR[cn] = eR[cn] + 1;
  456. counterR++;
  457. }
  458. }
  459. double leftent = 0.0;
  460. for ( map<int, int>::iterator mapit = eL.begin() ; mapit != eL.end(); mapit++ )
  461. {
  462. double p = ( double ) ( *mapit ).second / ( double ) counterL;
  463. leftent -= p * log2 ( p );
  464. }
  465. double rightent = 0.0;
  466. for ( map<int, int>::iterator mapit = eR.begin() ; mapit != eR.end(); mapit++ )
  467. {
  468. double p = ( double ) ( *mapit ).second / ( double ) counterR;
  469. rightent -= p * log2 ( p );
  470. }
  471. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  472. double pl = ( double ) counterL / ( double ) ( counterL + counterR );
  473. //information gain
  474. double ig = globent - ( 1.0 - pl ) * rightent - pl * leftent;
  475. //double ig = globent - rightent - leftent;
  476. if ( useShannonEntropy )
  477. {
  478. double esplit = - ( pl * log ( pl ) + ( 1 - pl ) * log ( 1 - pl ) );
  479. ig = 2 * ig / ( globent + esplit );
  480. }
  481. if ( ig > l_bestig )
  482. {
  483. l_bestig = ig;
  484. l_splitval = sval;
  485. }
  486. }
  487. if ( l_bestig > bestig )
  488. {
  489. bestig = l_bestig;
  490. splitop = featsel[f];
  491. splitval = l_splitval;
  492. }
  493. }
  494. #ifdef DEBUG
  495. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  496. #endif
  497. return bestig;
  498. }
  499. inline double SemSegContextTree3D::getMeanProb (
  500. const int &x,
  501. const int &y,
  502. const int &z,
  503. const int &channel,
  504. const MultiChannelImage3DT<unsigned short int> &nodeIndices )
  505. {
  506. double val = 0.0;
  507. for ( int tree = 0; tree < nbTrees; tree++ )
  508. {
  509. val += forest[tree][nodeIndices.get ( x,y,z,tree ) ].dist[channel];
  510. }
  511. return val / ( double ) nbTrees;
  512. }
  513. void SemSegContextTree3D::updateProbabilityMaps (
  514. const NICE::MultiChannelImage3DT<unsigned short int> &nodeIndices,
  515. NICE::MultiChannelImage3DT<double> &feats,
  516. int firstChannel )
  517. {
  518. int xsize = feats.width();
  519. int ysize = feats.height();
  520. int zsize = feats.depth();
  521. int classes = ( int ) labelmap.size();
  522. // integral images for context channels (probability maps for each class)
  523. #pragma omp parallel for
  524. for ( int c = 0; c < classes; c++ )
  525. {
  526. for ( int z = 0; z < zsize; z++ )
  527. for ( int y = 0; y < ysize; y++ )
  528. for ( int x = 0; x < xsize; x++ )
  529. {
  530. double val = getMeanProb ( x, y, z, c, nodeIndices );
  531. if (useFeat3 || useFeat4)
  532. feats ( x, y, z, firstChannel + c ) = val;
  533. }
  534. feats.calcIntegral ( firstChannel + c );
  535. }
  536. }
  537. inline double computeWeight ( const int &d, const int &dim )
  538. {
  539. if (d == 0)
  540. return 0.0;
  541. else
  542. return 1.0 / ( pow ( 2, ( double ) ( dim - d + 1 ) ) );
  543. }
  544. void SemSegContextTree3D::train ( const MultiDataset *md )
  545. {
  546. const LabeledSet *trainp = ( *md ) ["train"];
  547. if ( saveLoadData )
  548. {
  549. if ( FileMgt::fileExists ( fileLocation ) )
  550. read ( fileLocation );
  551. else
  552. {
  553. train ( trainp );
  554. write ( fileLocation );
  555. }
  556. }
  557. else
  558. {
  559. train ( trainp );
  560. }
  561. }
  562. void SemSegContextTree3D::train ( const LabeledSet * trainp )
  563. {
  564. int shortsize = numeric_limits<short>::max();
  565. Timer timer;
  566. timer.start();
  567. vector<int> zsizeVec;
  568. getDepthVector ( trainp, zsizeVec, run3Dseg );
  569. //FIXME: memory usage
  570. vector<MultiChannelImage3DT<double> > allfeats; // Feature Werte
  571. vector<MultiChannelImage3DT<unsigned short int> > nodeIndices; // Zuordnung Knoten/Baum für jeden Pixel
  572. vector<MultiChannelImageT<int> > labels;
  573. // für externen Klassifikator
  574. vector<SparseVector*> globalCategorFeats;
  575. vector<map<int,int> > classesPerImage;
  576. vector<vector<int> > rSize; // anzahl der pixel je region
  577. vector<int> amountRegionpI; // ANZAHL der regionen pro bild (von unsupervised segmentation)
  578. int imgCounter = 0;
  579. int amountPixels = 0;
  580. // How many channels of non-integral type do we have?
  581. if ( imagetype == IMAGETYPE_RGB )
  582. rawChannels = 3;
  583. else
  584. rawChannels = 1;
  585. if ( useGradient )
  586. {
  587. if ( run3Dseg )
  588. rawChannels *= 4; // gx, gy, gz
  589. else
  590. rawChannels *= 3; // gx, gy
  591. }
  592. if ( useWeijer ) // Weijer Colornames
  593. rawChannels += 11;
  594. if ( useHoiemFeatures ) // geometrische Kontextmerkmale
  595. rawChannels += 8;
  596. if ( useAdditionalLayer ) // beliebige Merkmale in extra Bilddateien
  597. rawChannels += 1;
  598. ///////////////////////////// read input data /////////////////////////////////
  599. ///////////////////////////////////////////////////////////////////////////////
  600. int depthCount = 0;
  601. vector< string > filelist;
  602. NICE::MultiChannelImageT<int> pixelLabels;
  603. std::map<int, bool> labelExist;
  604. for (LabeledSet::const_iterator it = trainp->begin(); it != trainp->end(); it++)
  605. {
  606. for (std::vector<ImageInfo *>::const_iterator jt = it->second.begin();
  607. jt != it->second.end(); jt++)
  608. {
  609. int classno = it->first;
  610. ImageInfo & info = *(*jt);
  611. std::string file = info.img();
  612. filelist.push_back ( file );
  613. depthCount++;
  614. const LocalizationResult *locResult = info.localization();
  615. // getting groundtruth
  616. NICE::ImageT<int> pL;
  617. pL.resize ( locResult->xsize, locResult->ysize );
  618. pL.set ( 0 );
  619. locResult->calcLabeledImage ( pL, ( *classNames ).getBackgroundClass() );
  620. pixelLabels.addChannel ( pL );
  621. if ( locResult->size() <= 0 )
  622. {
  623. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  624. file.c_str() );
  625. continue;
  626. }
  627. fprintf ( stderr, "SSContext: Collecting pixel examples from localization info: %s\n", file.c_str() );
  628. int depthBoundary = 0;
  629. if ( run3Dseg )
  630. {
  631. depthBoundary = zsizeVec[imgCounter];
  632. }
  633. if ( depthCount < depthBoundary ) continue;
  634. // all image slices collected -> make a 3d image
  635. NICE::MultiChannelImage3DT<double> imgData;
  636. make3DImage ( filelist, imgData );
  637. int xsize = imgData.width();
  638. int ysize = imgData.height();
  639. int zsize = imgData.depth();
  640. amountPixels += xsize * ysize * zsize;
  641. MultiChannelImageT<int> tmpMat ( xsize, ysize, ( uint ) zsize );
  642. labels.push_back ( tmpMat );
  643. nodeIndices.push_back ( MultiChannelImage3DT<unsigned short int> ( xsize, ysize, zsize, nbTrees ) );
  644. nodeIndices[imgCounter].setAll ( 0 );
  645. int amountRegions;
  646. // convert color to L*a*b, add selected feature channels
  647. addFeatureMaps ( imgData, filelist, amountRegions );
  648. allfeats.push_back(imgData);
  649. if ( useFeat1 )
  650. {
  651. amountRegionpI.push_back ( amountRegions );
  652. rSize.push_back ( vector<int> ( amountRegions, 0 ) );
  653. }
  654. if ( useCategorization )
  655. {
  656. globalCategorFeats.push_back ( new SparseVector() );
  657. classesPerImage.push_back ( map<int,int>() );
  658. }
  659. for ( int x = 0; x < xsize; x++ )
  660. for ( int y = 0; y < ysize; y++ )
  661. for ( int z = 0; z < zsize; z++ )
  662. {
  663. if ( useFeat1 )
  664. rSize[imgCounter][allfeats[imgCounter] ( x, y, z, rawChannels ) ]++;
  665. if ( run3Dseg )
  666. classno = pixelLabels ( x, y, ( uint ) z );
  667. else
  668. classno = pL.getPixelQuick ( x,y );
  669. labels[imgCounter].set ( x, y, classno, ( uint ) z );
  670. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  671. continue;
  672. labelExist[classno] = true;
  673. if ( useCategorization )
  674. classesPerImage[imgCounter][classno] = 1;
  675. }
  676. filelist.clear();
  677. pixelLabels.reInit ( 0,0,0 );
  678. depthCount = 0;
  679. imgCounter++;
  680. }
  681. }
  682. int classes = 0;
  683. for ( map<int, bool>::const_iterator mapit = labelExist.begin();
  684. mapit != labelExist.end(); mapit++ )
  685. {
  686. labelmap[mapit->first] = classes;
  687. labelmapback[classes] = mapit->first;
  688. classes++;
  689. }
  690. ////////////////////////// channel type configuration /////////////////////////
  691. ///////////////////////////////////////////////////////////////////////////////
  692. unsigned char shift = 0;
  693. std::vector<int> rawChannelsIdx, numClassesIdx;
  694. int idx = 0;
  695. for ( int i = 0; i < rawChannels; i++, idx++ )
  696. rawChannelsIdx.push_back ( idx );
  697. for ( int i = 0; i < classes; i++, idx++ )
  698. numClassesIdx.push_back ( idx );
  699. /** Type 0: single pixel & pixel-comparison features on gray value channels */
  700. // actual values derived from integral values
  701. channelsPerType.push_back ( rawChannelsIdx );
  702. /** Type 1: region channel with unsupervised segmentation */
  703. if ( useFeat1 )
  704. {
  705. channelsPerType.push_back ( vector<int>(1, rawChannels) );
  706. shift = 1;
  707. }
  708. else
  709. channelsPerType.push_back ( vector<int>() );
  710. /** Type 2: rectangular and Haar-like features on gray value integral channels */
  711. if ( useFeat2 )
  712. channelsPerType.push_back ( rawChannelsIdx );
  713. else
  714. channelsPerType.push_back ( vector<int>() );
  715. /** Type 3: type 2 features on integral probability channels (context) */
  716. if ( useFeat3 )
  717. channelsPerType.push_back ( numClassesIdx );
  718. else
  719. channelsPerType.push_back ( vector<int>() );
  720. /** Type 4: type 0 features on probability channels (context) */
  721. // Type 4 channels are now INTEGRAL
  722. // This remains for compatibility reasons.
  723. if ( useFeat4 )
  724. channelsPerType.push_back ( numClassesIdx );
  725. else
  726. channelsPerType.push_back ( vector<int>() );
  727. ///////////////////////////////////////////////////////////////////////////////
  728. ///////////////////////////////////////////////////////////////////////////////
  729. vector<vector<vector<double> > > regionProbs;
  730. if ( useFeat1 )
  731. {
  732. for ( int i = 0; i < imgCounter; i++ )
  733. {
  734. regionProbs.push_back ( vector<vector<double> > ( amountRegionpI[i], vector<double> ( classes, 0.0 ) ) );
  735. }
  736. }
  737. //balancing
  738. a = vector<double> ( classes, 0.0 );
  739. int selectionCounter = 0;
  740. for ( int iCounter = 0; iCounter < imgCounter; iCounter++ )
  741. {
  742. int xsize = ( int ) nodeIndices[iCounter].width();
  743. int ysize = ( int ) nodeIndices[iCounter].height();
  744. int zsize = ( int ) nodeIndices[iCounter].depth();
  745. for ( int x = 0; x < xsize; x++ )
  746. for ( int y = 0; y < ysize; y++ )
  747. for ( int z = 0; z < zsize; z++ )
  748. {
  749. int cn = labels[iCounter] ( x, y, ( uint ) z );
  750. if ( labelmap.find ( cn ) == labelmap.end() )
  751. continue;
  752. a[labelmap[cn]] ++;
  753. selectionCounter++;
  754. }
  755. }
  756. for ( int i = 0; i < ( int ) a.size(); i++ )
  757. a[i] /= ( double ) selectionCounter;
  758. #ifdef VERBOSE
  759. cout << "\nDistribution:" << endl;
  760. for ( int i = 0; i < ( int ) a.size(); i++ )
  761. cout << "class '" << classNames->code(labelmapback[i]) << "': "
  762. << a[i] << endl;
  763. #endif
  764. depth = 0;
  765. uniquenumber = 0;
  766. //initialize random forest
  767. for ( int t = 0; t < nbTrees; t++ )
  768. {
  769. vector<TreeNode> singletree;
  770. singletree.push_back ( TreeNode() );
  771. singletree[0].dist = vector<double> ( classes, 0.0 );
  772. singletree[0].depth = depth;
  773. singletree[0].featcounter = amountPixels;
  774. singletree[0].nodeNumber = uniquenumber;
  775. uniquenumber++;
  776. forest.push_back ( singletree );
  777. }
  778. vector<int> startnode ( nbTrees, 0 );
  779. bool noNewSplit = false;
  780. timer.stop();
  781. cout << "\nTime for Pre-Processing: " << timer.getLastAbsolute() << " seconds\n" << endl;
  782. //////////////////////////// train the classifier ///////////////////////////
  783. /////////////////////////////////////////////////////////////////////////////
  784. timer.start();
  785. while ( !noNewSplit && (depth < maxDepth) )
  786. {
  787. depth++;
  788. #ifdef DEBUG
  789. cout << "depth: " << depth << endl;
  790. #endif
  791. noNewSplit = true;
  792. vector<MultiChannelImage3DT<unsigned short int> > lastNodeIndices = nodeIndices;
  793. vector<vector<vector<double> > > lastRegionProbs = regionProbs;
  794. if ( useFeat1 )
  795. for ( int i = 0; i < imgCounter; i++ )
  796. {
  797. int numRegions = (int) regionProbs[i].size();
  798. for ( int r = 0; r < numRegions; r++ )
  799. for ( int c = 0; c < classes; c++ )
  800. regionProbs[i][r][c] = 0.0;
  801. }
  802. // initialize & update context channels
  803. for ( int i = 0; i < imgCounter; i++)
  804. if ( useFeat3 || useFeat4 )
  805. this->updateProbabilityMaps ( nodeIndices[i], allfeats[i], rawChannels + shift );
  806. #ifdef VERBOSE
  807. Timer timerDepth;
  808. timerDepth.start();
  809. #endif
  810. double weight = computeWeight ( depth, maxDepth )
  811. - computeWeight ( depth - 1, maxDepth );
  812. #pragma omp parallel for
  813. // for each tree
  814. for ( int tree = 0; tree < nbTrees; tree++ )
  815. {
  816. const int t = ( int ) forest[tree].size();
  817. const int s = startnode[tree];
  818. startnode[tree] = t;
  819. double bestig;
  820. // for each node
  821. for ( int node = s; node < t; node++ )
  822. {
  823. if ( !forest[tree][node].isleaf && forest[tree][node].left < 0 )
  824. {
  825. // find best split
  826. Operation3D *splitfeat = NULL;
  827. double splitval;
  828. bestig = getBestSplit ( allfeats, lastNodeIndices, labels, node,
  829. splitfeat, splitval, tree, lastRegionProbs );
  830. forest[tree][node].feat = splitfeat;
  831. forest[tree][node].decision = splitval;
  832. // split the node
  833. if ( splitfeat != NULL )
  834. {
  835. noNewSplit = false;
  836. int left;
  837. #pragma omp critical
  838. {
  839. left = forest[tree].size();
  840. forest[tree].push_back ( TreeNode() );
  841. forest[tree].push_back ( TreeNode() );
  842. }
  843. int right = left + 1;
  844. forest[tree][node].left = left;
  845. forest[tree][node].right = right;
  846. forest[tree][left].init( depth, classes, uniquenumber);
  847. int leftu = uniquenumber;
  848. uniquenumber++;
  849. forest[tree][right].init( depth, classes, uniquenumber);
  850. int rightu = uniquenumber;
  851. uniquenumber++;
  852. #pragma omp parallel for
  853. for ( int i = 0; i < imgCounter; i++ )
  854. {
  855. int xsize = nodeIndices[i].width();
  856. int ysize = nodeIndices[i].height();
  857. int zsize = nodeIndices[i].depth();
  858. for ( int x = 0; x < xsize; x++ )
  859. {
  860. for ( int y = 0; y < ysize; y++ )
  861. {
  862. for ( int z = 0; z < zsize; z++ )
  863. {
  864. if ( nodeIndices[i].get ( x, y, z, tree ) == node )
  865. {
  866. // get feature value
  867. Features feat;
  868. feat.feats = &allfeats[i];
  869. feat.rProbs = &lastRegionProbs[i];
  870. double val = 0.0;
  871. val = splitfeat->getVal ( feat, x, y, z );
  872. if ( !isfinite ( val ) ) val = 0.0;
  873. #pragma omp critical
  874. {
  875. int curLabel = labels[i] ( x, y, ( uint ) z );
  876. // traverse to left child
  877. if ( val < splitval )
  878. {
  879. nodeIndices[i].set ( x, y, z, left, tree );
  880. if ( labelmap.find ( curLabel ) != labelmap.end() )
  881. forest[tree][left].dist[labelmap[curLabel]]++;
  882. forest[tree][left].featcounter++;
  883. if ( useCategorization && leftu < shortsize )
  884. ( *globalCategorFeats[i] ) [leftu]+=weight;
  885. }
  886. // traverse to right child
  887. else
  888. {
  889. nodeIndices[i].set ( x, y, z, right, tree );
  890. if ( labelmap.find ( curLabel ) != labelmap.end() )
  891. forest[tree][right].dist[labelmap[curLabel]]++;
  892. forest[tree][right].featcounter++;
  893. if ( useCategorization && rightu < shortsize )
  894. ( *globalCategorFeats[i] ) [rightu]+=weight;
  895. }
  896. }
  897. }
  898. }
  899. }
  900. }
  901. }
  902. // normalize distributions in child leaves
  903. double lcounter = 0.0, rcounter = 0.0;
  904. for ( int c = 0; c < (int)forest[tree][left].dist.size(); c++ )
  905. {
  906. if ( forbidden_classes.find ( labelmapback[c] ) != forbidden_classes.end() )
  907. {
  908. forest[tree][left].dist[c] = 0;
  909. forest[tree][right].dist[c] = 0;
  910. }
  911. else
  912. {
  913. forest[tree][left].dist[c] /= a[c];
  914. lcounter += forest[tree][left].dist[c];
  915. forest[tree][right].dist[c] /= a[c];
  916. rcounter += forest[tree][right].dist[c];
  917. }
  918. }
  919. assert ( lcounter > 0 && rcounter > 0 );
  920. for ( int c = 0; c < classes; c++ )
  921. {
  922. forest[tree][left].dist[c] /= lcounter;
  923. forest[tree][right].dist[c] /= rcounter;
  924. }
  925. }
  926. else
  927. {
  928. forest[tree][node].isleaf = true;
  929. }
  930. }
  931. }
  932. }
  933. if ( useFeat1 )
  934. {
  935. for ( int i = 0; i < imgCounter; i++ )
  936. {
  937. int xsize = nodeIndices[i].width();
  938. int ysize = nodeIndices[i].height();
  939. int zsize = nodeIndices[i].depth();
  940. #pragma omp parallel for
  941. // set region probability distribution
  942. for ( int x = 0; x < xsize; x++ )
  943. {
  944. for ( int y = 0; y < ysize; y++ )
  945. {
  946. for ( int z = 0; z < zsize; z++ )
  947. {
  948. for ( int tree = 0; tree < nbTrees; tree++ )
  949. {
  950. int node = nodeIndices[i].get ( x, y, z, tree );
  951. for ( int c = 0; c < classes; c++ )
  952. {
  953. int r = (int) ( allfeats[i] ( x, y, z, rawChannels ) );
  954. regionProbs[i][r][c] += forest[tree][node].dist[c];
  955. }
  956. }
  957. }
  958. }
  959. }
  960. // normalize distribution
  961. int numRegions = (int) regionProbs[i].size();
  962. for ( int r = 0; r < numRegions; r++ )
  963. {
  964. for ( int c = 0; c < classes; c++ )
  965. {
  966. regionProbs[i][r][c] /= ( double ) ( rSize[i][r] );
  967. }
  968. }
  969. }
  970. }
  971. if ( firstiteration ) firstiteration = false;
  972. #ifdef VERBOSE
  973. timerDepth.stop();
  974. cout << "Depth " << depth << ": " << timerDepth.getLastAbsolute() << " seconds" <<endl;
  975. #endif
  976. lastNodeIndices.clear();
  977. lastRegionProbs.clear();
  978. }
  979. timer.stop();
  980. cout << "Time for Learning: " << timer.getLastAbsolute() << " seconds\n" << endl;
  981. //////////////////////// classification using HIK ///////////////////////////
  982. /////////////////////////////////////////////////////////////////////////////
  983. if ( useCategorization && fasthik != NULL )
  984. {
  985. timer.start();
  986. uniquenumber = std::min ( shortsize, uniquenumber );
  987. for ( uint i = 0; i < globalCategorFeats.size(); i++ )
  988. {
  989. globalCategorFeats[i]->setDim ( uniquenumber );
  990. globalCategorFeats[i]->normalize();
  991. }
  992. std::map< uint, NICE::Vector > ys;
  993. uint cCounter = 0;
  994. for ( std::map<int,int>::const_iterator it = labelmap.begin();
  995. it != labelmap.end(); it++, cCounter++ )
  996. {
  997. ys[cCounter] = NICE::Vector ( globalCategorFeats.size() );
  998. for ( int i = 0; i < imgCounter; i++ )
  999. {
  1000. if ( classesPerImage[i].find ( it->first ) != classesPerImage[i].end() )
  1001. {
  1002. ys[cCounter][i] = 1;
  1003. }
  1004. else
  1005. {
  1006. ys[cCounter][i] = -1;
  1007. }
  1008. }
  1009. }
  1010. fasthik->train( reinterpret_cast<vector<const NICE::SparseVector *>&>(globalCategorFeats), ys);
  1011. timer.stop();
  1012. cerr << "Time for Categorization: " << timer.getLastAbsolute() << " seconds\n" << endl;
  1013. }
  1014. #ifdef VERBOSE
  1015. cout << "\nFEATURE USAGE" << endl;
  1016. cout << "#############\n" << endl;
  1017. // amount of used features per feature type
  1018. std::map<int, int> featTypeCounter;
  1019. for ( int tree = 0; tree < nbTrees; tree++ )
  1020. {
  1021. int t = ( int ) forest[tree].size();
  1022. for ( int node = 0; node < t; node++ )
  1023. {
  1024. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  1025. {
  1026. featTypeCounter[ forest[tree][node].feat->getFeatType() ] += 1;
  1027. }
  1028. }
  1029. }
  1030. cout << "Types:" << endl;
  1031. for ( map<int, int>::const_iterator it = featTypeCounter.begin(); it != featTypeCounter.end(); it++ )
  1032. cout << it->first << ": " << it->second << endl;
  1033. cout << "\nOperations - All:" << endl;
  1034. // used operations
  1035. vector<int> opOverview ( NBOPERATIONS, 0 );
  1036. // relative use of context vs raw features per tree level
  1037. vector<vector<double> > contextOverview ( maxDepth, vector<double> ( 2, 0.0 ) );
  1038. for ( int tree = 0; tree < nbTrees; tree++ )
  1039. {
  1040. int t = ( int ) forest[tree].size();
  1041. for ( int node = 0; node < t; node++ )
  1042. {
  1043. #ifdef DEBUG
  1044. printf ( "tree[%i]: left: %i, right: %i", node, forest[tree][node].left, forest[tree][node].right );
  1045. #endif
  1046. if ( !forest[tree][node].isleaf && forest[tree][node].left != -1 )
  1047. {
  1048. #ifdef DEBUG
  1049. cout << forest[tree][node].feat->writeInfos() << endl;
  1050. #endif
  1051. opOverview[ forest[tree][node].feat->getOps() ]++;
  1052. contextOverview[forest[tree][node].depth][ ( int ) forest[tree][node].feat->getContext() ]++;
  1053. }
  1054. #ifdef DEBUG
  1055. for ( int d = 0; d < ( int ) forest[tree][node].dist.size(); d++ )
  1056. cout << " " << forest[tree][node].dist[d];
  1057. cout << endl;
  1058. #endif
  1059. }
  1060. }
  1061. // amount of used features per operation type
  1062. cout << "\nOperations - Summary:" << endl;
  1063. for ( int t = 0; t < ( int ) opOverview.size(); t++ )
  1064. {
  1065. cout << "Ops " << t << ": " << opOverview[ t ] << endl;
  1066. }
  1067. // ratio of used context features per depth level
  1068. cout << "\nContext-Ratio:" << endl;
  1069. for ( int d = 0; d < maxDepth; d++ )
  1070. {
  1071. double sum = contextOverview[d][0] + contextOverview[d][1];
  1072. if ( sum == 0 )
  1073. sum = 1;
  1074. contextOverview[d][0] /= sum;
  1075. contextOverview[d][1] /= sum;
  1076. cout << "Depth [" << d+1 << "] Normal: " << contextOverview[d][0] << " Context: " << contextOverview[d][1] << endl;
  1077. }
  1078. #endif
  1079. }
  1080. void SemSegContextTree3D::addFeatureMaps (
  1081. NICE::MultiChannelImage3DT<double> &imgData,
  1082. const vector<string> &filelist,
  1083. int &amountRegions )
  1084. {
  1085. int xsize = imgData.width();
  1086. int ysize = imgData.height();
  1087. int zsize = imgData.depth();
  1088. amountRegions = 0;
  1089. // RGB to Lab
  1090. if ( imagetype == IMAGETYPE_RGB )
  1091. {
  1092. for ( int z = 0; z < zsize; z++ )
  1093. for ( int y = 0; y < ysize; y++ )
  1094. for ( int x = 0; x < xsize; x++ )
  1095. {
  1096. double R, G, B, X, Y, Z, L, a, b;
  1097. R = ( double )imgData.get( x, y, z, 0 ) / 255.0;
  1098. G = ( double )imgData.get( x, y, z, 1 ) / 255.0;
  1099. B = ( double )imgData.get( x, y, z, 2 ) / 255.0;
  1100. if ( useAltTristimulus )
  1101. {
  1102. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 4 );
  1103. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 4 );
  1104. }
  1105. else
  1106. {
  1107. ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
  1108. ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 0 );
  1109. }
  1110. imgData.set( x, y, z, L, 0 );
  1111. imgData.set( x, y, z, a, 1 );
  1112. imgData.set( x, y, z, b, 2 );
  1113. }
  1114. }
  1115. // Gradient layers
  1116. if ( useGradient )
  1117. {
  1118. int currentsize = imgData.channels();
  1119. imgData.addChannel ( 2*currentsize );
  1120. // gradients for X and Y
  1121. for ( int z = 0; z < zsize; z++ )
  1122. for ( int c = 0; c < currentsize; c++ )
  1123. {
  1124. ImageT<double> tmp = imgData.getChannelT(z, c);
  1125. ImageT<double> sobX( xsize, ysize );
  1126. ImageT<double> sobY( xsize, ysize );
  1127. NICE::FilterT<double, double, double>::sobelX ( tmp, sobX );
  1128. NICE::FilterT<double, double, double>::sobelY ( tmp, sobY );
  1129. for ( int y = 0; y < ysize; y++ )
  1130. for ( int x = 0; x < xsize; x++ )
  1131. {
  1132. imgData.set( x, y, z, sobX.getPixelQuick(x,y), c+currentsize );
  1133. imgData.set( x, y, z, sobY.getPixelQuick(x,y), c+(currentsize*2) );
  1134. }
  1135. }
  1136. // gradients for Z
  1137. if ( run3Dseg )
  1138. {
  1139. imgData.addChannel ( currentsize );
  1140. for ( int x = 0; x < xsize; x++ )
  1141. for ( int c = 0; c < currentsize; c++ )
  1142. {
  1143. ImageT<double> tmp = imgData.getXSlice(x, c);
  1144. ImageT<double> sobZ( zsize, ysize );
  1145. NICE::FilterT<double, double, double>::sobelX ( tmp, sobZ );
  1146. for ( int y = 0; y < ysize; y++ )
  1147. for ( int z = 0; z < zsize; z++ )
  1148. imgData.set( x, y, z, sobZ.getPixelQuick(z,y), c+(currentsize*3) );
  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. }