SemSegContextTree3D.cpp 66 KB

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