SemSegContextTree.cpp 66 KB

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