SemSegContextTree.cpp 63 KB

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