SemSegCsurka.cpp 44 KB

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