SemSegCsurka.cpp 49 KB

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