SemSegCsurka.cpp 44 KB

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