SemSegCsurka.cpp 44 KB

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