SemSegContextTree.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  1. #include "SemSegContextTree.h"
  2. #include "vislearning/baselib/Globals.h"
  3. #include "vislearning/baselib/ProgressBar.h"
  4. #include "core/basics/StringTools.h"
  5. #include "vislearning/cbaselib/CachedExample.h"
  6. #include "vislearning/cbaselib/PascalResults.h"
  7. #include "vislearning/baselib/ColorSpace.h"
  8. #include "objrec/segmentation/RSMeanShift.h"
  9. #include "objrec/segmentation/RSGraphBased.h"
  10. #include "core/basics/numerictools.h"
  11. #include "core/basics/StringTools.h"
  12. #include "core/basics/FileName.h"
  13. #include "vislearning/baselib/ICETools.h"
  14. #include "core/basics/Timer.h"
  15. #include "core/basics/vectorio.h"
  16. #include "core/image/FilterT.h"
  17. #include <omp.h>
  18. #include <iostream>
  19. #undef LOCALFEATS
  20. #undef WRITEGLOB
  21. #undef TEXTONMAP
  22. #undef DEBUG
  23. //#define LOCALFEATS
  24. using namespace OBJREC;
  25. using namespace std;
  26. using namespace NICE;
  27. SemSegContextTree::SemSegContextTree ( const Config *conf, const MultiDataset *md )
  28. : SemanticSegmentation ( conf, & ( md->getClassNames ( "train" ) ) )
  29. {
  30. this->conf = conf;
  31. string section = "SSContextTree";
  32. lfcw = new LFColorWeijer ( conf );
  33. firstiteration = true;
  34. grid = conf->gI ( section, "grid", 10 );
  35. maxSamples = conf->gI ( section, "max_samples", 2000 );
  36. minFeats = conf->gI ( section, "min_feats", 50 );
  37. maxDepth = conf->gI ( section, "max_depth", 10 );
  38. windowSize = conf->gI ( section, "window_size", 16 );
  39. featsPerSplit = conf->gI ( section, "feats_per_split", 200 );
  40. useShannonEntropy = conf->gB ( section, "use_shannon_entropy", true );
  41. nbTrees = conf->gI ( section, "amount_trees", 1 );
  42. string segmentationtype = conf->gS ( section, "segmentation_type", "meanshift" );
  43. randomTests = conf->gI ( section, "random_tests", 10 );
  44. bool saveLoadData = conf->gB ( "debug", "save_load_data", false );
  45. string fileLocation = conf->gS ( "debug", "datafile", "tmp.txt" );
  46. pixelWiseLabeling = false;
  47. useRegionFeature = true;
  48. if ( segmentationtype == "meanshift" )
  49. segmentation = new RSMeanShift ( conf );
  50. else if ( segmentationtype == "none" )
  51. {
  52. segmentation = NULL;
  53. pixelWiseLabeling = true;
  54. useRegionFeature = false;
  55. }
  56. else if ( segmentationtype == "felzenszwalb" )
  57. segmentation = new RSGraphBased ( conf );
  58. else
  59. throw ( "no valid segmenation_type\n please choose between none, meanshift and felzenszwalb\n" );
  60. ftypes = conf->gI ( section, "features", 100 );;
  61. string featsec = "Features";
  62. vector<Operation*> tops;
  63. if ( conf->gB ( featsec, "minus", true ) )
  64. tops.push_back ( new Minus() );
  65. if ( conf->gB ( featsec, "minus_abs", true ) )
  66. tops.push_back ( new MinusAbs() );
  67. if ( conf->gB ( featsec, "addition", true ) )
  68. tops.push_back ( new Addition() );
  69. if ( conf->gB ( featsec, "only1", true ) )
  70. tops.push_back ( new Only1() );
  71. if ( conf->gB ( featsec, "rel_x", true ) )
  72. tops.push_back ( new RelativeXPosition() );
  73. if ( conf->gB ( featsec, "rel_y", true ) )
  74. tops.push_back ( new RelativeYPosition() );
  75. ops.push_back ( tops );
  76. tops.clear();
  77. tops.push_back ( new Equality() );
  78. ops.push_back ( tops );
  79. tops.clear();
  80. if ( conf->gB ( featsec, "bi_int_cent", true ) )
  81. tops.push_back ( new BiIntegralCenteredOps() );
  82. if ( conf->gB ( featsec, "int_cent", true ) )
  83. tops.push_back ( new IntegralCenteredOps() );
  84. if ( conf->gB ( featsec, "int", true ) )
  85. tops.push_back ( new IntegralOps() );
  86. if ( conf->gB ( featsec, "haar_horz", true ) )
  87. tops.push_back ( new HaarHorizontal() );
  88. if ( conf->gB ( featsec, "haar_vert", true ) )
  89. tops.push_back ( new HaarVertical() );
  90. if ( conf->gB ( featsec, "haar_diag", true ) )
  91. tops.push_back ( new HaarDiag() );
  92. if ( conf->gB ( featsec, "haar3_horz", true ) )
  93. tops.push_back ( new Haar3Horiz() );
  94. if ( conf->gB ( featsec, "haar3_vert", true ) )
  95. tops.push_back ( new Haar3Vert() );
  96. if ( conf->gB ( featsec, "glob", true ) )
  97. tops.push_back ( new GlobalFeats() );
  98. ops.push_back ( tops );
  99. ops.push_back ( tops );
  100. tops.clear();
  101. if ( conf->gB ( featsec, "minus", true ) )
  102. tops.push_back ( new Minus() );
  103. if ( conf->gB ( featsec, "minus_abs", true ) )
  104. tops.push_back ( new MinusAbs() );
  105. if ( conf->gB ( featsec, "addition", true ) )
  106. tops.push_back ( new Addition() );
  107. if ( conf->gB ( featsec, "only1", true ) )
  108. tops.push_back ( new Only1() );
  109. if ( conf->gB ( featsec, "rel_x", true ) )
  110. tops.push_back ( new RelativeXPosition() );
  111. if ( conf->gB ( featsec, "rel_y", true ) )
  112. tops.push_back ( new RelativeYPosition() );
  113. ops.push_back ( tops );
  114. useGradient = conf->gB ( featsec, "use_gradient", true );
  115. // geometric features of hoiem
  116. useHoiemFeatures = conf->gB ( featsec, "use_hoiem_features", false );
  117. if ( useHoiemFeatures )
  118. {
  119. hoiemDirectory = conf->gS ( featsec, "hoiem_directory" );
  120. }
  121. opOverview = vector<int> ( NBOPERATIONS, 0 );
  122. contextOverview = vector<vector<double> > ( maxDepth, vector<double> ( 2, 0.0 ) );
  123. calcVal.push_back ( new MCImageAccess() );
  124. calcVal.push_back ( new MCImageAccess() );
  125. calcVal.push_back ( new MCImageAccess() );
  126. calcVal.push_back ( new MCImageAccess() );
  127. calcVal.push_back ( new ClassificationResultAccess() );
  128. classnames = md->getClassNames ( "train" );
  129. ///////////////////////////////////
  130. // Train Segmentation Context Trees
  131. ///////////////////////////////////
  132. if ( saveLoadData )
  133. {
  134. if ( FileMgt::fileExists ( fileLocation ) )
  135. read ( fileLocation );
  136. else
  137. {
  138. train ( md );
  139. write ( fileLocation );
  140. }
  141. }
  142. else
  143. {
  144. train ( md );
  145. }
  146. }
  147. SemSegContextTree::~SemSegContextTree()
  148. {
  149. }
  150. double SemSegContextTree::getBestSplit ( std::vector<NICE::MultiChannelImageT<double> > &feats, std::vector<NICE::MultiChannelImageT<unsigned short int> > &currentfeats, const std::vector<NICE::MatrixT<int> > &labels, int node, Operation *&splitop, double &splitval, const int &tree )
  151. {
  152. Timer t;
  153. t.start();
  154. int imgCount = 0;
  155. try
  156. {
  157. imgCount = ( int ) feats.size();
  158. }
  159. catch ( Exception )
  160. {
  161. cerr << "no features computed?" << endl;
  162. }
  163. double bestig = -numeric_limits< double >::max();
  164. splitop = NULL;
  165. splitval = -1.0;
  166. set<vector<int> >selFeats;
  167. map<int, int> e;
  168. int featcounter = forest[tree][node].featcounter;
  169. if ( featcounter < minFeats )
  170. {
  171. //cout << "only " << featcounter << " feats in current node -> it's a leaf" << endl;
  172. return 0.0;
  173. }
  174. vector<double> fraction ( a.size(), 0.0 );
  175. for ( uint i = 0; i < fraction.size(); i++ )
  176. {
  177. if ( forbidden_classes.find ( labelmapback[i] ) != forbidden_classes.end() )
  178. fraction[i] = 0;
  179. else
  180. fraction[i] = ( ( double ) maxSamples ) / ( ( double ) featcounter * a[i] * a.size() );
  181. }
  182. featcounter = 0;
  183. for ( int iCounter = 0; iCounter < imgCount; iCounter++ )
  184. {
  185. int xsize = ( int ) currentfeats[iCounter].width();
  186. int ysize = ( int ) currentfeats[iCounter].height();
  187. for ( int x = 0; x < xsize; x++ )
  188. {
  189. for ( int y = 0; y < ysize; y++ )
  190. {
  191. if ( currentfeats[iCounter].get ( x, y, tree ) == node )
  192. {
  193. int cn = labels[iCounter] ( x, y );
  194. double randD = ( double ) rand() / ( double ) RAND_MAX;
  195. if ( labelmap.find ( cn ) == labelmap.end() )
  196. continue;
  197. if ( randD < fraction[labelmap[cn]] )
  198. {
  199. vector<int> tmp ( 3, 0 );
  200. tmp[0] = iCounter;
  201. tmp[1] = x;
  202. tmp[2] = y;
  203. featcounter++;
  204. selFeats.insert ( tmp );
  205. e[cn]++;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. map<int, int>::iterator mapit;
  212. double globent = 0.0;
  213. for ( mapit = e.begin() ; mapit != e.end(); mapit++ )
  214. {
  215. double p = ( double ) ( *mapit ).second / ( double ) featcounter;
  216. globent += p * log2 ( p );
  217. }
  218. globent = -globent;
  219. if ( globent < 0.5 )
  220. {
  221. return 0.0;
  222. }
  223. /** vector of all possible features */
  224. std::vector<Operation*> featsel;
  225. for ( int i = 0; i < featsPerSplit; i++ )
  226. {
  227. int x1, x2, y1, y2;
  228. int ft = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) ftypes );
  229. int tmpws = windowSize;
  230. if ( ft > 1 && firstiteration )
  231. ft = 0;
  232. if ( channelsPerType[ft].size() == 0 )
  233. {
  234. ft = 0;
  235. }
  236. if ( ft > 1 )
  237. {
  238. //use larger window size for context features
  239. tmpws *= 4;
  240. }
  241. x1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  242. x2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  243. y1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  244. y2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) tmpws ) - tmpws / 2;
  245. int f1 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) channelsPerType[ft].size() );
  246. int f2 = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) channelsPerType[ft].size() );
  247. int o = ( int ) ( ( double ) rand() / ( double ) RAND_MAX * ( double ) ops[ft].size() );
  248. Operation *op = ops[ft][o]->clone();
  249. op->set ( x1, y1, x2, y2, channelsPerType[ft][f1], channelsPerType[ft][f2], calcVal[ft] );
  250. //if( i < 10)
  251. //cerr << "type: " << ft << " features: " << op->writeInfos() << endl;
  252. if ( ft == 3 || ft == 4 )
  253. op->setContext ( true );
  254. else
  255. op->setContext ( false );
  256. //if(ft == 4)
  257. //cerr << "type: " << ft << " features: " << op->writeInfos() << endl;
  258. featsel.push_back ( op );
  259. }
  260. #pragma omp parallel for private(mapit)
  261. for ( int f = 0; f < featsPerSplit; f++ )
  262. {
  263. double l_bestig = -numeric_limits< double >::max();
  264. double l_splitval = -1.0;
  265. set<vector<int> >::iterator it;
  266. vector<double> vals;
  267. double maxval = -numeric_limits<double>::max();
  268. double minval = numeric_limits<double>::max();
  269. for ( it = selFeats.begin() ; it != selFeats.end(); it++ )
  270. {
  271. Features feat;
  272. feat.feats = &feats[ ( *it ) [0]];
  273. feat.cfeats = &currentfeats[ ( *it ) [0]];
  274. feat.cTree = tree;
  275. feat.tree = &forest[tree];
  276. double val = featsel[f]->getVal ( feat, ( *it ) [1], ( *it ) [2] );
  277. vals.push_back ( val );
  278. maxval = std::max ( val, maxval );
  279. minval = std::min ( val, minval );
  280. }
  281. if ( minval == maxval )
  282. continue;
  283. double scale = maxval - minval;
  284. vector<double> splits;
  285. for ( int r = 0; r < randomTests; r++ )
  286. {
  287. splits.push_back ( ( ( double ) rand() / ( double ) RAND_MAX*scale ) + minval );
  288. }
  289. for ( int run = 0 ; run < randomTests; run++ )
  290. {
  291. set<vector<int> >::iterator it2;
  292. double val = splits[run];
  293. map<int, int> eL, eR;
  294. int counterL = 0, counterR = 0;
  295. int counter2 = 0;
  296. for ( it2 = selFeats.begin() ; it2 != selFeats.end(); it2++, counter2++ )
  297. {
  298. int cn = labels[ ( *it2 ) [0]] ( ( *it2 ) [1], ( *it2 ) [2] );
  299. //cout << "vals[counter2] " << vals[counter2] << " val: " << val << endl;
  300. if ( vals[counter2] < val )
  301. {
  302. //left entropie:
  303. eL[cn] = eL[cn] + 1;
  304. counterL++;
  305. }
  306. else
  307. {
  308. //right entropie:
  309. eR[cn] = eR[cn] + 1;
  310. counterR++;
  311. }
  312. }
  313. double leftent = 0.0;
  314. for ( mapit = eL.begin() ; mapit != eL.end(); mapit++ )
  315. {
  316. double p = ( double ) ( *mapit ).second / ( double ) counterL;
  317. leftent -= p * log2 ( p );
  318. }
  319. double rightent = 0.0;
  320. for ( mapit = eR.begin() ; mapit != eR.end(); mapit++ )
  321. {
  322. double p = ( double ) ( *mapit ).second / ( double ) counterR;
  323. rightent -= p * log2 ( p );
  324. }
  325. //cout << "rightent: " << rightent << " leftent: " << leftent << endl;
  326. double pl = ( double ) counterL / ( double ) ( counterL + counterR );
  327. double ig = globent - ( 1.0 - pl ) * rightent - pl * leftent;
  328. //double ig = globent - rightent - leftent;
  329. if ( useShannonEntropy )
  330. {
  331. double esplit = - ( pl * log ( pl ) + ( 1 - pl ) * log ( 1 - pl ) );
  332. ig = 2 * ig / ( globent + esplit );
  333. }
  334. if ( ig > l_bestig )
  335. {
  336. l_bestig = ig;
  337. l_splitval = val;
  338. }
  339. }
  340. #pragma omp critical
  341. {
  342. if ( l_bestig > bestig )
  343. {
  344. bestig = l_bestig;
  345. splitop = featsel[f];
  346. splitval = l_splitval;
  347. }
  348. }
  349. }
  350. //FIXME: delete all features!
  351. /*for(int i = 0; i < featsPerSplit; i++)
  352. {
  353. if(featsel[i] != splitop)
  354. delete featsel[i];
  355. }*/
  356. #ifdef DEBUGA
  357. cout << "globent: " << globent << " bestig " << bestig << " splitval: " << splitval << endl;
  358. #endif
  359. return bestig;
  360. }
  361. inline double SemSegContextTree::getMeanProb ( const int &x, const int &y, const int &channel, const MultiChannelImageT<unsigned short int> &currentfeats )
  362. {
  363. double val = 0.0;
  364. for ( int tree = 0; tree < nbTrees; tree++ )
  365. {
  366. val += forest[tree][currentfeats.get ( x,y,tree ) ].dist[channel];
  367. }
  368. return val / ( double ) nbTrees;
  369. }
  370. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<SparseVectorInt> &infeats, NICE::MultiChannelImageT<SparseVectorInt> &integralImage )
  371. {
  372. int xsize = infeats.width();
  373. int ysize = infeats.height();
  374. integralImage ( 0, 0 ).add ( infeats.get ( 0, 0 ) );
  375. //first column
  376. for ( int y = 1; y < ysize; y++ )
  377. {
  378. integralImage ( 0, y ).add ( infeats.get ( 0, y ) );
  379. integralImage ( 0, y ).add ( integralImage ( 0, y - 1 ) );
  380. }
  381. //first row
  382. for ( int x = 1; x < xsize; x++ )
  383. {
  384. integralImage ( x, 0 ).add ( infeats.get ( x, 0 ) );
  385. integralImage ( x, 0 ).add ( integralImage ( x - 1, 0 ) );
  386. }
  387. //rest
  388. for ( int y = 1; y < ysize; y++ )
  389. {
  390. for ( int x = 1; x < xsize; x++ )
  391. {
  392. integralImage ( x, y ).add ( infeats.get ( x, y ) );
  393. integralImage ( x, y ).add ( integralImage ( x, y - 1 ) );
  394. integralImage ( x, y ).add ( integralImage ( x - 1, y ) );
  395. integralImage ( x, y ).sub ( integralImage ( x - 1, y - 1 ) );
  396. }
  397. }
  398. }
  399. void SemSegContextTree::computeIntegralImage ( const NICE::MultiChannelImageT<unsigned short int> &currentfeats, NICE::MultiChannelImageT<double> &feats, int firstChannel )
  400. {
  401. int xsize = currentfeats.width();
  402. int ysize = currentfeats.height();
  403. xsize = feats.width();
  404. ysize = feats.height();
  405. if ( firstiteration )
  406. {
  407. firstiteration = false;
  408. #pragma omp parallel for
  409. for ( int it = 0; it < ( int ) integralMap.size(); it++ )
  410. {
  411. //cerr << "there are " << omp_get_num_threads() << " threads. " << endl;
  412. //cerr << "current thread: " << omp_get_thread_num() << endl;
  413. int c1 = integralMap[it].first;
  414. int c = integralMap[it].second;
  415. feats ( 0, 0, c ) = feats ( 0, 0, c1 );
  416. //first column
  417. for ( int y = 1; y < ysize; y++ )
  418. {
  419. feats ( 0, y, c ) = feats.get ( 0, y, c1 )
  420. + feats.get ( 0, y - 1, c );
  421. }
  422. //first row
  423. for ( int x = 1; x < xsize; x++ )
  424. {
  425. feats ( x, 0, c ) = feats.get ( x, 0, c1 )
  426. + feats.get ( x - 1, 0, c );
  427. }
  428. //rest
  429. for ( int y = 1; y < ysize; y++ )
  430. {
  431. for ( int x = 1; x < xsize; x++ )
  432. {
  433. feats ( x, y, c ) = feats ( x, y, c1 )
  434. + feats ( x, y - 1, c )
  435. + feats ( x - 1, y, c )
  436. - feats ( x - 1, y - 1, c );
  437. }
  438. }
  439. }
  440. }
  441. int channels = ( int ) forest[0][0].dist.size();
  442. #pragma omp parallel for
  443. for ( int c = 0; c < channels; c++ )
  444. {
  445. feats ( 0, 0, firstChannel + c ) = getMeanProb ( 0, 0, c, currentfeats );
  446. //first column
  447. for ( int y = 1; y < ysize; y++ )
  448. {
  449. feats ( 0, y, firstChannel + c ) = getMeanProb ( 0, y, c, currentfeats )
  450. + feats ( 0, y - 1, firstChannel + c );
  451. }
  452. //first row
  453. for ( int x = 1; x < xsize; x++ )
  454. {
  455. feats ( x, 0, firstChannel + c ) = getMeanProb ( x, 0, c, currentfeats )
  456. + feats ( x - 1, 0, firstChannel + c );
  457. }
  458. //rest
  459. for ( int y = 1; y < ysize; y++ )
  460. {
  461. for ( int x = 1; x < xsize; x++ )
  462. {
  463. feats ( x, y, firstChannel + c ) = getMeanProb ( x, y, c, currentfeats )
  464. + feats ( x, y - 1, firstChannel + c )
  465. + feats ( x - 1, y, firstChannel + c )
  466. - feats ( x - 1, y - 1, firstChannel + c );
  467. }
  468. }
  469. }
  470. }
  471. inline double computeWeight ( const double &d, const double &dim )
  472. {
  473. return 1.0 / ( pow ( 2, ( double ) ( dim - d + 1 ) ) );
  474. }
  475. void SemSegContextTree::train ( const MultiDataset *md )
  476. {
  477. Timer timer;
  478. timer.start();
  479. const LabeledSet train = * ( *md ) ["train"];
  480. const LabeledSet *trainp = &train;
  481. ProgressBar pb ( "compute feats" );
  482. pb.show();
  483. //TODO: Speichefresser!, lohnt sich sparse?
  484. vector<MultiChannelImageT<double> > allfeats;
  485. vector<MultiChannelImageT<unsigned short int> > currentfeats;
  486. vector<MatrixT<int> > labels;
  487. #ifdef TEXTONMAP
  488. vector<MultiChannelImageT<SparseVectorInt> > textonMap;
  489. #endif
  490. vector<MultiChannelImageT<SparseVectorInt> > integralTexton;
  491. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  492. if ( forbidden_classes_s == "" )
  493. {
  494. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  495. }
  496. classnames.getSelection ( forbidden_classes_s, forbidden_classes );
  497. int imgcounter = 0;
  498. int amountPixels = 0;
  499. LOOP_ALL_S ( *trainp )
  500. {
  501. EACH_INFO ( classno, info );
  502. NICE::ColorImage img;
  503. std::string currentFile = info.img();
  504. CachedExample *ce = new CachedExample ( currentFile );
  505. const LocalizationResult *locResult = info.localization();
  506. if ( locResult->size() <= 0 )
  507. {
  508. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  509. currentFile.c_str() );
  510. continue;
  511. }
  512. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n", currentFile.c_str() );
  513. int xsize, ysize;
  514. ce->getImageSize ( xsize, ysize );
  515. amountPixels += xsize * ysize;
  516. MatrixT<int> tmpMat ( xsize, ysize );
  517. currentfeats.push_back ( MultiChannelImageT<unsigned short int> ( xsize, ysize, nbTrees ) );
  518. currentfeats[imgcounter].setAll ( 0 );
  519. #ifdef TEXTONMAP
  520. textonMap.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  521. integralTexton.push_back ( MultiChannelImageT<SparseVectorInt> ( xsize / grid + 1, ysize / grid + 1, 1 ) );
  522. #endif
  523. labels.push_back ( tmpMat );
  524. try {
  525. img = ColorImage ( currentFile );
  526. } catch ( Exception ) {
  527. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  528. continue;
  529. }
  530. Globals::setCurrentImgFN ( currentFile );
  531. //TODO: resize image?!
  532. MultiChannelImageT<double> feats;
  533. allfeats.push_back ( feats );
  534. // read image and do some simple transformations
  535. extractBasicFeatures ( allfeats[imgcounter], img, currentFile );
  536. // getting groundtruth
  537. NICE::Image pixelLabels ( xsize, ysize );
  538. pixelLabels.set ( 0 );
  539. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  540. for ( int x = 0; x < xsize; x++ )
  541. {
  542. for ( int y = 0; y < ysize; y++ )
  543. {
  544. classno = pixelLabels.getPixel ( x, y );
  545. labels[imgcounter] ( x, y ) = classno;
  546. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  547. continue;
  548. labelcounter[classno]++;
  549. }
  550. }
  551. imgcounter++;
  552. pb.update ( trainp->count() );
  553. delete ce;
  554. }
  555. pb.hide();
  556. map<int, int>::iterator mapit;
  557. int classes = 0;
  558. for ( mapit = labelcounter.begin(); mapit != labelcounter.end(); mapit++ )
  559. {
  560. labelmap[mapit->first] = classes;
  561. labelmapback[classes] = mapit->first;
  562. classes++;
  563. }
  564. ////////////////////////////////////////////////////
  565. //define which featurextraction methods should be used for each channel
  566. #ifdef LOCALFEATS
  567. rawChannels = 11;
  568. #else
  569. rawChannels = 3;
  570. #endif
  571. // how many channels without integral image
  572. int shift = 0;
  573. if ( useGradient )
  574. rawChannels *= 2;
  575. if ( useHoiemFeatures )
  576. rawChannels += 8;
  577. // gray value images
  578. for ( int i = 0; i < rawChannels; i++ )
  579. {
  580. channelType.push_back ( 0 );
  581. }
  582. // regions
  583. if ( useRegionFeature )
  584. {
  585. channelType.push_back ( 1 );
  586. shift++;
  587. }
  588. for ( int i = 0; i < rawChannels; i++ )
  589. {
  590. channelType.push_back ( 2 );
  591. }
  592. // integral images
  593. for ( int i = 0; i < classes; i++ )
  594. {
  595. channelType.push_back ( 3 );
  596. }
  597. integralMap.clear();
  598. int integralImageAmount = rawChannels;
  599. for ( int ii = 0; ii < integralImageAmount; ii++ )
  600. {
  601. integralMap.push_back ( pair<int, int> ( ii, ii + integralImageAmount + shift ) );
  602. }
  603. int amountTypes = 5;
  604. channelsPerType = vector<vector<int> > ( amountTypes, vector<int>() );
  605. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  606. {
  607. channelsPerType[channelType[i]].push_back ( i );
  608. }
  609. for ( int i = 0; i < classes; i++ )
  610. {
  611. channelsPerType[channelsPerType.size()-1].push_back ( i );
  612. }
  613. ftypes = std::min ( amountTypes, ftypes );
  614. ////////////////////////////////////////////////////
  615. //balancing
  616. int featcounter = 0;
  617. a = vector<double> ( classes, 0.0 );
  618. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  619. {
  620. int xsize = ( int ) currentfeats[iCounter].width();
  621. int ysize = ( int ) currentfeats[iCounter].height();
  622. for ( int x = 0; x < xsize; x++ )
  623. {
  624. for ( int y = 0; y < ysize; y++ )
  625. {
  626. featcounter++;
  627. int cn = labels[iCounter] ( x, y );
  628. if ( labelmap.find ( cn ) == labelmap.end() )
  629. continue;
  630. a[labelmap[cn]] ++;
  631. }
  632. }
  633. }
  634. for ( int i = 0; i < ( int ) a.size(); i++ )
  635. {
  636. a[i] /= ( double ) featcounter;
  637. }
  638. #ifdef DEBUG
  639. for ( int i = 0; i < ( int ) a.size(); i++ )
  640. {
  641. cout << "a[" << i << "]: " << a[i] << endl;
  642. }
  643. cout << "a.size: " << a.size() << endl;
  644. #endif
  645. depth = 0;
  646. int uniquenumber = 0;
  647. for ( int t = 0; t < nbTrees; t++ )
  648. {
  649. vector<TreeNode> tree;
  650. tree.push_back ( TreeNode() );
  651. tree[0].dist = vector<double> ( classes, 0.0 );
  652. tree[0].depth = depth;
  653. tree[0].featcounter = amountPixels;
  654. tree[0].nodeNumber = uniquenumber;
  655. uniquenumber++;
  656. forest.push_back ( tree );
  657. }
  658. vector<int> startnode ( nbTrees, 0 );
  659. bool allleaf = false;
  660. //int baseFeatSize = allfeats[0].size();
  661. timer.stop();
  662. cerr << "preprocessing finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  663. timer.start();
  664. while ( !allleaf && depth < maxDepth )
  665. {
  666. depth++;
  667. #ifdef DEBUG
  668. cout << "depth: " << depth << endl;
  669. #endif
  670. allleaf = true;
  671. vector<MultiChannelImageT<unsigned short int> > lastfeats = currentfeats;
  672. #if 1
  673. Timer timerDepth;
  674. timerDepth.start();
  675. #endif
  676. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  677. if ( depth == 1 )
  678. {
  679. weight = computeWeight ( 1, maxDepth );
  680. }
  681. // omp_set_dynamic(0);
  682. //#pragma omp parallel for
  683. for ( int tree = 0; tree < nbTrees; tree++ )
  684. {
  685. const int t = ( int ) forest[tree].size();
  686. const int s = startnode[tree];
  687. startnode[tree] = t;
  688. #pragma omp parallel for
  689. for ( int i = s; i < t; i++ )
  690. {
  691. if ( !forest[tree][i].isleaf && forest[tree][i].left < 0 )
  692. {
  693. Operation *splitfeat = NULL;
  694. double splitval;
  695. double bestig = getBestSplit ( allfeats, lastfeats, labels, i, splitfeat, splitval, tree );
  696. for ( int ii = 0; ii < ( int ) lastfeats.size(); ii++ )
  697. {
  698. for ( int c = 0; c < lastfeats[ii].channels(); c++ )
  699. {
  700. short unsigned int minv, maxv;
  701. lastfeats[ii].statistics ( minv, maxv, c );
  702. }
  703. }
  704. forest[tree][i].feat = splitfeat;
  705. forest[tree][i].decision = splitval;
  706. if ( splitfeat != NULL )
  707. {
  708. allleaf = false;
  709. int left;
  710. #pragma omp critical
  711. {
  712. left = forest[tree].size();
  713. forest[tree].push_back ( TreeNode() );
  714. forest[tree].push_back ( TreeNode() );
  715. }
  716. int right = left + 1;
  717. forest[tree][i].left = left;
  718. forest[tree][i].right = right;
  719. forest[tree][left].dist = vector<double> ( classes, 0.0 );
  720. forest[tree][right].dist = vector<double> ( classes, 0.0 );
  721. forest[tree][left].depth = depth;
  722. forest[tree][right].depth = depth;
  723. forest[tree][left].featcounter = 0;
  724. forest[tree][right].featcounter = 0;
  725. forest[tree][left].nodeNumber = uniquenumber;
  726. int leftu = uniquenumber;
  727. uniquenumber++;
  728. forest[tree][right].nodeNumber = uniquenumber;
  729. int rightu = uniquenumber;
  730. uniquenumber++;
  731. forest[tree][right].featcounter = 0;
  732. #pragma omp parallel for
  733. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  734. {
  735. int xsize = currentfeats[iCounter].width();
  736. int ysize = currentfeats[iCounter].height();
  737. for ( int x = 0; x < xsize; x++ )
  738. {
  739. for ( int y = 0; y < ysize; y++ )
  740. {
  741. if ( currentfeats[iCounter].get ( x, y, tree ) == i )
  742. {
  743. Features feat;
  744. feat.feats = &allfeats[iCounter];
  745. feat.cfeats = &lastfeats[iCounter];
  746. feat.cTree = tree;
  747. feat.tree = &forest[tree];
  748. double val = splitfeat->getVal ( feat, x, y );
  749. //int subx = x / grid;
  750. //int suby = y / grid;
  751. #pragma omp critical
  752. if ( val < splitval )
  753. {
  754. currentfeats[iCounter].set ( x, y, left, tree );
  755. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  756. forest[tree][left].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  757. forest[tree][left].featcounter++;
  758. SparseVectorInt v;
  759. v.insert ( pair<int, double> ( leftu, weight ) );
  760. #ifdef TEXTONMAP
  761. textonMap[iCounter] ( subx, suby ).add ( v );
  762. #endif
  763. }
  764. else
  765. {
  766. currentfeats[iCounter].set ( x, y, right, tree );
  767. if ( labelmap.find ( labels[iCounter] ( x, y ) ) != labelmap.end() )
  768. forest[tree][right].dist[labelmap[labels[iCounter] ( x, y ) ]]++;
  769. forest[tree][right].featcounter++;
  770. //feld im subsampled finden und in diesem rechts hochzählen
  771. SparseVectorInt v;
  772. v.insert ( pair<int, double> ( rightu, weight ) );
  773. #ifdef TEXTONMAP
  774. textonMap[iCounter] ( subx, suby ).add ( v );
  775. #endif
  776. }
  777. }
  778. }
  779. }
  780. }
  781. double lcounter = 0.0, rcounter = 0.0;
  782. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  783. {
  784. if ( forbidden_classes.find ( labelmapback[d] ) != forbidden_classes.end() )
  785. {
  786. forest[tree][left].dist[d] = 0;
  787. forest[tree][right].dist[d] = 0;
  788. }
  789. else
  790. {
  791. forest[tree][left].dist[d] /= a[d];
  792. lcounter += forest[tree][left].dist[d];
  793. forest[tree][right].dist[d] /= a[d];
  794. rcounter += forest[tree][right].dist[d];
  795. }
  796. }
  797. if ( lcounter <= 0 || rcounter <= 0 )
  798. {
  799. cout << "lcounter : " << lcounter << " rcounter: " << rcounter << endl;
  800. cout << "splitval: " << splitval << " splittype: " << splitfeat->writeInfos() << endl;
  801. cout << "bestig: " << bestig << endl;
  802. for ( int iCounter = 0; iCounter < imgcounter; iCounter++ )
  803. {
  804. int xsize = currentfeats[iCounter].width();
  805. int ysize = currentfeats[iCounter].height();
  806. int counter = 0;
  807. for ( int x = 0; x < xsize; x++ )
  808. {
  809. for ( int y = 0; y < ysize; y++ )
  810. {
  811. if ( lastfeats[iCounter].get ( x, y, tree ) == i )
  812. {
  813. if ( ++counter > 30 )
  814. break;
  815. Features feat;
  816. feat.feats = &allfeats[iCounter];
  817. feat.cfeats = &lastfeats[iCounter];
  818. feat.cTree = tree;
  819. feat.tree = &forest[tree];
  820. double val = splitfeat->getVal ( feat, x, y );
  821. cout << "splitval: " << splitval << " val: " << val << endl;
  822. }
  823. }
  824. }
  825. }
  826. assert ( lcounter > 0 && rcounter > 0 );
  827. }
  828. for ( uint d = 0; d < forest[tree][left].dist.size(); d++ )
  829. {
  830. forest[tree][left].dist[d] /= lcounter;
  831. forest[tree][right].dist[d] /= rcounter;
  832. }
  833. }
  834. else
  835. {
  836. forest[tree][i].isleaf = true;
  837. }
  838. }
  839. }
  840. }
  841. //compute integral images
  842. if ( firstiteration )
  843. {
  844. for ( int i = 0; i < imgcounter; i++ )
  845. {
  846. allfeats[i].addChannel ( ( int ) ( classes + rawChannels ) );
  847. }
  848. }
  849. for ( int i = 0; i < imgcounter; i++ )
  850. {
  851. computeIntegralImage ( currentfeats[i], allfeats[i], channelType.size() - classes );
  852. #ifdef TEXTONMAP
  853. computeIntegralImage ( textonMap[i], integralTexton[i] );
  854. #endif
  855. }
  856. #if 1
  857. timerDepth.stop();
  858. cout << "time for depth " << depth << ": " << timerDepth.getLastAbsolute() << endl;
  859. #endif
  860. }
  861. timer.stop();
  862. cerr << "learning finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  863. timer.start();
  864. #ifdef WRITEGLOB
  865. ofstream outstream ( "globtrain.feat" );
  866. for ( int i = 0; i < textonMap.size(); i++ )
  867. {
  868. set<int> usedclasses;
  869. for ( uint x = 0; x < labels[i].rows(); x++ )
  870. {
  871. for ( uint y = 0; y < labels[i].cols(); y++ )
  872. {
  873. int classno = labels[i] ( x, y );
  874. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  875. continue;
  876. usedclasses.insert ( classno );
  877. }
  878. }
  879. cout << "labels.cols: " << labels[i].cols() << " labels.rows " << labels[i].rows() << endl;
  880. cout << "currentfeats : " << allfeats[i].width() << " allfeats[i].height(); " << allfeats[i].height() << endl;
  881. set<int>::iterator it;
  882. for ( it = usedclasses.begin() ; it != usedclasses.end(); it++ )
  883. outstream << *it << " ";
  884. outstream << endl;
  885. integralTexton[i] ( integralTexton[i].width() - 1, integralTexton[i].height() - 1 ).store ( outstream );
  886. }
  887. outstream.close();
  888. #endif
  889. cout << "uniquenumber " << uniquenumber << endl;
  890. //getchar();
  891. #ifdef DEBUG
  892. for ( int tree = 0; tree < nbTrees; tree++ )
  893. {
  894. int t = ( int ) forest[tree].size();
  895. for ( int i = 0; i < t; i++ )
  896. {
  897. printf ( "tree[%i]: left: %i, right: %i", i, forest[tree][i].left, forest[tree][i].right );
  898. if ( !forest[tree][i].isleaf && forest[tree][i].left != -1 )
  899. {
  900. cout << ", feat: " << forest[tree][i].feat->writeInfos() << " ";
  901. opOverview[forest[tree][i].feat->getOps() ]++;
  902. contextOverview[forest[tree][i].depth][ ( int ) forest[tree][i].feat->getContext() ]++;
  903. }
  904. for ( int d = 0; d < ( int ) forest[tree][i].dist.size(); d++ )
  905. {
  906. cout << " " << forest[tree][i].dist[d];
  907. }
  908. cout << endl;
  909. }
  910. }
  911. for ( uint c = 0; c < ops.size(); c++ )
  912. {
  913. for ( int t = 0; t < ops[c].size(); t++ )
  914. {
  915. cout << ops[c][t]->writeInfos() << ": " << opOverview[ops[c][t]->getOps() ] << endl;
  916. }
  917. }
  918. for ( int d = 0; d < maxDepth; d++ )
  919. {
  920. double sum = contextOverview[d][0] + contextOverview[d][1];
  921. contextOverview[d][0] /= sum;
  922. contextOverview[d][1] /= sum;
  923. cout << "depth: " << d << " woContext: " << contextOverview[d][0] << " wContext: " << contextOverview[d][1] << endl;
  924. }
  925. #endif
  926. timer.stop();
  927. cerr << "rest finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  928. timer.start();
  929. }
  930. void SemSegContextTree::extractBasicFeatures ( NICE::MultiChannelImageT<double> &feats, const ColorImage &img, const string &currentFile )
  931. {
  932. int xsize = img.width();
  933. int ysize = img.height();
  934. //TODO: resize image?!
  935. #ifdef LOCALFEATS
  936. lfcw->getFeats ( img, feats );
  937. #else
  938. feats.reInit ( xsize, ysize, 3 );
  939. for ( int x = 0; x < xsize; x++ )
  940. {
  941. for ( int y = 0; y < ysize; y++ )
  942. {
  943. for ( int r = 0; r < 3; r++ )
  944. {
  945. feats.set ( x, y, img.getPixel ( x, y, r ), r );
  946. }
  947. }
  948. }
  949. feats = ColorSpace::rgbtolab ( feats );
  950. #endif
  951. if ( useGradient )
  952. {
  953. int currentsize = feats.channels();
  954. feats.addChannel ( currentsize );
  955. for ( int c = 0; c < currentsize; c++ )
  956. {
  957. ImageT<double> tmp = feats[c];
  958. ImageT<double> tmp2 = feats[c+currentsize];
  959. NICE::FilterT<double, double, double>::gradientStrength ( tmp, tmp2 );
  960. }
  961. }
  962. // read the geometric cues produced by Hoiem et al.
  963. if ( useHoiemFeatures )
  964. {
  965. // we could also give the following set as a config option
  966. string hoiemClasses_s = "sky 000 090-045 090-090 090-135 090 090-por 090-sol";
  967. vector<string> hoiemClasses;
  968. StringTools::split ( hoiemClasses_s, ' ', hoiemClasses );
  969. // Now we have to do some fancy regular expressions :)
  970. // Original image filename: basel_000083.jpg
  971. // hoiem result: basel_000083_c_sky.png
  972. // Fancy class of Ferid which supports string handling especially for filenames
  973. FileName fn ( currentFile );
  974. fn.removeExtension();
  975. FileName fnBase = fn.extractFileName();
  976. // counter for the channel index, starts with the current size of the destination multi-channel image
  977. int currentChannel = feats.channels();
  978. // add a channel for each feature in advance
  979. feats.addChannel ( hoiemClasses.size() );
  980. // loop through all geometric categories and add the images
  981. for ( vector<string>::const_iterator i = hoiemClasses.begin(); i != hoiemClasses.end(); i++, currentChannel++ )
  982. {
  983. string hoiemClass = *i;
  984. FileName fnConfidenceImage ( hoiemDirectory + fnBase.str() + "_c_" + hoiemClass + ".png" );
  985. if ( ! fnConfidenceImage.fileExists() )
  986. {
  987. fthrow ( Exception, "Unable to read the Hoiem geometric confidence image: " << fnConfidenceImage.str() << " (original image is " << currentFile << ")" );
  988. } else {
  989. Image confidenceImage ( fnConfidenceImage.str() );
  990. // check whether the image size is consistent
  991. if ( confidenceImage.width() != feats.width() || confidenceImage.height() != feats.height() )
  992. {
  993. fthrow ( Exception, "The size of the geometric confidence image does not match with the original image size: " << fnConfidenceImage.str() );
  994. }
  995. ImageT<double> dst = feats[currentChannel];
  996. // copy standard image to double image
  997. for ( uint y = 0 ; y < ( uint ) confidenceImage.height(); y++ )
  998. for ( uint x = 0 ; x < ( uint ) confidenceImage.width(); x++ )
  999. feats ( x, y, currentChannel ) = ( double ) confidenceImage ( x, y );
  1000. }
  1001. }
  1002. }
  1003. }
  1004. void SemSegContextTree::semanticseg ( CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities )
  1005. {
  1006. int xsize;
  1007. int ysize;
  1008. ce->getImageSize ( xsize, ysize );
  1009. firstiteration = true;
  1010. int classes = labelmapback.size();
  1011. int numClasses = classNames->numClasses();
  1012. fprintf ( stderr, "ContextTree classification !\n" );
  1013. probabilities.reInit ( xsize, ysize, numClasses );
  1014. probabilities.setAll ( 0 );
  1015. #ifdef TEXTONMAP
  1016. MultiChannelImageT<SparseVectorInt> textonMap ( xsize / grid + 1, ysize / grid + 1, 1 );
  1017. MultiChannelImageT<SparseVectorInt> integralTexton ( xsize / grid + 1, ysize / grid + 1, 1 );
  1018. #endif
  1019. std::string currentFile = Globals::getCurrentImgFN();
  1020. MultiChannelImageT<double> feats;
  1021. NICE::ColorImage img;
  1022. try {
  1023. img = ColorImage ( currentFile );
  1024. } catch ( Exception ) {
  1025. cerr << "SemSeg: error opening image file <" << currentFile << ">" << endl;
  1026. return;
  1027. }
  1028. extractBasicFeatures ( feats, img, currentFile ); //read image and do some simple transformations
  1029. bool allleaf = false;
  1030. MultiChannelImageT<unsigned short int> currentfeats ( xsize, ysize, nbTrees );
  1031. currentfeats.setAll ( 0 );
  1032. depth = 0;
  1033. for ( int d = 0; d < maxDepth && !allleaf; d++ )
  1034. {
  1035. depth++;
  1036. #ifdef TEXTONMAP
  1037. double weight = computeWeight ( depth, maxDepth ) - computeWeight ( depth - 1, maxDepth );
  1038. if ( depth == 1 )
  1039. {
  1040. weight = computeWeight ( 1, maxDepth );
  1041. }
  1042. #endif
  1043. allleaf = true;
  1044. MultiChannelImageT<unsigned short int> lastfeats = currentfeats;
  1045. int tree;
  1046. #pragma omp parallel for private(tree)
  1047. for ( tree = 0; tree < nbTrees; tree++ )
  1048. {
  1049. for ( int x = 0; x < xsize; x++ )
  1050. {
  1051. for ( int y = 0; y < ysize; y++ )
  1052. {
  1053. int t = currentfeats.get ( x, y, tree );
  1054. if ( forest[tree][t].left > 0 )
  1055. {
  1056. allleaf = false;
  1057. Features feat;
  1058. feat.feats = &feats;
  1059. feat.cfeats = &lastfeats;
  1060. feat.cTree = tree;
  1061. feat.tree = &forest[tree];
  1062. double val = forest[tree][t].feat->getVal ( feat, x, y );
  1063. //int subx = x / grid;
  1064. //int suby = y / grid;
  1065. if ( val < forest[tree][t].decision )
  1066. {
  1067. currentfeats.set ( x, y, forest[tree][t].left, tree );
  1068. #ifdef TEXTONMAP
  1069. #pragma omp critical
  1070. {
  1071. SparseVectorInt v;
  1072. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].left].nodeNumber, weight ) );
  1073. textonMap ( subx, suby ).add ( v );
  1074. }
  1075. #endif
  1076. }
  1077. else
  1078. {
  1079. currentfeats.set ( x, y, forest[tree][t].right, tree );
  1080. #ifdef TEXTONMAP
  1081. #pragma omp critical
  1082. {
  1083. SparseVectorInt v;
  1084. v.insert ( pair<int, double> ( forest[tree][forest[tree][t].right].nodeNumber, weight ) );
  1085. textonMap ( subx, suby ).add ( v );
  1086. }
  1087. #endif
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. if ( depth < maxDepth )
  1094. {
  1095. //compute integral images
  1096. if ( firstiteration )
  1097. {
  1098. feats.addChannel ( classes + rawChannels );
  1099. }
  1100. computeIntegralImage ( currentfeats, feats, channelType.size() - classes );
  1101. #ifdef TEXTONMAP
  1102. computeIntegralImage ( textonMap, integralTexton );
  1103. #endif
  1104. }
  1105. }
  1106. #ifdef WRITEGLOB
  1107. ofstream outstream ( "globtest.feat", ofstream::app );
  1108. outstream << 0 << endl;
  1109. integralTexton ( integralTexton.width() - 1, integralTexton.height() - 1 ).store ( outstream );
  1110. outstream.close();
  1111. #endif
  1112. string cndir = conf->gS ( "SSContextTree", "cndir", "" );
  1113. int allClasses = ( int ) probabilities.channels();
  1114. vector<int> useclass ( allClasses, 1 );
  1115. #ifdef WRITEGLOB
  1116. std::vector< std::string > list;
  1117. StringTools::split ( currentFile, '/', list );
  1118. string orgname = list.back();
  1119. ofstream ostream ( "filelist.txt", ofstream::app );
  1120. ostream << orgname << ".dat" << endl;
  1121. ostream.close();
  1122. if ( cndir != "" )
  1123. {
  1124. useclass = vector<int> ( allClasses, 0 );
  1125. ifstream infile ( ( cndir + "/" + orgname + ".dat" ).c_str() );
  1126. #undef OLD
  1127. #ifdef OLD
  1128. while ( !infile.eof() && infile.good() )
  1129. {
  1130. int tmp;
  1131. infile >> tmp;
  1132. assert ( tmp >= 0 && tmp < allClasses );
  1133. useclass[tmp] = 1;
  1134. }
  1135. #else
  1136. int c = 0;
  1137. vector<double> probs ( allClasses, 0.0 );
  1138. while ( !infile.eof() && infile.good() )
  1139. {
  1140. infile >> probs[c];
  1141. c++;
  1142. }
  1143. vector<double> sorted = probs;
  1144. sort ( sorted.begin(), sorted.end() );
  1145. double thr = sorted[10];
  1146. if ( thr < 0.0 )
  1147. thr = 0.0;
  1148. for ( int c = 0; c < allClasses; c++ )
  1149. {
  1150. if ( probs[c] < thr )
  1151. {
  1152. useclass[c] = 1;
  1153. }
  1154. }
  1155. #endif
  1156. for ( int c = 0; c < allClasses; c++ )
  1157. {
  1158. if ( useclass[c] == 0 )
  1159. {
  1160. probabilities.set ( -numeric_limits< double >::max(), c );
  1161. }
  1162. }
  1163. }
  1164. #endif
  1165. if ( pixelWiseLabeling )
  1166. {
  1167. //finales labeln:
  1168. //long int offset = 0;
  1169. for ( int x = 0; x < xsize; x++ )
  1170. {
  1171. for ( int y = 0; y < ysize; y++ )
  1172. {
  1173. double maxvalue = - numeric_limits<double>::max(); //TODO: das kann auch nur pro knoten gemacht werden, nicht pro pixel
  1174. int maxindex = 0;
  1175. uint s = forest[0][0].dist.size();
  1176. for ( uint i = 0; i < s; i++ )
  1177. {
  1178. int currentclass = labelmapback[i];
  1179. if ( useclass[currentclass] )
  1180. {
  1181. probabilities ( x, y, currentclass ) = getMeanProb ( x, y, i, currentfeats );
  1182. if ( probabilities ( x, y, currentclass ) > maxvalue )
  1183. {
  1184. maxvalue = probabilities ( x, y, currentclass );
  1185. maxindex = currentclass;
  1186. }
  1187. }
  1188. }
  1189. segresult.setPixel ( x, y, maxindex );
  1190. if ( maxvalue > 1 )
  1191. cout << "maxvalue: " << maxvalue << endl;
  1192. }
  1193. }
  1194. #undef VISUALIZE
  1195. #ifdef VISUALIZE
  1196. for ( int j = 0 ; j < ( int ) probabilities.numChannels; j++ )
  1197. {
  1198. //cout << "class: " << j << endl;//" " << cn.text ( j ) << endl;
  1199. NICE::Matrix tmp ( probabilities.height(), probabilities.width() );
  1200. double maxval = -numeric_limits<double>::max();
  1201. double minval = numeric_limits<double>::max();
  1202. for ( int y = 0; y < probabilities.height(); y++ )
  1203. for ( int x = 0; x < probabilities.width(); x++ )
  1204. {
  1205. double val = probabilities ( x, y, j );
  1206. tmp ( y, x ) = val;
  1207. maxval = std::max ( val, maxval );
  1208. minval = std::min ( val, minval );
  1209. }
  1210. tmp ( 0, 0 ) = 1.0;
  1211. tmp ( 0, 1 ) = 0.0;
  1212. NICE::ColorImage imgrgb ( probabilities.width(), probabilities.height() );
  1213. ICETools::convertToRGB ( tmp, imgrgb );
  1214. cout << "maxval = " << maxval << " minval: " << minval << " for class " << j << endl; //cn.text ( j ) << endl;
  1215. std::string s;
  1216. std::stringstream out;
  1217. out << "tmpprebmap" << j << ".ppm";
  1218. s = out.str();
  1219. imgrgb.write ( s );
  1220. //showImage(imgrgb, "Ergebnis");
  1221. //getchar();
  1222. }
  1223. cout << "fertsch" << endl;
  1224. getchar();
  1225. cout << "weiter gehtsch" << endl;
  1226. #endif
  1227. }
  1228. else
  1229. {
  1230. //final labeling using segmentation
  1231. Matrix regions;
  1232. //showImage(img);
  1233. int regionNumber = segmentation->segRegions ( img, regions );
  1234. cout << "regions: " << regionNumber << endl;
  1235. int dSize = forest[0][0].dist.size();
  1236. vector<vector<double> > regionProbs ( regionNumber, vector<double> ( dSize, 0.0 ) );
  1237. vector<int> bestlabels ( regionNumber, 0 );
  1238. for ( int y = 0; y < img.height(); y++ )
  1239. {
  1240. for ( int x = 0; x < img.width(); x++ )
  1241. {
  1242. int cregion = regions ( x, y );
  1243. for ( int d = 0; d < dSize; d++ )
  1244. {
  1245. regionProbs[cregion][d] += getMeanProb ( x, y, d, currentfeats );
  1246. }
  1247. }
  1248. }
  1249. for ( int r = 0; r < regionNumber; r++ )
  1250. {
  1251. double maxval = regionProbs[r][0];
  1252. bestlabels[r] = 0;
  1253. for ( int d = 1; d < dSize; d++ )
  1254. {
  1255. if ( maxval < regionProbs[r][d] )
  1256. {
  1257. maxval = regionProbs[r][d];
  1258. bestlabels[r] = d;
  1259. }
  1260. }
  1261. bestlabels[r] = labelmapback[bestlabels[r]];
  1262. }
  1263. for ( int y = 0; y < img.height(); y++ )
  1264. {
  1265. for ( int x = 0; x < img.width(); x++ )
  1266. {
  1267. segresult.setPixel ( x, y, bestlabels[regions ( x,y ) ] );
  1268. }
  1269. }
  1270. #define WRITEREGIONS
  1271. #ifdef WRITEREGIONS
  1272. RegionGraph rg;
  1273. segmentation->getGraphRepresentation ( img, regions, rg );
  1274. for ( uint pos = 0; pos < regionProbs.size(); pos++ )
  1275. {
  1276. rg[pos]->setProbs ( regionProbs[pos] );
  1277. }
  1278. std::string s;
  1279. std::stringstream out;
  1280. std::vector< std::string > list;
  1281. StringTools::split ( Globals::getCurrentImgFN (), '/', list );
  1282. out << "rgout/" << list.back() << ".graph";
  1283. string writefile = out.str();
  1284. rg.write ( writefile );
  1285. #endif
  1286. }
  1287. cout << "segmentation finished" << endl;
  1288. }
  1289. void SemSegContextTree::store ( std::ostream & os, int format ) const
  1290. {
  1291. os.precision ( numeric_limits<double>::digits10 + 1 );
  1292. os << nbTrees << endl;
  1293. classnames.store ( os );
  1294. map<int, int>::const_iterator it;
  1295. os << labelmap.size() << endl;
  1296. for ( it = labelmap.begin() ; it != labelmap.end(); it++ )
  1297. os << ( *it ).first << " " << ( *it ).second << endl;
  1298. os << labelmapback.size() << endl;
  1299. for ( it = labelmapback.begin() ; it != labelmapback.end(); it++ )
  1300. os << ( *it ).first << " " << ( *it ).second << endl;
  1301. int trees = forest.size();
  1302. os << trees << endl;
  1303. for ( int t = 0; t < trees; t++ )
  1304. {
  1305. int nodes = forest[t].size();
  1306. os << nodes << endl;
  1307. for ( int n = 0; n < nodes; n++ )
  1308. {
  1309. 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;
  1310. os << forest[t][n].dist << endl;
  1311. if ( forest[t][n].feat == NULL )
  1312. os << -1 << endl;
  1313. else
  1314. {
  1315. os << forest[t][n].feat->getOps() << endl;
  1316. forest[t][n].feat->store ( os );
  1317. }
  1318. }
  1319. }
  1320. os << channelType.size() << endl;
  1321. for ( int i = 0; i < ( int ) channelType.size(); i++ )
  1322. {
  1323. os << channelType[i] << " ";
  1324. }
  1325. os << endl;
  1326. os << integralMap.size() << endl;
  1327. for ( int i = 0; i < ( int ) integralMap.size(); i++ )
  1328. {
  1329. os << integralMap[i].first << " " << integralMap[i].second << endl;
  1330. }
  1331. os << rawChannels << endl;
  1332. }
  1333. void SemSegContextTree::restore ( std::istream & is, int format )
  1334. {
  1335. is >> nbTrees;
  1336. classnames.restore ( is );
  1337. int lsize;
  1338. is >> lsize;
  1339. labelmap.clear();
  1340. for ( int l = 0; l < lsize; l++ )
  1341. {
  1342. int first, second;
  1343. is >> first;
  1344. is >> second;
  1345. labelmap[first] = second;
  1346. }
  1347. is >> lsize;
  1348. labelmapback.clear();
  1349. for ( int l = 0; l < lsize; l++ )
  1350. {
  1351. int first, second;
  1352. is >> first;
  1353. is >> second;
  1354. labelmapback[first] = second;
  1355. }
  1356. int trees;
  1357. is >> trees;
  1358. forest.clear();
  1359. for ( int t = 0; t < trees; t++ )
  1360. {
  1361. vector<TreeNode> tmptree;
  1362. forest.push_back ( tmptree );
  1363. int nodes;
  1364. is >> nodes;
  1365. //cout << "nodes: " << nodes << endl;
  1366. for ( int n = 0; n < nodes; n++ )
  1367. {
  1368. TreeNode tmpnode;
  1369. forest[t].push_back ( tmpnode );
  1370. is >> forest[t][n].left;
  1371. is >> forest[t][n].right;
  1372. is >> forest[t][n].decision;
  1373. is >> forest[t][n].isleaf;
  1374. is >> forest[t][n].depth;
  1375. is >> forest[t][n].featcounter;
  1376. is >> forest[t][n].nodeNumber;
  1377. is >> forest[t][n].dist;
  1378. int feattype;
  1379. is >> feattype;
  1380. assert ( feattype < NBOPERATIONS );
  1381. forest[t][n].feat = NULL;
  1382. if ( feattype >= 0 )
  1383. {
  1384. for ( uint o = 0; o < ops.size(); o++ )
  1385. {
  1386. for ( uint o2 = 0; o2 < ops[o].size(); o2++ )
  1387. {
  1388. if ( forest[t][n].feat == NULL )
  1389. {
  1390. for ( uint c = 0; c < ops[o].size(); c++ )
  1391. {
  1392. if ( ops[o][o2]->getOps() == feattype )
  1393. {
  1394. forest[t][n].feat = ops[o][o2]->clone();
  1395. break;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. }
  1401. assert ( forest[t][n].feat != NULL );
  1402. forest[t][n].feat->restore ( is );
  1403. }
  1404. }
  1405. }
  1406. channelType.clear();
  1407. int ctsize;
  1408. is >> ctsize;
  1409. for ( int i = 0; i < ctsize; i++ )
  1410. {
  1411. int tmp;
  1412. is >> tmp;
  1413. channelType.push_back ( tmp );
  1414. }
  1415. integralMap.clear();
  1416. int iMapSize;
  1417. is >> iMapSize;
  1418. for ( int i = 0; i < iMapSize; i++ )
  1419. {
  1420. int first;
  1421. int second;
  1422. is >> first;
  1423. is >> second;
  1424. integralMap.push_back ( pair<int, int> ( first, second ) );
  1425. }
  1426. is >> rawChannels;
  1427. }