SemSegContextTree3D.cpp 65 KB

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