SemSegCsurka.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  1. /**
  2. * @file SemSegCsurka.cpp
  3. * @brief semantic segmentation using the method from Csurka08
  4. * @author Björn Fröhlich
  5. * @date 04/24/2009
  6. */
  7. #include <iostream>
  8. #include "SemSegCsurka.h"
  9. #include "objrec/baselib/ICETools.h"
  10. #include "core/image/Filter.h"
  11. #include <sstream>
  12. using namespace std;
  13. using namespace NICE;
  14. using namespace OBJREC;
  15. #undef DEBUG_CSURK
  16. SemSegCsurka::SemSegCsurka ( const Config *conf,
  17. const MultiDataset *md )
  18. : SemanticSegmentation ( conf, & ( md->getClassNames ( "train" ) ) )
  19. {
  20. this->conf = conf;
  21. opSiftImpl = conf->gS ( "Descriptor", "implementation", "VANDESANDE" );
  22. readfeat = conf->gB ( "Descriptor", "read", true );
  23. writefeat = conf->gB ( "Descriptor", "write", true );
  24. #ifdef DEBUG_CSURK
  25. clog << "[log] SemSegCsurka::SemSegCsurka: OppenentSift implemenation: " << opSiftImpl << endl;
  26. #endif
  27. save_cache = conf->gB ( "FPCPixel", "save_cache", true );
  28. read_cache = conf->gB ( "FPCPixel", "read_cache", false );
  29. cache = conf->gS ( "cache", "root", "" );
  30. sigmaweight = conf->gD ( "SemSegCsurka", "sigmaweight", 0.6 );
  31. dim = conf->gI ( "SemSegCsurka", "pcadim", 50 );
  32. usepca = conf->gB ( "SemSegCsurka", "usepca", true );
  33. calcpca = conf->gB ( "SemSegCsurka", "calcpca", false );
  34. usegmm = conf->gB ( "SemSegCsurka", "usegmm", false );
  35. norm = conf->gB ( "SemSegCsurka", "normalize", false );
  36. usefisher = conf->gB ( "SemSegCsurka", "usefisher", false );
  37. dogmm = conf->gB ( "SemSegCsurka", "dogmm", false );
  38. gaussians = conf->gI ( "SemSegCsurka", "gaussians", 50 );
  39. usekmeans = conf->gB ( "SemSegCsurka", "usekmeans", false );
  40. kmeansfeat = conf->gI ( "SemSegCsurka", "kmeansfeat", 50 );
  41. kmeanshard = conf->gB ( "SemSegCsurka", "kmeanshard", false );
  42. cname = conf->gS ( "SemSegCsurka", "classifier", "RandomForests" );
  43. anteil = conf->gD ( "SemSegCsurka", "anteil", 1.0 );
  44. userellocprior = conf->gB ( "SemSegCsurka", "rellocfeat", false );
  45. bool usesrg = conf->gB ( "SemSegCsurka", "usesrg", false );
  46. useregions = conf->gB ( "SemSegCsurka", "useregions", true );
  47. savesteps = conf->gB ( "SemSegCsurka", "savesteps", true );
  48. bool usegcopt = conf->gB ( "SemSegCsurka", "usegcopt", false );
  49. bestclasses = conf->gI ( "SemSegCsurka", "bestclasses", 0 );
  50. smoothhl = conf->gB ( "SemSegCsurka", "smoothhl", false );
  51. smoothfactor = conf->gD ( "SemSegCsurka", "smoothfactor", 1.0 );
  52. usecolorfeats = conf->gB("SemSegCsurka", "usecolorfeats", false);
  53. string rsMethod = conf->gS("SemSegCsurka", "segmentation", "meanshift");
  54. g = NULL;
  55. k = NULL;
  56. relloc = NULL;
  57. srg = NULL;
  58. gcopt = NULL;
  59. if ( !useregions && ( userellocprior || usesrg ) )
  60. {
  61. cerr << "relative location priors and super region growing are just supported in combination with useregions" << endl;
  62. exit ( 1 );
  63. }
  64. if ( usepca )
  65. pca = PCA ( dim );
  66. RegionSegmentationMethod * tmpseg;
  67. if(rsMethod == "meanshift")
  68. tmpseg = new RSMeanShift ( conf );
  69. else
  70. tmpseg = new RSGraphBased(conf);
  71. if(save_cache)
  72. seg = new RSCache ( conf, tmpseg );
  73. else
  74. seg = tmpseg;
  75. if ( userellocprior )
  76. relloc = new RelativeLocationPrior ( conf );
  77. else
  78. relloc = NULL;
  79. if ( usesrg )
  80. srg = new PPSuperregion ( conf );
  81. else
  82. srg = NULL;
  83. if ( usegcopt )
  84. gcopt = new PPGraphCut ( conf );
  85. else
  86. gcopt = NULL;
  87. classifier = NULL;
  88. vclassifier = NULL;
  89. if ( cname == "RandomForests" )
  90. classifier = new FPCRandomForests ( conf, "ClassifierForest" );
  91. else if ( cname == "SMLR" )
  92. classifier = new FPCSMLR ( conf, "ClassifierSMLR" );
  93. else
  94. vclassifier = CSGeneric::selectVecClassifier ( conf, "main" );
  95. //classifier = new FPCSparseMultinomialLogisticRegression(conf, "ClassifierSMLR");
  96. if(classifier != NULL)
  97. classifier->setMaxClassNo ( classNames->getMaxClassno() );
  98. else
  99. vclassifier->setMaxClassNo ( classNames->getMaxClassno() );
  100. cn = md->getClassNames ( "train" );
  101. if ( read_cache )
  102. {
  103. fprintf ( stderr, "SemSegCsurka:: Reading classifier data from %s\n", ( cache+"/fpcrf.data" ).c_str() );
  104. if(classifier != NULL)
  105. classifier->read ( cache+"/fpcrf.data" );
  106. else
  107. vclassifier->read ( cache+"/veccl.data" );
  108. if ( usepca )
  109. {
  110. std::string filename = cache + "/pca";
  111. pca.read ( filename );
  112. }
  113. if ( usegmm )
  114. {
  115. g = new GMM ( conf, gaussians );
  116. if ( !g->loadData ( cache+"/gmm" ) )
  117. {
  118. cerr << "SemSegCsurka:: no gmm file found" << endl;
  119. exit ( -1 );
  120. }
  121. }
  122. else{ g = NULL; }
  123. if ( usekmeans )
  124. {
  125. k = new KMeansOnline ( gaussians );
  126. }
  127. fprintf ( stderr, "SemSegCsurka:: successfully read\n" );
  128. std::string filename = cache + "/rlp";
  129. FILE *value;
  130. value = fopen ( filename.c_str(),"r" );
  131. if ( value==NULL )
  132. {
  133. trainpostprocess ( md );
  134. }
  135. else
  136. {
  137. if ( userellocprior )
  138. {
  139. relloc->read ( filename );
  140. }
  141. }
  142. filename = cache + "/srg";
  143. value = fopen ( filename.c_str(),"r" );
  144. if ( value==NULL )
  145. {
  146. trainpostprocess ( md );
  147. }
  148. else
  149. {
  150. if ( srg != NULL )
  151. {
  152. srg->read ( filename );
  153. }
  154. }
  155. }
  156. else
  157. {
  158. train ( md );
  159. }
  160. }
  161. SemSegCsurka::~SemSegCsurka()
  162. {
  163. // clean-up
  164. if ( classifier != NULL )
  165. delete classifier;
  166. if( vclassifier !=NULL)
  167. delete vclassifier;
  168. if ( seg != NULL )
  169. delete seg;
  170. g = NULL;
  171. if ( g != NULL )
  172. delete g;
  173. }
  174. void SemSegCsurka::normalize(Examples &ex)
  175. {
  176. assert(ex.size() > 0);
  177. if(vecmin.size() == 0)
  178. {
  179. for(int j = 0; j < (int)ex[0].second.vec->size(); j++)
  180. {
  181. double maxv = -numeric_limits<int>::max();
  182. double minv = numeric_limits<int>::max();
  183. for(int i = 0; i < (int)ex.size(); i++)
  184. {
  185. maxv = std::max(maxv,(*ex[i].second.vec)[j]);
  186. minv = std::min(minv,(*ex[i].second.vec)[j]);
  187. }
  188. vecmin.push_back(minv);
  189. vecmax.push_back(maxv);
  190. }
  191. }
  192. for(int i = 0; i < (int)ex.size(); i++)
  193. {
  194. for(int j = 0; j < (int)ex[i].second.vec->size(); j++)
  195. {
  196. (*ex[i].second.vec)[j] = ((*ex[i].second.vec)[j]-vecmin[j])/(vecmax[j]-vecmin[j]);
  197. }
  198. }
  199. return;
  200. }
  201. void SemSegCsurka::convertLowToHigh ( Examples &ex, double reduce )
  202. {
  203. cout << "converting low-level features to high-level features" << endl;
  204. if ( reduce >= 1.0 )
  205. {
  206. for ( int i = 0; i < ( int ) ex.size(); i++ )
  207. {
  208. SparseVector *f = new SparseVector();
  209. if ( usekmeans )
  210. {
  211. k->getDist ( *ex[i].second.vec, *f, kmeansfeat, kmeanshard );
  212. }
  213. else
  214. {
  215. if ( usefisher )
  216. g->getFisher ( *ex[i].second.vec, *f );
  217. else
  218. g->getProbs ( *ex[i].second.vec, *f );
  219. }
  220. delete ex[i].second.vec;
  221. ex[i].second.vec = NULL;
  222. ex[i].second.svec = f;
  223. }
  224. }
  225. else
  226. {
  227. srand ( time ( NULL ) );
  228. vector<bool> del(ex.size(), false);
  229. cout << "Example size old " << ex.size() << endl;
  230. #pragma omp parallel for
  231. for ( int i = 0; i < ( int ) ex.size(); i++ )
  232. {
  233. double rval = ( double ) rand() / ( double ) RAND_MAX;
  234. if ( rval < reduce )
  235. {
  236. SparseVector *f = new SparseVector();
  237. if ( usekmeans )
  238. k->getDist ( *ex[i].second.vec, *f, kmeansfeat, kmeanshard );
  239. else
  240. {
  241. if ( usefisher )
  242. g->getFisher ( *ex[i].second.vec, *f );
  243. else
  244. g->getProbs ( *ex[i].second.vec, *f );
  245. }
  246. delete ex[i].second.vec;
  247. ex[i].second.vec = NULL;
  248. ex[i].second.svec = f;
  249. }
  250. else
  251. {
  252. del[i] = true;
  253. }
  254. }
  255. for ( int i = ( int ) del.size()-1; i >= 0; i-- )
  256. {
  257. if(del[i])
  258. {
  259. ex.erase ( ex.begin() +i);
  260. }
  261. }
  262. cerr << "Example size new " << ex.size() << endl;
  263. }
  264. cerr << "converting low-level features to high-level features finished" << endl;
  265. }
  266. void SemSegCsurka::smoothHL ( Examples ex )
  267. {
  268. if ( !smoothhl )
  269. return;
  270. assert ( ex.size() > 1 );
  271. long long int minx = numeric_limits<long long int>::max();
  272. long long int miny = numeric_limits<long long int>::max();
  273. long long int maxx = -numeric_limits<long long int>::max();
  274. long long int maxy = -numeric_limits<long long int>::max();
  275. long long int distx = numeric_limits<long long int>::max();
  276. long long int disty = numeric_limits<long long int>::max();
  277. set<double> scales;
  278. for ( int i = 0; i < (int)ex.size(); i++ )
  279. {
  280. scales.insert ( ex[i].second.scale );
  281. }
  282. map<double, int> scalepos;
  283. int it = 0;
  284. for ( set<double>::const_iterator iter = scales.begin(); iter != scales.end(); ++iter, ++it )
  285. {
  286. scalepos.insert(make_pair(*iter, it));
  287. }
  288. for ( int i = 0; i < (int)ex.size(); i++ )
  289. {
  290. if ( minx < numeric_limits<int>::max() && ex[i].second.x - minx > 0 )
  291. distx = std::min ( distx, ex[i].second.x - minx );
  292. if ( miny < numeric_limits<int>::max() && ex[i].second.y - miny > 0 )
  293. disty = std::min ( disty, ex[i].second.y - miny );
  294. minx = std::min ( (long long int)ex[i].second.x, minx );
  295. maxx = std::max ( (long long int)ex[i].second.x, maxx );
  296. miny = std::min ( (long long int)ex[i].second.y, miny );
  297. maxy = std::max ( (long long int)ex[i].second.y, maxy );
  298. }
  299. distx = abs ( distx );
  300. int xsize = ( maxx - minx ) /distx +1;
  301. int ysize = ( maxy - miny ) /disty +1;
  302. double valx = ( ( double ) xsize-1 ) / ( double ) ( maxx - minx );
  303. double valy = ( ( double ) ysize-1 ) / ( double ) ( maxy - miny );
  304. //double sigma = smoothfactor;
  305. double sigma = std::max(xsize,ysize) * smoothfactor;
  306. //double sigma = 0.2;
  307. cout << "sigma1: " << sigma << endl;
  308. vector<NICE::FloatImage> imgv;
  309. vector<NICE::FloatImage> gaussImgv;
  310. for(int i = 0; i < (int)scalepos.size(); i++)
  311. {
  312. NICE::FloatImage img( xsize, ysize);
  313. NICE::FloatImage gaussImg( xsize, ysize);
  314. imgv.push_back(img);
  315. gaussImgv.push_back(gaussImg);
  316. }
  317. for ( int d = 0; d < ex[0].second.svec->getDim(); d++ )
  318. {
  319. //TODO: max und min dynamisches bestimmen
  320. for(int i = 0; i < (int)scalepos.size(); i++)
  321. {
  322. imgv[i].set(0.0);
  323. gaussImgv[i].set(0.0);
  324. }
  325. for ( int i = 0; i < (int)ex.size(); i++ )
  326. {
  327. int xpos = ( ex[i].second.x - minx ) *valx;
  328. int ypos = ( ex[i].second.y - miny ) *valy;
  329. double val = ex[i].second.svec->get ( d );
  330. // refactor-nice.pl: check this substitution
  331. // old: PutValD ( imgv[scalepos[ex[i].second.scale]],xpos,ypos,val);
  332. imgv[scalepos[ex[i].second.scale]].setPixel(xpos,ypos,val);
  333. }
  334. /*
  335. for(int y = 0; y < ysize; y++)
  336. {
  337. for(int x = 0; x < xsize; x++)
  338. {
  339. // refactor-nice.pl: check this substitution
  340. // old: double val = GetValD(img,x,y);
  341. double val = img.getPixel(x,y);
  342. double c = 0.0;
  343. if(val == 0.0)
  344. {
  345. if(x > 0)
  346. {
  347. // refactor-nice.pl: check this substitution
  348. // old: val+=GetValD(img,x-1,y);
  349. val+=img.getPixel(x-1,y);
  350. c+=1.0;
  351. }
  352. if(y > 0)
  353. {
  354. // refactor-nice.pl: check this substitution
  355. // old: val+=GetValD(img,x,y-1);
  356. val+=img.getPixel(x,y-1);
  357. c+=1.0;
  358. }
  359. if(x < xsize-1)
  360. {
  361. // refactor-nice.pl: check this substitution
  362. // old: val+=GetValD(img,x+1,y);
  363. val+=img.getPixel(x+1,y);
  364. c+=1.0;
  365. }
  366. if(y < ysize-1)
  367. {
  368. // refactor-nice.pl: check this substitution
  369. // old: val+=GetValD(img,x,y+1);
  370. val+=img.getPixel(x,y+1);
  371. c+=1.0;
  372. }
  373. // refactor-nice.pl: check this substitution
  374. // old: PutValD(img,x,y,val/c);
  375. img.setPixel(x,y,val/c);
  376. }
  377. }
  378. }*/
  379. for(int i = 0; i < (int)imgv.size(); i++)
  380. filterGaussSigmaApproximate<float,float,float>( imgv[i], sigma, &gaussImgv[i] );
  381. for ( int i = 0; i < (int)ex.size(); i++ )
  382. {
  383. int xpos = ( ex[i].second.x - minx ) *valx;
  384. int ypos = ( ex[i].second.y - miny ) *valy;
  385. // refactor-nice.pl: check this substitution
  386. // old: double val = GetValD ( gaussImgv[scalepos[ex[i].second.scale]], xpos, ypos );
  387. double val = gaussImgv[scalepos[ex[i].second.scale]].getPixel(xpos,ypos);
  388. if ( fabs ( val ) < 1e-7 )
  389. {
  390. if ( ex[i].second.svec->get ( d ) != 0.0 )
  391. {
  392. ex[i].second.svec->erase ( d );
  393. }
  394. }
  395. else
  396. {
  397. ( *ex[i].second.svec ) [d] = val;
  398. }
  399. }
  400. }
  401. }
  402. void SemSegCsurka::initializePCA ( Examples &ex )
  403. {
  404. #ifdef DEBUG
  405. cerr << "start computing pca" << endl;
  406. #endif
  407. std::string filename = cache + "/pca";
  408. FILE *value;
  409. value = fopen ( filename.c_str(),"r" );
  410. if ( value==NULL || calcpca )
  411. {
  412. srand ( time ( NULL ) );
  413. int featsize = ( int ) ex.size();
  414. int maxfeatures = dim*10;
  415. int olddim = ex[0].second.vec->size();
  416. maxfeatures = std::min ( maxfeatures, featsize );
  417. NICE::Matrix features ( maxfeatures, olddim );
  418. for ( int i = 0; i < maxfeatures; i++ )
  419. {
  420. int k = rand() % featsize;
  421. int vsize = (int)ex[k].second.vec->size();
  422. for(int j = 0; j < vsize; j++)
  423. {
  424. features(i,j) = (*( ex[k].second.vec))[j];
  425. }
  426. }
  427. pca.calculateBasis ( features, dim, 1 );
  428. if ( save_cache )
  429. pca.save ( filename );
  430. }
  431. else
  432. {
  433. cout << "readpca: " << filename << endl;
  434. pca.read ( filename );
  435. cout << "end" << endl;
  436. }
  437. #ifdef DEBUG
  438. cerr << "finished computing pca" << endl;
  439. #endif
  440. }
  441. void SemSegCsurka::doPCA ( Examples &ex )
  442. {
  443. cout << "converting features using pca starts" << endl;
  444. std::string savedir = cname = conf->gS ( "cache", "root", "/dev/null/" );
  445. std::string shortf = ex.filename;
  446. if ( string::npos != ex.filename.rfind ( "/" ) )
  447. shortf = ex.filename.substr ( ex.filename.rfind ( "/" ) );
  448. std::string filename = savedir+"/pcasave/"+shortf;
  449. std::string syscall = "mkdir "+savedir+"/pcasave";
  450. system ( syscall.c_str() );
  451. cout << "filename: " << filename << endl;
  452. if ( !FileMgt::fileExists(filename) || calcpca )
  453. {
  454. ofstream ofStream;
  455. //Opens the file binary
  456. ofStream.open ( filename.c_str(),fstream::out | fstream::binary );
  457. for ( int k = 0; k < ( int ) ex.size(); k++ )
  458. {
  459. NICE::Vector tmp = pca.getFeatureVector ( * ( ex[k].second.vec ), true );
  460. delete ex[k].second.vec;
  461. for ( int d = 0; d < (int)tmp.size(); d++ )
  462. ofStream.write ( ( char* ) &tmp[d], sizeof ( double ) );
  463. ex[k].second.vec = new NICE::Vector ( tmp );
  464. }
  465. ofStream.close();
  466. cout << endl;
  467. }
  468. else
  469. {
  470. ifstream ifStream;
  471. ifStream.open ( filename.c_str(),std::fstream::in | std::fstream::binary );
  472. for ( int k = 0; k < ( int ) ex.size(); k++ )
  473. {
  474. NICE::Vector tmp = NICE::Vector ( dim );
  475. delete ex[k].second.vec;
  476. for ( int d = 0; d < dim; d++ )
  477. ifStream.read ( ( char* ) &tmp[d], sizeof ( double ) );
  478. ex[k].second.vec = new NICE::Vector ( tmp );
  479. }
  480. ifStream.close();
  481. }
  482. cout << "converting features using pca finished" << endl;
  483. }
  484. void SemSegCsurka::train ( const MultiDataset *md )
  485. {
  486. /*die einzelnen Trainingsschritte
  487. 1. auf allen Trainingsbilder SIFT Merkmale an den Gitterpunkten bei allen Auflösungen bestimmen
  488. 2. PCA anwenden
  489. 3. aus diesen ein GMM erstellen
  490. 4. für jedes SIFT-Merkmal einen Vektor erstellen, der an der Stelle i die Wahrscheinlichkeit enthällt zur Verteilung i des GMM, Zur Zeit mit BoV-Alternative durch Moosman06 erledigt
  491. 5. diese Vektoren in einem diskriminitativen Klassifikator ( z.B. SLR oder Randomized Forests) zusammen mit ihrer Klassenzugehörigkeit anlernen
  492. */
  493. #ifdef DEBUG
  494. cerr << "SemSegCsurka:: training starts" << endl;
  495. #endif
  496. Examples examples;
  497. examples.filename = "training";
  498. // Welche Opponentsift Implementierung soll genutzt werden ?
  499. LocalFeatureRepresentation *cSIFT = NULL;
  500. LocalFeatureRepresentation *writeFeats = NULL;
  501. LocalFeatureRepresentation *readFeats = NULL;
  502. LocalFeatureRepresentation *getFeats = NULL;
  503. if( opSiftImpl == "NICE" )
  504. {
  505. cSIFT = new LFonHSG( conf, "HSGtrain" );
  506. }
  507. else if( opSiftImpl == "VANDESANDE" )
  508. {
  509. // the used features
  510. cSIFT = new LFColorSande ( conf, "LFColorSandeTrain" );
  511. }
  512. else
  513. {
  514. fthrow(Exception, "feattype: %s not yet supported" << opSiftImpl );
  515. }
  516. getFeats = cSIFT;
  517. if(writefeat)
  518. {
  519. // write the features to a file, if there isn't any to read
  520. writeFeats = new LFWriteCache ( conf, cSIFT );
  521. getFeats = writeFeats;
  522. }
  523. if(readfeat)
  524. {
  525. // read the features from a file
  526. if(writefeat)
  527. {
  528. readFeats = new LFReadCache ( conf, writeFeats,-1 );
  529. }
  530. else
  531. {
  532. readFeats = new LFReadCache ( conf, cSIFT,-1 );
  533. }
  534. getFeats = readFeats;
  535. }
  536. // additional Colorfeatures
  537. LFColorWeijer lcw(conf);
  538. int lfdimension = -1;
  539. const LabeledSet train = * ( *md ) ["train"];
  540. const LabeledSet *trainp = &train;
  541. ////////////////////////
  542. // Merkmale berechnen //
  543. ////////////////////////
  544. set<int> forbidden_classes;
  545. std::string forbidden_classes_s = conf->gS ( "analysis", "donttrain", "" );
  546. if ( forbidden_classes_s == "" )
  547. {
  548. forbidden_classes_s = conf->gS ( "analysis", "forbidden_classes", "" );
  549. }
  550. cn.getSelection ( forbidden_classes_s, forbidden_classes );
  551. cerr << "forbidden: " << forbidden_classes_s << endl;
  552. ProgressBar pb ( "Local Feature Extraction" );
  553. pb.show();
  554. int imgnb = 0;
  555. LOOP_ALL_S ( *trainp )
  556. {
  557. //EACH_S(classno, currentFile);
  558. EACH_INFO ( classno,info );
  559. pb.update ( trainp->count() );
  560. NICE::ColorImage img;
  561. std::string currentFile = info.img();
  562. CachedExample *ce = new CachedExample ( currentFile );
  563. const LocalizationResult *locResult = info.localization();
  564. if ( locResult->size() <= 0 )
  565. {
  566. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  567. currentFile.c_str() );
  568. continue;
  569. }
  570. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n",
  571. currentFile.c_str() );
  572. int xsize, ysize;
  573. ce->getImageSize ( xsize, ysize );
  574. NICE::Image pixelLabels (xsize, ysize);
  575. pixelLabels.set(0);
  576. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  577. try {
  578. img = ColorImage(currentFile);
  579. } catch (Exception) {
  580. cerr << "SemSegCsurka: error opening image file <" << currentFile << ">" << endl;
  581. continue;
  582. }
  583. Globals::setCurrentImgFN ( currentFile );
  584. VVector features;
  585. VVector cfeatures;
  586. VVector positions;
  587. NICE::ColorImage cimg(currentFile);
  588. getFeats->extractFeatures ( img, features, positions );
  589. #ifdef DEBUG_CSURK
  590. cout << "[log] SemSegCsruka::train -> " << currentFile << " an " << positions.size() << " Positionen wurden Features (Anz = " << features.size() << ") " << endl; cout << "mit einer Dimension von " << features[ 0].size() << " extrahiert." << endl;
  591. #endif
  592. if(usecolorfeats)
  593. lcw.getDescriptors(cimg, cfeatures, positions);
  594. int j = 0;
  595. for ( VVector::const_iterator i = features.begin();
  596. i != features.end();
  597. i++,j++ )
  598. {
  599. const NICE::Vector & x = *i;
  600. classno = pixelLabels.getPixel(( int )positions[j][0], ( int )positions[j][1] );
  601. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  602. continue;
  603. if ( lfdimension < 0 )
  604. lfdimension = ( int ) x.size();
  605. else
  606. assert ( lfdimension == ( int ) x.size() );
  607. NICE::Vector *v = new NICE::Vector ( x );
  608. if(usecolorfeats && !usepca)
  609. v->append(cfeatures[j]);
  610. Example example ( v );
  611. example.position = imgnb;
  612. examples.push_back (
  613. pair<int, Example> ( classno, example ) );
  614. }
  615. features.clear();
  616. positions.clear();
  617. delete ce;
  618. imgnb++;
  619. }
  620. pb.hide();
  621. //////////////////
  622. // PCA anwenden //
  623. //////////////////
  624. if ( usepca )
  625. {
  626. if ( !read_cache )
  627. {
  628. initializePCA ( examples );
  629. }
  630. doPCA ( examples );
  631. lfdimension = dim;
  632. }
  633. /////////////////////////////////////////////////////
  634. // Low-Level Features in High-Level transformieren //
  635. /////////////////////////////////////////////////////
  636. int hlfdimension = lfdimension;
  637. if(norm)
  638. normalize(examples);
  639. if ( usegmm )
  640. {
  641. if(!usepca && !norm)
  642. normalize(examples);
  643. g = new GMM ( conf,gaussians );
  644. if ( dogmm || !g->loadData ( cache+"/gmm" ) )
  645. {
  646. g->computeMixture ( examples );
  647. if ( save_cache )
  648. g->saveData ( cache+"/gmm" );
  649. }
  650. hlfdimension = gaussians;
  651. if ( usefisher )
  652. hlfdimension = gaussians*2*dim;
  653. }
  654. if ( usekmeans )
  655. {
  656. if(!usepca || norm)
  657. normalize(examples);
  658. k = new KMeansOnline ( gaussians );
  659. k->cluster ( examples );
  660. hlfdimension = gaussians;
  661. }
  662. if ( usekmeans || usegmm )
  663. {
  664. examples.clear();
  665. pb.reset("Local Feature Extraction");
  666. lfdimension = -1;
  667. pb.update ( trainp->count() );
  668. LOOP_ALL_S ( *trainp )
  669. {
  670. EACH_INFO ( classno,info );
  671. pb.update ( trainp->count() );
  672. NICE::ColorImage img;
  673. std::string currentFile = info.img();
  674. CachedExample *ce = new CachedExample ( currentFile );
  675. const LocalizationResult *locResult = info.localization();
  676. if ( locResult->size() <= 0 )
  677. {
  678. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  679. currentFile.c_str() );
  680. continue;
  681. }
  682. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n",
  683. currentFile.c_str() );
  684. int xsize, ysize;
  685. ce->getImageSize ( xsize, ysize );
  686. NICE::Image pixelLabels (xsize, ysize);
  687. pixelLabels.set(0);
  688. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  689. try{
  690. img = ColorImage(currentFile);
  691. }
  692. catch (Exception){
  693. cerr << "SemSegCsurka: error opening image file <" << currentFile << ">" << endl;
  694. continue;
  695. }
  696. Globals::setCurrentImgFN ( currentFile );
  697. VVector features;
  698. VVector cfeatures;
  699. VVector positions;
  700. NICE::ColorImage cimg(currentFile);
  701. getFeats->extractFeatures ( img, features, positions );
  702. if(usecolorfeats)
  703. lcw.getDescriptors(cimg, cfeatures, positions);
  704. int j = 0;
  705. Examples tmpex;
  706. for ( VVector::const_iterator i = features.begin();
  707. i != features.end();
  708. i++,j++ )
  709. {
  710. const NICE::Vector & x = *i;
  711. classno = pixelLabels.getPixel(( int )positions[j][0], ( int )positions[j][1] );
  712. if ( forbidden_classes.find ( classno ) != forbidden_classes.end() )
  713. continue;
  714. if ( lfdimension < 0 )
  715. lfdimension = ( int ) x.size();
  716. else
  717. assert ( lfdimension == ( int ) x.size() );
  718. NICE::Vector *v = new NICE::Vector ( x );
  719. if(usecolorfeats)
  720. v->append(cfeatures[j]);
  721. Example example ( v );
  722. example.position = imgnb;
  723. example.x = ( int ) positions[j][0];
  724. example.y = ( int )positions[j][1];
  725. example.scale = positions[j][2];
  726. tmpex.push_back ( pair<int, Example> ( classno, example ) );
  727. }
  728. tmpex.filename = currentFile;
  729. if ( usepca )
  730. {
  731. doPCA ( tmpex );
  732. }
  733. convertLowToHigh ( tmpex, anteil );
  734. smoothHL ( tmpex );
  735. for ( int i = 0; i < (int)tmpex.size(); i++ )
  736. {
  737. examples.push_back ( pair<int, Example> ( tmpex[i].first, tmpex[i].second ) );
  738. }
  739. tmpex.clear();
  740. features.clear();
  741. positions.clear();
  742. delete ce;
  743. imgnb++;
  744. }
  745. pb.hide();
  746. }
  747. ////////////////////////////
  748. // Klassifikator anlernen //
  749. ////////////////////////////
  750. FeaturePool fp;
  751. Feature *f;
  752. if ( usegmm || usekmeans )
  753. f = new SparseVectorFeature ( hlfdimension );
  754. else
  755. f = new VectorFeature ( hlfdimension );
  756. f->explode ( fp );
  757. delete f;
  758. if(usecolorfeats && !( usekmeans || usegmm ))
  759. {
  760. int dimension = hlfdimension+11;
  761. for ( int i = hlfdimension ; i < dimension ; i++ )
  762. {
  763. VectorFeature *f = new VectorFeature ( dimension );
  764. f->feature_index = i;
  765. fp.addFeature(f, 1.0 / dimension);
  766. }
  767. }
  768. /*
  769. cout << "train classifier" << endl;
  770. fp.store(cout);
  771. getchar();
  772. for(int z = 0; z < examples.size(); z++)
  773. {
  774. cout << "examples.size() " << examples.size() << endl;
  775. cout << "class: " << examples[z].first << endl;
  776. cout << *examples[z].second.vec << endl;
  777. getchar();
  778. }*/
  779. if(classifier != NULL)
  780. classifier->train ( fp, examples );
  781. else
  782. {
  783. LabeledSetVector lvec;
  784. convertExamplesToLSet(examples, lvec);
  785. vclassifier->teach(lvec);
  786. if(usegmm)
  787. convertLSetToSparseExamples(examples, lvec);
  788. else
  789. convertLSetToExamples(examples, lvec);
  790. vclassifier->finishTeaching();
  791. }
  792. fp.destroy();
  793. if ( save_cache )
  794. {
  795. if(classifier != NULL)
  796. classifier->save ( cache+"/fpcrf.data" );
  797. else
  798. vclassifier->save ( cache+"/veccl.data" );
  799. }
  800. ////////////
  801. //clean up//
  802. ////////////
  803. for ( int i = 0; i < ( int ) examples.size(); i++ )
  804. {
  805. examples[i].second.clean();
  806. }
  807. examples.clear();
  808. if(cSIFT != NULL)
  809. delete cSIFT;
  810. if(writeFeats != NULL)
  811. delete writeFeats;
  812. if(readFeats != NULL)
  813. delete readFeats;
  814. getFeats = NULL;
  815. trainpostprocess ( md );
  816. cerr << "SemSeg training finished" << endl;
  817. }
  818. void SemSegCsurka::trainpostprocess ( const MultiDataset *md )
  819. {
  820. cout<< "start postprocess" << endl;
  821. ////////////////////////////
  822. // Postprocess trainieren //
  823. ////////////////////////////
  824. const LabeledSet train = * ( *md ) ["train"];
  825. const LabeledSet *trainp = &train;
  826. if ( userellocprior || srg != NULL || gcopt !=NULL )
  827. {
  828. clog << "[log] SemSegCsurka::trainpostprocess: if ( userellocprior || srg != NULL || gcopt !=NULL )" << endl;
  829. if ( userellocprior )
  830. relloc->setClassNo ( cn.numClasses() );
  831. if ( gcopt !=NULL )
  832. {
  833. gcopt->setClassNo ( cn.numClasses() );
  834. }
  835. ProgressBar pb ( "learn relative location prior maps" );
  836. pb.show();
  837. LOOP_ALL_S ( *trainp ) // für alle Bilder den ersten Klassifikationsschritt durchführen um den zweiten Klassifikator anzutrainieren
  838. {
  839. EACH_INFO ( classno,info );
  840. pb.update ( trainp->count() );
  841. NICE::ColorImage img;
  842. std::string currentFile = info.img();
  843. Globals::setCurrentImgFN ( currentFile );
  844. CachedExample *ce = new CachedExample ( currentFile );
  845. const LocalizationResult *locResult = info.localization();
  846. if ( locResult->size() <= 0 )
  847. {
  848. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  849. currentFile.c_str() );
  850. continue;
  851. }
  852. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n",
  853. currentFile.c_str() );
  854. int xsize, ysize;
  855. ce->getImageSize ( xsize, ysize );
  856. NICE::Image pixelLabels (xsize, ysize);
  857. pixelLabels.set(0);
  858. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  859. try{
  860. img = ColorImage(currentFile);
  861. }
  862. catch(Exception)
  863. {
  864. cerr << "SemSegCsurka: error opening image file <" << currentFile << ">" << endl;
  865. continue;
  866. }
  867. //Regionen ermitteln
  868. NICE::Matrix mask;
  869. int regionsize = seg->segRegions ( img, mask );
  870. #ifdef DEBUG_CSURK
  871. Image overlay(img.width(), img.height());
  872. double maxval = 0.0;
  873. for(int y = 0; y < img.height(); y++)
  874. {
  875. for(int x = 0; x < img.width(); x++)
  876. {
  877. int val = ((int)mask(x,y)+1)%256;
  878. overlay.setPixel(x,y,val);
  879. maxval = std::max(mask(x,y), maxval);
  880. }
  881. }
  882. cout << maxval << " different regions found" << endl;
  883. NICE::showImageOverlay ( img, overlay, "Segmentation Result" );
  884. #endif
  885. Examples regions;
  886. vector<vector<int> > hists;
  887. for ( int i = 0; i < regionsize; i++ )
  888. {
  889. Example tmp;
  890. regions.push_back ( pair<int, Example> ( 0, tmp ) );
  891. vector<int> hist ( cn.numClasses(), 0 );
  892. hists.push_back ( hist );
  893. }
  894. for ( int x = 0; x < xsize; x++ )
  895. {
  896. for ( int y = 0; y < ysize; y++ )
  897. {
  898. int numb = mask(x,y);
  899. regions[numb].second.x += x;
  900. regions[numb].second.y += y;
  901. regions[numb].second.weight += 1.0;
  902. hists[numb][pixelLabels.getPixel(x,y)]++;
  903. }
  904. }
  905. for ( int i = 0; i < regionsize; i++ )
  906. {
  907. regions[i].second.x /= ( int ) regions[i].second.weight;
  908. regions[i].second.y /= ( int ) regions[i].second.weight;
  909. int maxval = -numeric_limits<int>::max();
  910. int maxpos = -1;
  911. int secondpos = -1;
  912. for ( int k = 0; k < ( int ) hists[i].size(); k++ )
  913. {
  914. if ( maxval <hists[i][k] )
  915. {
  916. maxval = hists[i][k];
  917. secondpos = maxpos;
  918. maxpos = k;
  919. }
  920. }
  921. if ( cn.text ( maxpos ) == "various" )
  922. regions[i].first = secondpos;
  923. else
  924. regions[i].first = maxpos;
  925. }
  926. if ( userellocprior )
  927. relloc->trainPriorsMaps ( regions, xsize, ysize );
  928. if ( srg != NULL )
  929. srg->trainShape ( regions, mask );
  930. if ( gcopt !=NULL )
  931. gcopt->trainImage ( regions, mask );
  932. delete ce;
  933. }
  934. pb.hide();
  935. if ( userellocprior )
  936. relloc->finishPriorsMaps ( cn );
  937. if ( srg != NULL )
  938. srg->finishShape ( cn );
  939. if ( gcopt != NULL )
  940. gcopt->finishPP ( cn );
  941. }
  942. if ( userellocprior )
  943. {
  944. clog << "[log] SemSegCsurka::trainpostprocess: if ( userellocprior )" << endl;
  945. ProgressBar pb ( "learn relative location classifier" );
  946. pb.show();
  947. int nummer = 0;
  948. LOOP_ALL_S ( *trainp ) // für alle Bilder den ersten Klassifikationsschritt durchführen um den zweiten Klassifikator anzutrainieren
  949. {
  950. //EACH_S(classno, currentFile);
  951. EACH_INFO ( classno,info );
  952. nummer++;
  953. pb.update ( trainp->count() );
  954. NICE::Image img;
  955. std::string currentFile = info.img();
  956. CachedExample *ce = new CachedExample ( currentFile );
  957. const LocalizationResult *locResult = info.localization();
  958. if ( locResult->size() <= 0 )
  959. {
  960. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  961. currentFile.c_str() );
  962. continue;
  963. }
  964. fprintf ( stderr, "SemSegCsurka: Collecting pixel examples from localization info: %s\n",
  965. currentFile.c_str() );
  966. int xsize, ysize;
  967. ce->getImageSize ( xsize, ysize );
  968. NICE::Image pixelLabels (xsize, ysize);
  969. pixelLabels.set(0);
  970. locResult->calcLabeledImage ( pixelLabels, ( *classNames ).getBackgroundClass() );
  971. try{
  972. img = Preprocess::ReadImgAdv ( currentFile.c_str() );
  973. }
  974. catch(Exception)
  975. {
  976. cerr << "SemSegCsurka: error opening image file <" << currentFile << ">" << endl;
  977. continue;
  978. }
  979. Globals::setCurrentImgFN ( currentFile );
  980. NICE::Image segresult;
  981. GenericImage<double> probabilities ( xsize,ysize,classno,true );
  982. Examples regions;
  983. NICE::Matrix mask;
  984. if ( savesteps )
  985. {
  986. std::ostringstream s1;
  987. s1 << cache << "/rlpsave/" << nummer;
  988. std::string filename = s1.str();
  989. s1 << ".probs";
  990. std::string fn2 = s1.str();
  991. FILE *file;
  992. file = fopen ( filename.c_str(),"r" );
  993. if ( file==NULL )
  994. {
  995. //berechnen
  996. classifyregions ( ce, segresult, probabilities, regions, mask );
  997. //schreiben
  998. ofstream fout ( filename.c_str(), ios::app );
  999. fout << regions.size() << endl;
  1000. for ( int i = 0; i < ( int ) regions.size(); i++ )
  1001. {
  1002. regions[i].second.store ( fout );
  1003. fout << regions[i].first << endl;
  1004. }
  1005. fout.close();
  1006. probabilities.store ( fn2 );
  1007. }
  1008. else
  1009. {
  1010. //lesen
  1011. ifstream fin ( filename.c_str() );
  1012. int size;
  1013. fin >> size;
  1014. for ( int i = 0; i < size; i++ )
  1015. {
  1016. Example ex;
  1017. ex.restore ( fin );
  1018. int tmp;
  1019. fin >> tmp;
  1020. regions.push_back ( pair<int, Example> ( tmp, ex ) );
  1021. }
  1022. fin.close();
  1023. probabilities.restore ( fn2 );
  1024. }
  1025. }
  1026. else
  1027. {
  1028. classifyregions ( ce, segresult, probabilities, regions, mask );
  1029. }
  1030. relloc->trainClassifier ( regions, probabilities );
  1031. delete ce;
  1032. }
  1033. relloc->finishClassifier();
  1034. pb.hide();
  1035. relloc->save ( cache+"/rlp" );
  1036. }
  1037. cout << "finished postprocess" << endl;
  1038. }
  1039. void SemSegCsurka::classifyregions ( CachedExample *ce, NICE::Image & segresult, GenericImage<double> & probabilities, Examples &Regionen, NICE::Matrix & mask )
  1040. {
  1041. /* die einzelnen Testschritte:
  1042. 1.x auf dem Testbild alle SIFT Merkmale an den Gitterpunkten bei allen Auflösungen bestimmen
  1043. 2.x für jedes SIFT-Merkmal einen Vektor erstellen, der an der Stelle i die Wahrscheinlichkeit enthällt zur Verteilung i des GMM
  1044. 3.x diese Vektoren klassifizieren, so dass für jede Klasse die Wahrscheinlichkeit gespeichert wird
  1045. 4.x für jeden Pixel die Wahrscheinlichkeiten mitteln aus allen Patches, in denen der Pixel vorkommt
  1046. 5.x das Originalbild in homogene Bereiche segmentieren
  1047. 6.x die homogenen Bereiche bekommen die gemittelten Wahrscheinlichkeiten ihrer Pixel
  1048. 7. (einzelne Klassen mit einem globalen Klassifikator ausschließen)
  1049. 8.x jeder Pixel bekommt die Klasse seiner Region zugeordnet
  1050. */
  1051. clog << "[log] SemSegCsruka::classifyregions" << endl;
  1052. int xsize, ysize;
  1053. ce->getImageSize ( xsize, ysize );
  1054. probabilities.reInit ( xsize, ysize, classNames->getMaxClassno() +1, true/*allocMem*/ );
  1055. clog << "[log] SemSegCsruka::classifyregions: probabilities.numChannels = " << probabilities.numChannels << endl;
  1056. segresult.resize(xsize, ysize);
  1057. Examples pce;
  1058. // Welche Opponentsift Implementierung soll genutzt werden ?
  1059. LocalFeatureRepresentation *cSIFT = NULL;
  1060. LocalFeatureRepresentation *writeFeats = NULL;
  1061. LocalFeatureRepresentation *readFeats = NULL;
  1062. LocalFeatureRepresentation *getFeats = NULL;
  1063. if( opSiftImpl == "NICE" )
  1064. {
  1065. cSIFT = new LFonHSG( conf, "HSGtrain" );
  1066. }
  1067. else if( opSiftImpl == "VANDESANDE" )
  1068. {
  1069. // the used features
  1070. cSIFT = new LFColorSande ( conf, "LFColorSandeTrain" );
  1071. }
  1072. else
  1073. {
  1074. fthrow(Exception, "feattype: %s not yet supported" << opSiftImpl );
  1075. }
  1076. getFeats = cSIFT;
  1077. if(writefeat)
  1078. {
  1079. // write the features to a file, if there isn't any to read
  1080. writeFeats = new LFWriteCache ( conf, cSIFT );
  1081. getFeats = writeFeats;
  1082. }
  1083. if(readfeat)
  1084. {
  1085. // read the features from a file
  1086. if(writefeat)
  1087. {
  1088. readFeats = new LFReadCache ( conf, writeFeats,-1 );
  1089. }
  1090. else
  1091. {
  1092. readFeats = new LFReadCache ( conf, cSIFT,-1 );
  1093. }
  1094. getFeats = readFeats;
  1095. }
  1096. // additional Colorfeatures
  1097. LFColorWeijer lcw(conf);
  1098. NICE::ColorImage img;
  1099. std::string currentFile = Globals::getCurrentImgFN();
  1100. try
  1101. {
  1102. img = ColorImage(currentFile);
  1103. }
  1104. catch(Exception)
  1105. {
  1106. cerr << "SemSegCsurka: error opening image file <" << currentFile << ">" << endl;
  1107. }
  1108. VVector features;
  1109. VVector cfeatures;
  1110. VVector positions;
  1111. getFeats->extractFeatures ( img, features, positions );
  1112. if(usecolorfeats)
  1113. lcw.getDescriptors(img, cfeatures, positions);
  1114. set<double> scales;
  1115. int j = 0;
  1116. int lfdimension = -1;
  1117. for ( VVector::const_iterator i = features.begin();
  1118. i != features.end();
  1119. i++,j++ )
  1120. {
  1121. const NICE::Vector & x = *i;
  1122. if ( lfdimension < 0 ) lfdimension = ( int ) x.size();
  1123. else assert ( lfdimension == ( int ) x.size() );
  1124. NICE::Vector *v = new NICE::Vector ( x );
  1125. if(usecolorfeats)
  1126. v->append(cfeatures[j]);
  1127. Example tmp = Example ( v );
  1128. tmp.x = ( int )positions[j][0];
  1129. tmp.y = ( int ) positions[j][1];
  1130. tmp.width = ( int ) ( 16.0*positions[j][2] );
  1131. tmp.height = tmp.width;
  1132. tmp.scale = positions[j][2];
  1133. scales.insert ( positions[j][2] );
  1134. pce.push_back ( pair<int, Example> ( 0, tmp ) );
  1135. }
  1136. //////////////////
  1137. // PCA anwenden //
  1138. //////////////////
  1139. pce.filename = currentFile;
  1140. if ( usepca )
  1141. {
  1142. doPCA ( pce );
  1143. lfdimension = dim;
  1144. }
  1145. //////////////////
  1146. // BoV anwenden //
  1147. //////////////////
  1148. if(norm)
  1149. normalize(pce);
  1150. if ( usegmm || usekmeans )
  1151. {
  1152. if(!usepca && !norm)
  1153. normalize(pce);
  1154. convertLowToHigh ( pce );
  1155. smoothHL ( pce );
  1156. lfdimension = gaussians;
  1157. }
  1158. /////////////////////////////////////////
  1159. // Wahrscheinlichkeitskarten erstellen //
  1160. /////////////////////////////////////////
  1161. int klassen = probabilities.numChannels;
  1162. GenericImage<double> preMap ( xsize,ysize,klassen*scales.size(),true );
  1163. long int offset = 0;
  1164. // initialisieren
  1165. for ( int y = 0 ; y < ysize ; y++ )
  1166. for ( int x = 0 ; x < xsize ; x++,offset++ )
  1167. {
  1168. // alles zum Hintergrund machen
  1169. segresult.setPixel(x,y,0);
  1170. // Die Wahrscheinlichkeitsmaps auf 0 initialisieren
  1171. for ( int i = 0 ; i < ( int ) probabilities.numChannels; i++ )
  1172. {
  1173. probabilities.data[i][offset] = 0.0;
  1174. }
  1175. for ( int j = 0; j < ( int ) preMap.numChannels; j++ )
  1176. {
  1177. preMap.data[j][offset]=0.0;
  1178. }
  1179. }
  1180. // Die Wahrscheinlichkeitsmaps mit den einzelnen Wahrscheinlichkeiten je Skalierung füllen
  1181. int scalesize = scales.size();
  1182. // Globale Häufigkeiten akkumulieren
  1183. FullVector fV ( ( int ) probabilities.numChannels );
  1184. for ( int i = 0; i < fV.size(); i++ )
  1185. fV[i] = 0.0;
  1186. // read allowed classes
  1187. string cndir = conf->gS("SemSegCsurka", "cndir", "");
  1188. int classes = (int)probabilities.numChannels;
  1189. vector<int> useclass(classes,1);
  1190. std::vector< std::string > list;
  1191. StringTools::split (currentFile, '/', list);
  1192. string orgname = list.back();
  1193. if(cndir != "")
  1194. {
  1195. useclass = vector<int>(classes,0);
  1196. ifstream infile((cndir+"/"+orgname+".dat").c_str());
  1197. while(!infile.eof() && infile.good())
  1198. {
  1199. int tmp;
  1200. infile >> tmp;
  1201. if(tmp >= 0 && tmp < classes)
  1202. {
  1203. useclass[tmp] = 1;
  1204. }
  1205. }
  1206. }
  1207. if(classifier != NULL)
  1208. {
  1209. clog << "[log] SemSegCsruka::classifyregions: Wahrscheinlichkeitskarten erstellen: classifier != NULL" << endl;
  1210. #pragma omp parallel for
  1211. for ( int s = 0; s < scalesize; s++ )
  1212. {
  1213. #pragma omp parallel for
  1214. for ( int i = s; i < ( int ) pce.size(); i+=scalesize )
  1215. {
  1216. ClassificationResult r = classifier->classify ( pce[i].second );
  1217. for ( int j = 0 ; j < r.scores.size(); j++ )
  1218. {
  1219. if(useclass[j] == 0)
  1220. continue;
  1221. fV[j] += r.scores[j];
  1222. preMap.set ( pce[i].second.x,pce[i].second.y,r.scores[j],j+s*klassen );
  1223. }
  1224. }
  1225. }
  1226. }
  1227. else
  1228. {
  1229. //#pragma omp parallel for
  1230. for ( int s = 0; s < scalesize; s++ )
  1231. {
  1232. //#pragma omp parallel for
  1233. for ( int i = s; i < ( int ) pce.size(); i+=scalesize )
  1234. {
  1235. ClassificationResult r = vclassifier->classify ( *(pce[i].second.vec) );
  1236. for ( int j = 0 ; j < ( int ) r.scores.size(); j++ )
  1237. {
  1238. if(useclass[j] == 0)
  1239. continue;
  1240. fV[j] += r.scores[j];
  1241. preMap.set ( pce[i].second.x,pce[i].second.y,r.scores[j],j+s*klassen );
  1242. }
  1243. }
  1244. }
  1245. }
  1246. vector<double> scalesVec;
  1247. for ( set<double>::const_iterator iter = scales.begin();
  1248. iter != scales.end();
  1249. ++iter )
  1250. {
  1251. scalesVec.push_back ( *iter );
  1252. }
  1253. // Gaußfiltern
  1254. clog << "[log] SemSegCsruka::classifyregions: Wahrscheinlichkeitskarten erstellen -> Gaussfiltern" << endl;
  1255. for ( int s = 0; s < scalesize; s++ )
  1256. {
  1257. double sigma = sigmaweight*16.0*scalesVec[s];
  1258. cerr << "sigma: " << sigma << endl;
  1259. #pragma omp parallel for
  1260. for ( int i = 0; i < klassen; i++ )
  1261. {
  1262. int pos = i+s*klassen;
  1263. double maxval = preMap.data[pos][0];
  1264. double minval = preMap.data[pos][0];
  1265. for ( int z = 1; z < xsize*ysize; z++ )
  1266. {
  1267. maxval = std::max ( maxval, preMap.data[pos][z] );
  1268. minval = std::min ( minval, preMap.data[pos][z] );
  1269. }
  1270. NICE::FloatImage dblImg( xsize, ysize);
  1271. NICE::FloatImage gaussImg( xsize, ysize);
  1272. long int offset2 = 0;
  1273. for ( int y = 0; y < ysize; y++ )
  1274. {
  1275. for ( int x = 0; x < xsize; x++, offset2++ )
  1276. {
  1277. dblImg.setPixel(x,y,preMap.data[pos][offset2]);
  1278. }
  1279. }
  1280. filterGaussSigmaApproximate<float,float,float>( dblImg, sigma, &gaussImg );
  1281. offset2 = 0;
  1282. for ( int y = 0; y < ysize; y++ )
  1283. {
  1284. for ( int x = 0; x < xsize; x++, offset2++ )
  1285. {
  1286. preMap.data[pos][offset2]=gaussImg.getPixel(x,y);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. // Zusammenfassen und auswerten
  1292. clog << "[log] SemSegCsruka::classifyregions: Wahrscheinlichkeitskarten erstellen -> zusammenfassen und auswerten" << endl;
  1293. #pragma omp parallel for
  1294. for ( int x = 0; x < xsize; x++ )
  1295. {
  1296. for ( int y = 0; y < ysize; y++ )
  1297. {
  1298. for ( int j = 0 ; j < ( int ) probabilities.numChannels; j++ )
  1299. {
  1300. double prob = 0.0;
  1301. for ( int s = 0; s < ( int ) scalesize; s++ )
  1302. {
  1303. prob+=preMap.get ( x,y,j+s*klassen );
  1304. }
  1305. double val = prob / ( double ) ( scalesize );
  1306. probabilities.set ( x,y,val, j );
  1307. }
  1308. }
  1309. }
  1310. #undef VISSEMSEG
  1311. #ifdef VISSEMSEG
  1312. std::string s;
  1313. std::stringstream out;
  1314. std::vector< std::string > list;
  1315. StringTools::split (Globals::getCurrentImgFN (), '/', list);
  1316. out << "probmaps/" << list.back() << ".probs";
  1317. s = out.str();
  1318. probabilities.store(s);s
  1319. for ( int j = 0 ; j < ( int ) probabilities.numChannels; j++ )
  1320. {
  1321. cout << "klasse: " << j << endl;//" " << cn.text ( j ) << endl;
  1322. NICE::Matrix tmp ( probabilities.ysize, probabilities.xsize );
  1323. double maxval = 0.0;
  1324. for ( int y = 0; y < probabilities.ysize; y++ )
  1325. for ( int x = 0; x < probabilities.xsize; x++ )
  1326. {
  1327. double val = probabilities.get ( x,y,j );
  1328. tmp(y, x) = val;
  1329. maxval = std::max ( val, maxval );
  1330. }
  1331. NICE::ColorImage imgrgb (probabilities.xsize, probabilities.ysize);
  1332. ICETools::convertToRGB ( tmp, imgrgb );
  1333. cout << "maxval = " << maxval << " for class " << j << endl; //cn.text ( j ) << endl;
  1334. //Show ( ON, imgrgb, cn.text ( j ) );
  1335. //showImage(imgrgb, "Ergebnis");
  1336. std::string s;
  1337. std::stringstream out;
  1338. out << "tmp" << j << ".ppm";
  1339. s = out.str();
  1340. imgrgb.writePPM( s );
  1341. //getchar();
  1342. }
  1343. #endif
  1344. if ( useregions )
  1345. {
  1346. if ( bestclasses > 0 )
  1347. {
  1348. PSSImageLevelPrior pss ( 0, bestclasses, 0.2 );
  1349. pss.setPrior ( fV );
  1350. pss.postprocess ( segresult, probabilities );
  1351. }
  1352. //Regionen ermitteln
  1353. int regionsize = seg->segRegions ( img, mask);
  1354. Regionen.clear();
  1355. vector<vector <double> > regionprob;
  1356. // Wahrscheinlichkeiten für jede Region initialisieren
  1357. for ( int i = 0; i < regionsize; i++ )
  1358. {
  1359. vector<double> tmp;
  1360. for ( int j = 0; j < ( int ) probabilities.numChannels; j++ )
  1361. {
  1362. tmp.push_back ( 0.0 );
  1363. }
  1364. regionprob.push_back ( tmp );
  1365. Regionen.push_back ( pair<int, Example> ( 0, Example() ) );
  1366. }
  1367. // Wahrscheinlichkeiten für Regionen bestimmen
  1368. for ( int x = 0; x < xsize; x++ )
  1369. {
  1370. for ( int y = 0; y < ysize; y++ )
  1371. {
  1372. for ( int j = 0 ; j < ( int ) probabilities.numChannels; j++ )
  1373. {
  1374. double val = probabilities.get ( x,y,j );
  1375. int pos = mask(x,y);
  1376. Regionen[pos].second.weight+=1.0;
  1377. Regionen[pos].second.x += x;
  1378. Regionen[pos].second.y += y;
  1379. regionprob[pos][j] += val;
  1380. }
  1381. }
  1382. }
  1383. /*
  1384. cout << "regions: " << regionsize << endl;
  1385. cout << "outfeats: " << endl;
  1386. for(int j = 0; j < regionprob.size(); j++)
  1387. {
  1388. for(int i = 0; i < regionprob[j].size(); i++)
  1389. {
  1390. cout << regionprob[j][i] << " ";
  1391. }
  1392. cout << endl;
  1393. }
  1394. cout << endl;
  1395. getchar();*/
  1396. // beste Wahrscheinlichkeit je Region wählen
  1397. for ( int i = 0; i < regionsize; i++ )
  1398. {
  1399. if(Regionen[i].second.weight > 0)
  1400. {
  1401. Regionen[i].second.x /= ( int ) Regionen[i].second.weight;
  1402. Regionen[i].second.y /= ( int ) Regionen[i].second.weight;
  1403. }
  1404. double maxval = 0.0;
  1405. int maxpos = 0;
  1406. for ( int j = 0 ; j < ( int ) regionprob[i].size(); j++ )
  1407. {
  1408. regionprob[i][j] /= Regionen[i].second.weight;
  1409. if ( maxval < regionprob[i][j] )
  1410. {
  1411. maxval = regionprob[i][j];
  1412. maxpos = j;
  1413. }
  1414. probabilities.set (Regionen[i].second.x,Regionen[i].second.y,regionprob[i][j], j );
  1415. }
  1416. Regionen[i].first = maxpos;
  1417. }
  1418. // Pixel jeder Region labeln
  1419. for ( int y = 0; y < (int)mask.cols(); y++ )
  1420. {
  1421. for ( int x = 0; x < (int)mask.rows(); x++ )
  1422. {
  1423. int pos = mask(x,y);
  1424. segresult.setPixel(x,y,Regionen[pos].first);
  1425. }
  1426. }
  1427. #define WRITEREGIONS
  1428. #ifdef WRITEREGIONS
  1429. RegionGraph rg;
  1430. seg->getGraphRepresentation(img, mask, rg);
  1431. for(uint pos = 0; pos < regionprob.size(); pos++)
  1432. {
  1433. rg[pos]->setProbs(regionprob[pos]);
  1434. }
  1435. std::string s;
  1436. std::stringstream out;
  1437. std::vector< std::string > list;
  1438. StringTools::split (Globals::getCurrentImgFN (), '/', list);
  1439. out << "rgout/" << list.back() << ".graph";
  1440. string writefile = out.str();
  1441. rg.write(writefile);
  1442. #endif
  1443. }
  1444. else
  1445. {
  1446. PSSImageLevelPrior pss ( 1, 4, 0.2 );
  1447. pss.setPrior ( fV );
  1448. pss.postprocess ( segresult, probabilities );
  1449. }
  1450. // Saubermachen:
  1451. clog << "[log] SemSegCsurka::classifyregions: sauber machen" << endl;
  1452. for ( int i = 0; i < ( int ) pce.size(); i++ )
  1453. {
  1454. pce[i].second.clean();
  1455. }
  1456. pce.clear();
  1457. if(cSIFT != NULL)
  1458. delete cSIFT;
  1459. if(writeFeats != NULL)
  1460. delete writeFeats;
  1461. if(readFeats != NULL)
  1462. delete readFeats;
  1463. getFeats = NULL;
  1464. }
  1465. void SemSegCsurka::semanticseg ( CachedExample *ce,
  1466. NICE::Image & segresult,
  1467. GenericImage<double> & probabilities )
  1468. {
  1469. Examples regions;
  1470. NICE::Matrix regionmask;
  1471. classifyregions ( ce, segresult, probabilities, regions, regionmask );
  1472. if ( userellocprior || srg != NULL || gcopt !=NULL )
  1473. {
  1474. if ( userellocprior )
  1475. relloc->postprocess ( regions, probabilities );
  1476. if ( srg != NULL )
  1477. srg->optimizeShape ( regions, regionmask, probabilities );
  1478. if ( gcopt != NULL )
  1479. gcopt->optimizeImage ( regions, regionmask, probabilities );
  1480. // Pixel jeder Region labeln
  1481. for ( int y = 0; y < (int)regionmask.cols(); y++ )
  1482. {
  1483. for ( int x = 0; x < (int)regionmask.rows(); x++ )
  1484. {
  1485. int pos = regionmask(x,y);
  1486. segresult.setPixel(x,y,regions[pos].first);
  1487. }
  1488. }
  1489. }
  1490. #ifndef NOVISUAL
  1491. #undef VISSEMSEG
  1492. #ifdef VISSEMSEG
  1493. // showImage(img);
  1494. for ( int j = 0 ; j < ( int ) probabilities.numChannels; j++ )
  1495. {
  1496. cout << "klasse: " << j << " " << cn.text ( j ) << endl;
  1497. NICE::Matrix tmp ( probabilities.ysize, probabilities.xsize );
  1498. double maxval = 0.0;
  1499. for ( int y = 0; y < probabilities.ysize; y++ )
  1500. for ( int x = 0; x < probabilities.xsize; x++ )
  1501. {
  1502. double val = probabilities.get ( x,y,j );
  1503. tmp(y, x) = val;
  1504. maxval = std::max ( val, maxval );
  1505. }
  1506. NICE::ColorImage imgrgb (probabilities.xsize, probabilities.ysize);
  1507. ICETools::convertToRGB ( tmp, imgrgb );
  1508. cout << "maxval = " << maxval << " for class " << cn.text ( j ) << endl;
  1509. Show ( ON, imgrgb, cn.text ( j ) );
  1510. imgrgb.Write ( "tmp.ppm" );
  1511. getchar();
  1512. }
  1513. #endif
  1514. #endif
  1515. }