SemSegContextTree.cpp 63 KB

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