SemSegCsurka.cpp 48 KB

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