SemSegNovelty.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. #include <sstream>
  2. #include <iostream>
  3. #include "core/image/FilterT.h"
  4. #include "core/basics/numerictools.h"
  5. #include "core/basics/StringTools.h"
  6. #include "core/basics/Timer.h"
  7. #include "gp-hik-exp/GPHIKClassifierNICE.h"
  8. #include "vislearning/baselib/ICETools.h"
  9. #include "vislearning/baselib/Globals.h"
  10. #include "vislearning/features/fpfeatures/SparseVectorFeature.h"
  11. #include "segmentation/GenericRegionSegmentationMethodSelection.h"
  12. #include "SemSegNovelty.h"
  13. using namespace std;
  14. using namespace NICE;
  15. using namespace OBJREC;
  16. SemSegNovelty::SemSegNovelty ( )
  17. : SemanticSegmentation ( )
  18. {
  19. this->forbidden_classesTrain.clear();
  20. this->forbidden_classesActiveLearning.clear();
  21. this->classesInUse.clear();
  22. this->globalMaxUncert = -numeric_limits<double>::max();
  23. //we don't have queried any region so far
  24. this->queriedRegions.clear();
  25. this->featExtract = new LocalFeatureColorWeijer ();
  26. // those two guys need to be NULL, since only one of them will be active later on
  27. this->classifier = NULL;
  28. this->vclassifier = NULL;
  29. // this one here as well
  30. this->regionSeg = NULL;
  31. }
  32. SemSegNovelty::SemSegNovelty ( const Config * _conf,
  33. const MultiDataset *md )
  34. {
  35. ///////////
  36. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  37. ///////////
  38. this->forbidden_classesTrain.clear();
  39. this->forbidden_classesActiveLearning.clear();
  40. this->classesInUse.clear();
  41. this->globalMaxUncert = -numeric_limits<double>::max();
  42. //we don't have queried any region so far
  43. this->queriedRegions.clear();
  44. this->featExtract = new LocalFeatureColorWeijer ();
  45. // those two guys need to be NULL, since only one of them will be active later on
  46. this->classifier = NULL;
  47. this->vclassifier = NULL;
  48. // this one here as well
  49. this->regionSeg = NULL;
  50. ///////////
  51. // here comes the new code part different from the empty constructor
  52. ///////////
  53. this->setClassNames ( & ( md->getClassNames ( "train" ) ) );
  54. this->initFromConfig( _conf );
  55. }
  56. SemSegNovelty::~SemSegNovelty()
  57. {
  58. if(newTrainExamples.size() > 0)
  59. {
  60. // show most uncertain region
  61. if (b_visualizeALimages)
  62. showImage(maskedImg);
  63. //incorporate new information into the classifier
  64. if (classifier != NULL)
  65. {
  66. //NOTE dangerous!
  67. classifier->addMultipleExamples(newTrainExamples);
  68. }
  69. //store the classifier, such that we can read it again in the next round (if we like that)
  70. classifier->save ( cache + "/classifier.data" );
  71. }
  72. // clean-up
  73. ///////////////////////////////
  74. // FEATURE EXTRACTION //
  75. ///////////////////////////////
  76. if ( featExtract != NULL )
  77. delete featExtract;
  78. ///////////////////////////////
  79. // CLASSIFICATION STUFF //
  80. ///////////////////////////////
  81. if ( classifier != NULL )
  82. delete classifier;
  83. if ( vclassifier != NULL )
  84. delete vclassifier;
  85. ///////////////////////////////
  86. // SEGMENTATION STUFF //
  87. ///////////////////////////////
  88. if ( this->regionSeg != NULL )
  89. delete this->regionSeg;
  90. }
  91. void SemSegNovelty::initFromConfig(const Config* conf, const string _confSection)
  92. {
  93. //first of all, call method of parent object
  94. SemanticSegmentation::initFromConfig( conf );
  95. featExtract->initFromConfig ( conf );
  96. //save and read segmentation results from files
  97. this->reuseSegmentation = conf->gB ( "FPCPixel", "reuseSegmentation", true );
  98. //save the classifier to a file
  99. this->save_classifier = conf->gB ( "FPCPixel", "save_classifier", true );
  100. //read the classifier from a file
  101. this->read_classifier = conf->gB ( "FPCPixel", "read_classifier", false );
  102. //write uncertainty results in the same folder as done for the segmentation results
  103. resultdir = conf->gS("debug", "resultdir", "result");
  104. cache = conf->gS ( "cache", "root", "" );
  105. cache = conf->getAbsoluteFilenameRelativeToThisConfig(cache);
  106. this->findMaximumUncert = conf->gB(_confSection, "findMaximumUncert", true);
  107. this->whs = conf->gI ( _confSection, "window_size", 10 );
  108. //distance to next descriptor during training
  109. this->trainWSize = conf->gI ( _confSection, "train_window_size", 10 );
  110. //distance to next descriptor during testing
  111. this->testWSize = conf->gI (_confSection, "test_window_size", 10);
  112. // select your segmentation method here
  113. this->s_rsMethode = conf->gS ( _confSection, "segmentation", "none" );
  114. if( this->s_rsMethode == "none" )
  115. {
  116. regionSeg = NULL;
  117. }
  118. else
  119. {
  120. RegionSegmentationMethod *tmpRegionSeg = GenericRegionSegmentationMethodSelection::selectRegionSegmentationMethod( conf, this->s_rsMethode );
  121. if ( reuseSegmentation )
  122. regionSeg = new RSCache ( conf, tmpRegionSeg );
  123. else
  124. regionSeg = tmpRegionSeg;
  125. }
  126. //define which measure for "novelty" we want to use
  127. noveltyMethodString = conf->gS( _confSection, "noveltyMethod", "gp-variance");
  128. if (noveltyMethodString.compare("gp-variance") == 0) // novel = large variance
  129. {
  130. this->noveltyMethod = GPVARIANCE;
  131. this->mostNoveltyWithMaxScores = true;
  132. }
  133. else if (noveltyMethodString.compare("gp-uncertainty") == 0) //novel = large uncertainty (mean / var)
  134. {
  135. this->noveltyMethod = GPUNCERTAINTY;
  136. this->mostNoveltyWithMaxScores = false;
  137. globalMaxUncert = numeric_limits<double>::max();
  138. }
  139. else if (noveltyMethodString.compare("gp-mean") == 0) //novel = small mean
  140. {
  141. this->noveltyMethod = GPMINMEAN;
  142. this->mostNoveltyWithMaxScores = false;
  143. globalMaxUncert = numeric_limits<double>::max();
  144. }
  145. else if (noveltyMethodString.compare("gp-meanRatio") == 0) //novel = small difference between mean of most plausible class and mean of snd
  146. // most plausible class (not useful in binary settings)
  147. {
  148. this->noveltyMethod = GPMEANRATIO;
  149. this->mostNoveltyWithMaxScores = false;
  150. globalMaxUncert = numeric_limits<double>::max();
  151. }
  152. else if (noveltyMethodString.compare("gp-weightAll") == 0) // novel = large weight in alpha vector after updating the model (can be predicted exactly)
  153. {
  154. this->noveltyMethod = GPWEIGHTALL;
  155. this->mostNoveltyWithMaxScores = true;
  156. }
  157. else if (noveltyMethodString.compare("gp-weightRatio") == 0) // novel = small difference between weights for alpha vectors
  158. // with assumptions of GT label to be the most
  159. // plausible against the second most plausible class
  160. {
  161. this->noveltyMethod = GPWEIGHTRATIO;
  162. this->mostNoveltyWithMaxScores = false;
  163. globalMaxUncert = numeric_limits<double>::max();
  164. }
  165. else if (noveltyMethodString.compare("random") == 0)
  166. {
  167. initRand();
  168. this->noveltyMethod = RANDOM;
  169. }
  170. else
  171. {
  172. this->noveltyMethod = GPVARIANCE;
  173. this->mostNoveltyWithMaxScores = true;
  174. }
  175. b_visualizeALimages = conf->gB(_confSection, "visualizeALimages", false);
  176. classifierString = conf->gS ( _confSection, "classifier", "GPHIKClassifier" );
  177. classifier = NULL;
  178. vclassifier = NULL;
  179. if ( classifierString.compare("GPHIKClassifier") == 0)
  180. {
  181. //just to make sure, that we do NOT perform an optimization after every iteration step
  182. //this would just take a lot of time, which is not desired so far
  183. //TODO edit this!
  184. //this->conf->sB( "GPHIKClassifier", "performOptimizationAfterIncrement", false );
  185. classifier = new GPHIKClassifierNICE ( conf, "GPHIKClassifier" );
  186. }
  187. else
  188. vclassifier = GenericClassifierSelection::selectVecClassifier ( conf, classifierString );
  189. //check the same thing for the training classes - this is very specific to our setup
  190. std::string forbidden_classesTrain_s = conf->gS ( "analysis", "donttrainTrain", "" );
  191. if ( forbidden_classesTrain_s == "" )
  192. {
  193. forbidden_classesTrain_s = conf->gS ( "analysis", "forbidden_classesTrain", "" );
  194. }
  195. this->classNames->getSelection ( forbidden_classesTrain_s, forbidden_classesTrain );
  196. }
  197. void SemSegNovelty::visualizeRegion(const NICE::ColorImage &img, const NICE::Matrix &regions, int region, NICE::ColorImage &outimage)
  198. {
  199. std::vector<uchar> color;
  200. color.push_back(255);
  201. color.push_back(0);
  202. color.push_back(0);
  203. int width = img.width();
  204. int height = img.height();
  205. outimage.resize(width,height);
  206. for(int y = 0; y < height; y++)
  207. {
  208. for(int x = 0; x < width; x++)
  209. {
  210. if(regions(x,y) == region)
  211. {
  212. for(int c = 0; c < 3; c++)
  213. {
  214. outimage(x,y,c) = color[c];
  215. }
  216. }
  217. else
  218. {
  219. for(int c = 0; c < 3; c++)
  220. {
  221. outimage(x,y,c) = img(x,y,c);
  222. }
  223. }
  224. }
  225. }
  226. }
  227. void SemSegNovelty::train ( const MultiDataset *md )
  228. {
  229. if ( this->read_classifier )
  230. {
  231. try
  232. {
  233. if ( this->classifier != NULL )
  234. {
  235. string classifierdst = "/classifier.data";
  236. fprintf ( stderr, "SemSegNovelty:: Reading classifier data from %s\n", ( cache + classifierdst ).c_str() );
  237. classifier->read ( cache + classifierdst );
  238. }
  239. else
  240. {
  241. string classifierdst = "/veccl.data";
  242. fprintf ( stderr, "SemSegNovelty:: Reading classifier data from %s\n", ( cache + classifierdst ).c_str() );
  243. vclassifier->read ( cache + classifierdst );
  244. }
  245. fprintf ( stderr, "SemSegNovelty:: successfully read\n" );
  246. }
  247. catch ( char *str )
  248. {
  249. cerr << "error reading data: " << str << endl;
  250. }
  251. }
  252. else
  253. {
  254. const LabeledSet train = * ( *md ) ["train"];
  255. const LabeledSet *trainp = &train;
  256. ////////////////////////
  257. // feature extraction //
  258. ////////////////////////
  259. ProgressBar pb ( "Local Feature Extraction" );
  260. pb.show();
  261. int imgnb = 0;
  262. Examples examples;
  263. examples.filename = "training";
  264. int featdim = -1;
  265. classesInUse.clear();
  266. LOOP_ALL_S ( *trainp )
  267. {
  268. //EACH_S(classno, currentFile);
  269. EACH_INFO ( classno, info );
  270. std::string currentFile = info.img();
  271. CachedExample *ce = new CachedExample ( currentFile );
  272. const LocalizationResult *locResult = info.localization();
  273. if ( locResult->size() <= 0 )
  274. {
  275. fprintf ( stderr, "WARNING: NO ground truth polygons found for %s !\n",
  276. currentFile.c_str() );
  277. continue;
  278. }
  279. int xsize, ysize;
  280. ce->getImageSize ( xsize, ysize );
  281. Image labels ( xsize, ysize );
  282. labels.set ( 0 );
  283. locResult->calcLabeledImage ( labels, ( *classNames ).getBackgroundClass() );
  284. NICE::ColorImage img;
  285. try {
  286. img = ColorImage ( currentFile );
  287. } catch ( Exception ) {
  288. cerr << "SemSegNovelty: error opening image file <" << currentFile << ">" << endl;
  289. continue;
  290. }
  291. Globals::setCurrentImgFN ( currentFile );
  292. MultiChannelImageT<double> feats;
  293. // extract features
  294. featExtract->getFeats ( img, feats );
  295. featdim = feats.channels();
  296. feats.addChannel(featdim);
  297. for (int c = 0; c < featdim; c++)
  298. {
  299. ImageT<double> tmp = feats[c];
  300. ImageT<double> tmp2 = feats[c+featdim];
  301. NICE::FilterT<double, double, double>::gradientStrength (tmp, tmp2);
  302. }
  303. featdim += featdim;
  304. // compute integral images
  305. for ( int c = 0; c < featdim; c++ )
  306. {
  307. feats.calcIntegral ( c );
  308. }
  309. for ( int y = 0; y < ysize; y += trainWSize)
  310. {
  311. for ( int x = 0; x < xsize; x += trainWSize )
  312. {
  313. int classnoTmp = labels.getPixel ( x, y );
  314. if ( forbidden_classesTrain.find ( classnoTmp ) != forbidden_classesTrain.end() )
  315. {
  316. continue;
  317. }
  318. if (classesInUse.find(classnoTmp) == classesInUse.end())
  319. {
  320. classesInUse.insert(classnoTmp);
  321. }
  322. Example example;
  323. example.vec = NULL;
  324. example.svec = new SparseVector ( featdim );
  325. for ( int f = 0; f < featdim; f++ )
  326. {
  327. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  328. if ( val > 1e-10 )
  329. ( *example.svec ) [f] = val;
  330. }
  331. example.svec->normalize();
  332. example.position = imgnb;
  333. examples.push_back ( pair<int, Example> ( classnoTmp, example ) );
  334. }
  335. }
  336. delete ce;
  337. imgnb++;
  338. pb.update ( trainp->count() );
  339. }
  340. numberOfClasses = classesInUse.size();
  341. std::cerr << "numberOfClasses: " << numberOfClasses << std::endl;
  342. std::cerr << "classes in use: " << std::endl;
  343. for (std::set<int>::const_iterator it = classesInUse.begin(); it != classesInUse.end(); it++)
  344. {
  345. std::cerr << *it << " ";
  346. }
  347. std::cerr << std::endl;
  348. pb.hide();
  349. //////////////////////
  350. // train classifier //
  351. //////////////////////
  352. FeaturePool fp;
  353. Feature *f = new SparseVectorFeature ( featdim );
  354. f->explode ( fp );
  355. delete f;
  356. if ( classifier != NULL )
  357. {
  358. std::cerr << "train FP-classifier with " << examples.size() << " examples" << std::endl;
  359. classifier->train ( fp, examples );
  360. std::cerr << "training finished" << std::endl;
  361. }
  362. else
  363. {
  364. LabeledSetVector lvec;
  365. convertExamplesToLSet ( examples, lvec );
  366. vclassifier->teach ( lvec );
  367. // if ( usegmm )
  368. // convertLSetToSparseExamples ( examples, lvec );
  369. // else
  370. std::cerr << "classifierString: " << classifierString << std::endl;
  371. if (this->classifierString.compare("nn") == 0)
  372. {
  373. convertLSetToExamples ( examples, lvec, true /* only remove pointers to the data in the LSet-struct*/);
  374. }
  375. else
  376. {
  377. convertLSetToExamples ( examples, lvec, false /* remove all training examples of the LSet-struct */);
  378. }
  379. vclassifier->finishTeaching();
  380. }
  381. fp.destroy();
  382. if ( save_classifier )
  383. {
  384. if ( classifier != NULL )
  385. classifier->save ( cache + "/classifier.data" );
  386. else
  387. vclassifier->save ( cache + "/veccl.data" );
  388. }
  389. ////////////
  390. //clean up//
  391. ////////////
  392. for ( int i = 0; i < ( int ) examples.size(); i++ )
  393. {
  394. examples[i].second.clean();
  395. }
  396. examples.clear();
  397. cerr << "SemSeg training finished" << endl;
  398. }
  399. }
  400. void SemSegNovelty::semanticseg ( CachedExample *ce, NICE::Image & segresult, NICE::MultiChannelImageT<double> & probabilities )
  401. {
  402. Timer timer;
  403. timer.start();
  404. //segResult contains the GT labels when this method is called
  405. // we simply store them in labels, to have an easy access to the GT information lateron
  406. NICE::Image labels = segresult;
  407. //just to be sure that we do not have a GT-biased result :)
  408. segresult.set(0);
  409. int featdim = -1;
  410. std::string currentFile = Globals::getCurrentImgFN();
  411. int xsize, ysize;
  412. ce->getImageSize ( xsize, ysize );
  413. probabilities.reInit( xsize, ysize, this->classNames->getMaxClassno() + 1);
  414. probabilities.setAll ( -std::numeric_limits<double>::max() );
  415. NICE::ColorImage img;
  416. try {
  417. img = ColorImage ( currentFile );
  418. } catch ( Exception ) {
  419. cerr << "SemSegNovelty: error opening image file <" << currentFile << ">" << endl;
  420. return;
  421. }
  422. // MultiChannelImageT<double> m_CurrentImageFeatures;
  423. // extract features
  424. m_CurrentImageFeatures.freeData();
  425. featExtract->getFeats ( img, m_CurrentImageFeatures );
  426. featdim = m_CurrentImageFeatures.channels();
  427. m_CurrentImageFeatures.addChannel(featdim);
  428. for (int c = 0; c < featdim; c++)
  429. {
  430. ImageT<double> tmp = m_CurrentImageFeatures[c];
  431. ImageT<double> tmp2 = m_CurrentImageFeatures[c+featdim];
  432. NICE::FilterT<double, double, double>::gradientStrength (tmp, tmp2);
  433. }
  434. featdim += featdim;
  435. // compute integral images
  436. for ( int c = 0; c < featdim; c++ )
  437. {
  438. m_CurrentImageFeatures.calcIntegral ( c );
  439. }
  440. timer.stop();
  441. std::cout << "AL time for preparation: " << timer.getLastAbsolute() << std::endl;
  442. timer.start();
  443. //classification results currently only needed to be computed separately if we use the vclassifier, i.e., the nearest neighbor used
  444. // for the "novel feature learning" approach
  445. //in all other settings, such as active sem seg in general, we do this within the novelty-computation-methods
  446. if ( classifier == NULL )
  447. {
  448. this->computeClassificationResults( m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim);
  449. }
  450. // timer.stop();
  451. //
  452. // std::cerr << "classification results computed" << std::endl;
  453. FloatImage noveltyImage ( xsize, ysize );
  454. noveltyImage.set ( 0.0 );
  455. switch (noveltyMethod)
  456. {
  457. case GPVARIANCE:
  458. {
  459. this->computeNoveltyByVariance( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  460. break;
  461. }
  462. case GPUNCERTAINTY:
  463. {
  464. this->computeNoveltyByGPUncertainty( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  465. break;
  466. }
  467. case GPMINMEAN:
  468. {
  469. std::cerr << "compute novelty using the minimum mean" << std::endl;
  470. this->computeNoveltyByGPMean( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  471. break;
  472. }
  473. case GPMEANRATIO:
  474. {
  475. this->computeNoveltyByGPMeanRatio( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  476. break;
  477. }
  478. case GPWEIGHTALL:
  479. {
  480. this->computeNoveltyByGPWeightAll( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  481. break;
  482. }
  483. case GPWEIGHTRATIO:
  484. {
  485. this->computeNoveltyByGPWeightRatio( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  486. break;
  487. }
  488. case RANDOM:
  489. {
  490. this->computeNoveltyByRandom( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  491. break;
  492. }
  493. default:
  494. {
  495. //do nothing, keep the image constant to 0.0
  496. break;
  497. }
  498. }
  499. timer.stop();
  500. std::cout << "AL time for novelty score computation: " << timer.getLastAbsolute() << std::endl;
  501. if (b_visualizeALimages)
  502. {
  503. ColorImage imgrgbTmp (xsize, ysize);
  504. ICETools::convertToRGB ( noveltyImage, imgrgbTmp );
  505. showImage(imgrgbTmp, "Novelty Image without Region Segmentation");
  506. }
  507. timer.start();
  508. //Regionen ermitteln
  509. if(regionSeg != NULL)
  510. {
  511. NICE::Matrix mask;
  512. int amountRegions = regionSeg->segRegions ( img, mask );
  513. //compute probs per region
  514. std::vector<std::vector<double> > regionProb(amountRegions, std::vector<double>(probabilities.channels(), -std::numeric_limits<double>::max() ));
  515. std::vector<double> regionNoveltyMeasure (amountRegions, 0.0);
  516. std::vector<int> regionCounter(amountRegions, 0);
  517. std::vector<int> regionCounterNovelty(amountRegions, 0);
  518. for ( int y = 0; y < ysize; y += testWSize) //y++)
  519. {
  520. for (int x = 0; x < xsize; x += testWSize) //x++)
  521. {
  522. int r = mask(x,y);
  523. regionCounter[r]++;
  524. for(int j = 0; j < probabilities.channels(); j++)
  525. {
  526. if( regionProb[r][j] == -std::numeric_limits<double>::max() )
  527. regionProb[r][j] = 0.0f;
  528. regionProb[r][j] += probabilities ( x, y, j );
  529. }
  530. if ( forbidden_classesActiveLearning.find( labels(x,y) ) == forbidden_classesActiveLearning.end() )
  531. {
  532. //count the amount of "novelty" for the corresponding region
  533. regionNoveltyMeasure[r] += noveltyImage(x,y);
  534. regionCounterNovelty[r]++;
  535. }
  536. }
  537. }
  538. //find best class per region
  539. std::vector<int> bestClassPerRegion(amountRegions,0);
  540. double maxNoveltyScore = -numeric_limits<double>::max();
  541. if (!mostNoveltyWithMaxScores)
  542. {
  543. maxNoveltyScore = numeric_limits<double>::max();
  544. }
  545. int maxUncertRegion = -1;
  546. //loop over all regions and compute averaged novelty scores
  547. for(int r = 0; r < amountRegions; r++)
  548. {
  549. //check for the most plausible class per region
  550. double maxval = -numeric_limits<double>::max();
  551. //loop over all classes
  552. for(int c = 0; c < probabilities.channels(); c++)
  553. {
  554. regionProb[r][c] /= regionCounter[r];
  555. if( (maxval < regionProb[r][c]) ) //&& (regionProb[r][c] != 0.0) )
  556. {
  557. maxval = regionProb[r][c];
  558. bestClassPerRegion[r] = c;
  559. }
  560. }
  561. //if the region only contains unvalid information (e.g., background) skip it
  562. if (regionCounterNovelty[r] == 0)
  563. {
  564. continue;
  565. }
  566. //normalize summed novelty scores to region size
  567. regionNoveltyMeasure[r] /= regionCounterNovelty[r];
  568. //did we find a region that has a higher score as the most novel region known so far within this image?
  569. if( ( mostNoveltyWithMaxScores && (maxNoveltyScore < regionNoveltyMeasure[r]) ) // if we look for large novelty scores, e.g., variance
  570. || ( !mostNoveltyWithMaxScores && (maxNoveltyScore > regionNoveltyMeasure[r]) ) ) // if we look for small novelty scores, e.g., min mean
  571. {
  572. //did we already query a region of this image? -- and it was this specific region
  573. if ( (queriedRegions.find( currentFile ) != queriedRegions.end() ) && ( queriedRegions[currentFile].find(r) != queriedRegions[currentFile].end() ) )
  574. {
  575. continue;
  576. }
  577. else //only accept the region as novel if we never queried it before
  578. {
  579. maxNoveltyScore = regionNoveltyMeasure[r];
  580. maxUncertRegion = r;
  581. }
  582. }
  583. }
  584. // after finding the most novel region for the current image, check whether this region is also the most novel with respect
  585. // to all previously seen test images
  586. // if so, store the corresponding features, since we want to "actively" query them to incorporate useful information
  587. if(findMaximumUncert)
  588. {
  589. if( ( mostNoveltyWithMaxScores && (maxNoveltyScore > globalMaxUncert) )
  590. || ( !mostNoveltyWithMaxScores && (maxNoveltyScore < globalMaxUncert) ) )
  591. {
  592. //current most novel region of the image has "higher" novelty score then previous most novel region of all test images worked on so far
  593. // -> save new important features of this region
  594. Examples examples;
  595. for ( int y = 0; y < ysize; y += testWSize )
  596. {
  597. for ( int x = 0; x < xsize; x += testWSize)
  598. {
  599. if(mask(x,y) == maxUncertRegion)
  600. {
  601. int classnoTmp = labels(x,y);
  602. if ( forbidden_classesActiveLearning.find(classnoTmp) != forbidden_classesActiveLearning.end() )
  603. continue;
  604. Example t_Example(NULL, x, y);
  605. t_Example.vec = NULL;
  606. t_Example.svec = new SparseVector ( featdim );
  607. for ( int f = 0; f < featdim; f++ )
  608. {
  609. // double val = ( *example.svec ) [f];
  610. double val = m_CurrentImageFeatures.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  611. if ( val > 1e-10 )
  612. ( *t_Example.svec ) [f] = val;
  613. }
  614. examples.push_back ( pair<int, Example> ( classnoTmp, t_Example ) );
  615. }
  616. }
  617. }
  618. if(examples.size() > 0)
  619. {
  620. std::cerr << "found " << examples.size() << " new examples in the queried region" << std::endl << std::endl;
  621. // sauber aufräumen
  622. for( int i=0; i< newTrainExamples.size(); i++)
  623. {
  624. delete newTrainExamples.at(i).second.svec;
  625. newTrainExamples.at(i).second.svec = NULL;
  626. }
  627. newTrainExamples.clear();
  628. newTrainExamples = examples;
  629. globalMaxUncert = maxNoveltyScore;
  630. //prepare for later visualization
  631. // if (b_visualizeALimages)
  632. visualizeRegion(img,mask,maxUncertRegion,maskedImg);
  633. }
  634. else
  635. {
  636. std::cerr << "the queried region has no valid information" << std::endl << std::endl;
  637. }
  638. //save filename and region index
  639. currentRegionToQuery.first = currentFile;
  640. currentRegionToQuery.second = maxUncertRegion;
  641. }
  642. }
  643. //write back best results per region
  644. //i.e., write normalized novelty scores for every region into the novelty image
  645. for ( int y = 0; y < ysize; y++)
  646. {
  647. for (int x = 0; x < xsize; x++)
  648. {
  649. int r = mask(x,y);
  650. for(int j = 0; j < probabilities.channels(); j++)
  651. {
  652. probabilities ( x, y, j ) = regionProb[r][j];
  653. }
  654. segresult(x,y) = bestClassPerRegion[r];
  655. // write novelty scores for every segment into the "final" image
  656. noveltyImage(x,y) = regionNoveltyMeasure[r];
  657. }
  658. }
  659. } // if regionSeg != null
  660. timer.stop();
  661. std::cout << "AL time for determination of novel regions: " << timer.getLastAbsolute() << std::endl;
  662. if (b_visualizeALimages)
  663. {
  664. timer.start();
  665. std::stringstream out;
  666. std::vector< std::string > list2;
  667. StringTools::split ( Globals::getCurrentImgFN (), '/', list2 );
  668. out << resultdir << "/" << list2.back();
  669. noveltyImage.writeRaw(out.str() + "_run_" + NICE::intToString(this->iterationCountSuffix) + "_" + noveltyMethodString+".rawfloat");
  670. ColorImage imgrgb ( xsize, ysize );
  671. ICETools::convertToRGB ( noveltyImage, imgrgb );
  672. showImage(imgrgb, "Novelty Image");
  673. timer.stop();
  674. cout << "AL time for writing the raw novelty image: " << timer.getLastAbsolute() << endl;
  675. }
  676. }
  677. inline void SemSegNovelty::computeClassificationResults( const NICE::MultiChannelImageT<double> & feats,
  678. NICE::Image & segresult,
  679. NICE::MultiChannelImageT<double> & probabilities,
  680. const int & xsize,
  681. const int & ysize,
  682. const int & featdim
  683. )
  684. {
  685. std::cerr << "featdim: " << featdim << std::endl;
  686. if ( classifier != NULL )
  687. {
  688. #pragma omp parallel for
  689. for ( int y = 0; y < ysize; y += testWSize )
  690. {
  691. Example example;
  692. example.vec = NULL;
  693. example.svec = new SparseVector ( featdim );
  694. for ( int x = 0; x < xsize; x += testWSize)
  695. {
  696. for ( int f = 0; f < featdim; f++ )
  697. {
  698. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  699. if ( val > 1e-10 )
  700. ( *example.svec ) [f] = val;
  701. }
  702. example.svec->normalize();
  703. ClassificationResult cr = classifier->classify ( example );
  704. int xs = std::max(0, x - testWSize/2);
  705. int xe = std::min(xsize - 1, x + testWSize/2);
  706. int ys = std::max(0, y - testWSize/2);
  707. int ye = std::min(ysize - 1, y + testWSize/2);
  708. for (int yl = ys; yl <= ye; yl++)
  709. {
  710. for (int xl = xs; xl <= xe; xl++)
  711. {
  712. for ( int j = 0 ; j < cr.scores.size(); j++ )
  713. {
  714. probabilities ( xl, yl, j ) = cr.scores[j];
  715. }
  716. segresult ( xl, yl ) = cr.classno;
  717. }
  718. }
  719. example.svec->clear();
  720. }
  721. delete example.svec;
  722. example.svec = NULL;
  723. }
  724. }
  725. else //vclassifier
  726. {
  727. std::cerr << "compute classification results with vclassifier" << std::endl;
  728. #pragma omp parallel for
  729. for ( int y = 0; y < ysize; y += testWSize )
  730. {
  731. for ( int x = 0; x < xsize; x += testWSize)
  732. {
  733. NICE::Vector v(featdim);
  734. for ( int f = 0; f < featdim; f++ )
  735. {
  736. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  737. v[f] = val;
  738. }
  739. v.normalizeL1();
  740. ClassificationResult cr = vclassifier->classify ( v );
  741. int xs = std::max(0, x - testWSize/2);
  742. int xe = std::min(xsize - 1, x + testWSize/2);
  743. int ys = std::max(0, y - testWSize/2);
  744. int ye = std::min(ysize - 1, y + testWSize/2);
  745. for (int yl = ys; yl <= ye; yl++)
  746. {
  747. for (int xl = xs; xl <= xe; xl++)
  748. {
  749. for ( int j = 0 ; j < cr.scores.size(); j++ )
  750. {
  751. probabilities ( xl, yl, j ) = cr.scores[j];
  752. }
  753. segresult ( xl, yl ) = cr.classno;
  754. }
  755. }
  756. }
  757. }
  758. }
  759. }
  760. // compute novelty images depending on the strategy chosen
  761. void SemSegNovelty::computeNoveltyByRandom( NICE::FloatImage & noveltyImage,
  762. const NICE::MultiChannelImageT<double> & feats,
  763. NICE::Image & segresult,
  764. NICE::MultiChannelImageT<double> & probabilities,
  765. const int & xsize, const int & ysize, const int & featdim )
  766. {
  767. #pragma omp parallel for
  768. for ( int y = 0; y < ysize; y += testWSize )
  769. {
  770. Example example;
  771. example.vec = NULL;
  772. example.svec = new SparseVector ( featdim );
  773. for ( int x = 0; x < xsize; x += testWSize)
  774. {
  775. for ( int f = 0; f < featdim; f++ )
  776. {
  777. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  778. if ( val > 1e-10 )
  779. ( *example.svec ) [f] = val;
  780. }
  781. example.svec->normalize();
  782. ClassificationResult cr = classifier->classify ( example );
  783. int xs = std::max(0, x - testWSize/2);
  784. int xe = std::min(xsize - 1, x + testWSize/2);
  785. int ys = std::max(0, y - testWSize/2);
  786. int ye = std::min(ysize - 1, y + testWSize/2);
  787. double randVal = randDouble();
  788. for (int yl = ys; yl <= ye; yl++)
  789. {
  790. for (int xl = xs; xl <= xe; xl++)
  791. {
  792. for ( int j = 0 ; j < cr.scores.size(); j++ )
  793. {
  794. probabilities ( xl, yl, j ) = cr.scores[j];
  795. }
  796. segresult ( xl, yl ) = cr.classno;
  797. noveltyImage ( xl, yl ) = randVal;
  798. }
  799. }
  800. }
  801. }
  802. }
  803. void SemSegNovelty::computeNoveltyByVariance( NICE::FloatImage & noveltyImage,
  804. const NICE::MultiChannelImageT<double> & feats,
  805. NICE::Image & segresult,
  806. NICE::MultiChannelImageT<double> & probabilities,
  807. const int & xsize, const int & ysize, const int & featdim )
  808. {
  809. #pragma omp parallel for
  810. for ( int y = 0; y < ysize; y += testWSize )
  811. {
  812. Example example;
  813. example.vec = NULL;
  814. example.svec = new SparseVector ( featdim );
  815. for ( int x = 0; x < xsize; x += testWSize)
  816. {
  817. for ( int f = 0; f < featdim; f++ )
  818. {
  819. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  820. if ( val > 1e-10 )
  821. ( *example.svec ) [f] = val;
  822. }
  823. example.svec->normalize();
  824. ClassificationResult cr = classifier->classify ( example );
  825. int xs = std::max(0, x - testWSize/2);
  826. int xe = std::min(xsize - 1, x + testWSize/2);
  827. int ys = std::max(0, y - testWSize/2);
  828. int ye = std::min(ysize - 1, y + testWSize/2);
  829. for (int yl = ys; yl <= ye; yl++)
  830. {
  831. for (int xl = xs; xl <= xe; xl++)
  832. {
  833. for ( int j = 0 ; j < cr.scores.size(); j++ )
  834. {
  835. probabilities ( xl, yl, j ) = cr.scores[j];
  836. }
  837. segresult ( xl, yl ) = cr.classno;
  838. noveltyImage ( xl, yl ) = cr.uncertainty;
  839. }
  840. }
  841. example.svec->clear();
  842. }
  843. delete example.svec;
  844. example.svec = NULL;
  845. }
  846. }
  847. void SemSegNovelty::computeNoveltyByGPUncertainty( NICE::FloatImage & noveltyImage,
  848. const NICE::MultiChannelImageT<double> & feats,
  849. NICE::Image & segresult,
  850. NICE::MultiChannelImageT<double> & probabilities,
  851. const int & xsize, const int & ysize, const int & featdim )
  852. {
  853. double gpNoise = 0.01;
  854. //TODO getMethod for GPHIK
  855. //conf->gD("GPHIK", "noise", 0.01);
  856. #pragma omp parallel for
  857. for ( int y = 0; y < ysize; y += testWSize )
  858. {
  859. Example example;
  860. example.vec = NULL;
  861. example.svec = new SparseVector ( featdim );
  862. for ( int x = 0; x < xsize; x += testWSize)
  863. {
  864. for ( int f = 0; f < featdim; f++ )
  865. {
  866. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  867. if ( val > 1e-10 )
  868. ( *example.svec ) [f] = val;
  869. }
  870. example.svec->normalize();
  871. ClassificationResult cr = classifier->classify ( example );
  872. double maxMeanAbs ( 0.0 );
  873. for ( int j = 0 ; j < cr.scores.size(); j++ )
  874. {
  875. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  876. {
  877. continue;
  878. }
  879. //check for larger abs mean
  880. if (abs(cr.scores[j]) > maxMeanAbs)
  881. {
  882. maxMeanAbs = abs(cr.scores[j]);
  883. }
  884. }
  885. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  886. //compute the heuristic GP-UNCERTAINTY, as proposed by Kapoor et al. in IJCV 2010
  887. // GP-UNCERTAINTY : |mean| / sqrt(var^2 + gpnoise^2)
  888. double gpUncertaintyVal = maxMeanAbs*firstTerm; //firstTerm = 1.0 / sqrt(r.uncertainty+gpNoise))
  889. int xs = std::max(0, x - testWSize/2);
  890. int xe = std::min(xsize - 1, x + testWSize/2);
  891. int ys = std::max(0, y - testWSize/2);
  892. int ye = std::min(ysize - 1, y + testWSize/2);
  893. for (int yl = ys; yl <= ye; yl++)
  894. {
  895. for (int xl = xs; xl <= xe; xl++)
  896. {
  897. for ( int j = 0 ; j < cr.scores.size(); j++ )
  898. {
  899. probabilities ( xl, yl, j ) = cr.scores[j];
  900. }
  901. segresult ( xl, yl ) = cr.classno;
  902. noveltyImage ( xl, yl ) = gpUncertaintyVal;
  903. }
  904. }
  905. example.svec->clear();
  906. }
  907. delete example.svec;
  908. example.svec = NULL;
  909. }
  910. }
  911. void SemSegNovelty::computeNoveltyByGPMean( NICE::FloatImage & noveltyImage,
  912. const NICE::MultiChannelImageT<double> & feats,
  913. NICE::Image & segresult,
  914. NICE::MultiChannelImageT<double> & probabilities,
  915. const int & xsize, const int & ysize, const int & featdim )
  916. {
  917. double gpNoise = 0.01;
  918. //TODO getMethod for GPHIK
  919. //conf->gD("GPHIK", "noise", 0.01);
  920. #pragma omp parallel for
  921. for ( int y = 0; y < ysize; y += testWSize )
  922. {
  923. Example example;
  924. example.vec = NULL;
  925. example.svec = new SparseVector ( featdim );
  926. for ( int x = 0; x < xsize; x += testWSize)
  927. {
  928. for ( int f = 0; f < featdim; f++ )
  929. {
  930. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  931. if ( val > 1e-10 )
  932. ( *example.svec ) [f] = val;
  933. }
  934. example.svec->normalize();
  935. ClassificationResult cr = classifier->classify ( example );
  936. double minMeanAbs ( numeric_limits<double>::max() );
  937. for ( int j = 0 ; j < probabilities.channels(); j++ )
  938. {
  939. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  940. {
  941. continue;
  942. }
  943. //check whether we found a class with higher smaller abs mean than the current minimum
  944. if (abs( cr.scores[j] ) < minMeanAbs)
  945. {
  946. minMeanAbs = abs(cr.scores[j]);
  947. }
  948. }
  949. // compute results when we take the lowest mean value of all classes
  950. double gpMeanVal = minMeanAbs;
  951. int xs = std::max(0, x - testWSize/2);
  952. int xe = std::min(xsize - 1, x + testWSize/2);
  953. int ys = std::max(0, y - testWSize/2);
  954. int ye = std::min(ysize - 1, y + testWSize/2);
  955. for (int yl = ys; yl <= ye; yl++)
  956. {
  957. for (int xl = xs; xl <= xe; xl++)
  958. {
  959. for ( int j = 0 ; j < cr.scores.size(); j++ )
  960. {
  961. probabilities ( xl, yl, j ) = cr.scores[j];
  962. }
  963. segresult ( xl, yl ) = cr.classno;
  964. noveltyImage ( xl, yl ) = gpMeanVal;
  965. }
  966. }
  967. }
  968. }
  969. }
  970. void SemSegNovelty::computeNoveltyByGPMeanRatio( NICE::FloatImage & noveltyImage,
  971. const NICE::MultiChannelImageT<double> & feats,
  972. NICE::Image & segresult,
  973. NICE::MultiChannelImageT<double> & probabilities,
  974. const int & xsize, const int & ysize, const int & featdim )
  975. {
  976. double gpNoise = 0.01;
  977. //TODO getMethod for GPHIK
  978. //conf->gD("GPHIK", "noise", 0.01);
  979. #pragma omp parallel for
  980. for ( int y = 0; y < ysize; y += testWSize )
  981. {
  982. Example example;
  983. example.vec = NULL;
  984. example.svec = new SparseVector ( featdim );
  985. for ( int x = 0; x < xsize; x += testWSize)
  986. {
  987. for ( int f = 0; f < featdim; f++ )
  988. {
  989. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  990. if ( val > 1e-10 )
  991. ( *example.svec ) [f] = val;
  992. }
  993. example.svec->normalize();
  994. ClassificationResult cr = classifier->classify ( example );
  995. double maxMean ( -numeric_limits<double>::max() );
  996. double sndMaxMean ( -numeric_limits<double>::max() );
  997. for ( int j = 0 ; j < cr.scores.size(); j++ )
  998. {
  999. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1000. {
  1001. continue;
  1002. }
  1003. //check for larger mean without abs as well
  1004. if (cr.scores[j] > maxMean)
  1005. {
  1006. sndMaxMean = maxMean;
  1007. maxMean = cr.scores[j];
  1008. }
  1009. // and also for the second highest mean of all classes
  1010. else if (cr.scores[j] > sndMaxMean)
  1011. {
  1012. sndMaxMean = cr.scores[j];
  1013. }
  1014. }
  1015. //look at the difference in the absolut mean values for the most plausible class
  1016. // and the second most plausible class
  1017. double gpMeanRatioVal= maxMean - sndMaxMean;
  1018. int xs = std::max(0, x - testWSize/2);
  1019. int xe = std::min(xsize - 1, x + testWSize/2);
  1020. int ys = std::max(0, y - testWSize/2);
  1021. int ye = std::min(ysize - 1, y + testWSize/2);
  1022. for (int yl = ys; yl <= ye; yl++)
  1023. {
  1024. for (int xl = xs; xl <= xe; xl++)
  1025. {
  1026. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1027. {
  1028. probabilities ( xl, yl, j ) = cr.scores[j];
  1029. }
  1030. segresult ( xl, yl ) = cr.classno;
  1031. noveltyImage ( xl, yl ) = gpMeanRatioVal;
  1032. }
  1033. }
  1034. example.svec->clear();
  1035. }
  1036. delete example.svec;
  1037. example.svec = NULL;
  1038. }
  1039. }
  1040. void SemSegNovelty::computeNoveltyByGPWeightAll( NICE::FloatImage & noveltyImage,
  1041. const NICE::MultiChannelImageT<double> & feats,
  1042. NICE::Image & segresult,
  1043. NICE::MultiChannelImageT<double> & probabilities,
  1044. const int & xsize, const int & ysize, const int & featdim )
  1045. {
  1046. double gpNoise = 0.01;
  1047. //TODO getMethod for GPHIK
  1048. //conf->gD("GPHIK", "noise", 0.01);
  1049. #pragma omp parallel for
  1050. for ( int y = 0; y < ysize; y += testWSize )
  1051. {
  1052. Example example;
  1053. example.vec = NULL;
  1054. example.svec = new SparseVector ( featdim );
  1055. for ( int x = 0; x < xsize; x += testWSize)
  1056. {
  1057. for ( int f = 0; f < featdim; f++ )
  1058. {
  1059. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  1060. if ( val > 1e-10 )
  1061. ( *example.svec ) [f] = val;
  1062. }
  1063. example.svec->normalize();
  1064. ClassificationResult cr = classifier->classify ( example );
  1065. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  1066. double gpWeightAllVal ( 0.0 );
  1067. if ( numberOfClasses > 2)
  1068. {
  1069. //compute the weight in the alpha-vector for every sample after assuming it to be
  1070. // added to the training set.
  1071. // Thereby, we measure its "importance" for the current model
  1072. //
  1073. //double firstTerm is already computed
  1074. //
  1075. //the second term is only needed when computing impacts
  1076. //double secondTerm; //this is the nasty guy :/
  1077. //--- compute the third term
  1078. // this is the difference between predicted label and GT label
  1079. std::vector<double> diffToPositive; diffToPositive.clear();
  1080. std::vector<double> diffToNegative; diffToNegative.clear();
  1081. double diffToNegativeSum(0.0);
  1082. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1083. {
  1084. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1085. {
  1086. continue;
  1087. }
  1088. // look at the difference to plus 1
  1089. diffToPositive.push_back(abs(cr.scores[j] - 1));
  1090. // look at the difference to -1
  1091. diffToNegative.push_back(abs(cr.scores[j] + 1));
  1092. //sum up the difference to -1
  1093. diffToNegativeSum += abs(cr.scores[j] - 1);
  1094. }
  1095. //let's subtract for every class its diffToNegative from the sum, add its diffToPositive,
  1096. //and use this as the third term for this specific class.
  1097. //the final value is obtained by minimizing over all classes
  1098. //
  1099. // originally, we minimize over all classes after building the final score
  1100. // however, the first and the second term do not depend on the choice of
  1101. // y*, therefore we minimize here already
  1102. double thirdTerm (numeric_limits<double>::max()) ;
  1103. for(uint tmpCnt = 0; tmpCnt < diffToPositive.size(); tmpCnt++)
  1104. {
  1105. double tmpVal ( diffToPositive[tmpCnt] + (diffToNegativeSum-diffToNegative[tmpCnt]) );
  1106. if (tmpVal < thirdTerm)
  1107. thirdTerm = tmpVal;
  1108. }
  1109. gpWeightAllVal = thirdTerm*firstTerm;
  1110. }
  1111. else //binary scenario
  1112. {
  1113. gpWeightAllVal = std::min( abs(cr.scores[*classesInUse.begin()]+1), abs(cr.scores[*classesInUse.begin()]-1) );
  1114. gpWeightAllVal *= firstTerm;
  1115. }
  1116. int xs = std::max(0, x - testWSize/2);
  1117. int xe = std::min(xsize - 1, x + testWSize/2);
  1118. int ys = std::max(0, y - testWSize/2);
  1119. int ye = std::min(ysize - 1, y + testWSize/2);
  1120. for (int yl = ys; yl <= ye; yl++)
  1121. {
  1122. for (int xl = xs; xl <= xe; xl++)
  1123. {
  1124. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1125. {
  1126. probabilities ( xl, yl, j ) = cr.scores[j];
  1127. }
  1128. segresult ( xl, yl ) = cr.classno;
  1129. noveltyImage ( xl, yl ) = gpWeightAllVal;
  1130. }
  1131. }
  1132. example.svec->clear();
  1133. }
  1134. delete example.svec;
  1135. example.svec = NULL;
  1136. }
  1137. }
  1138. void SemSegNovelty::computeNoveltyByGPWeightRatio( NICE::FloatImage & noveltyImage,
  1139. const NICE::MultiChannelImageT<double> & feats,
  1140. NICE::Image & segresult,
  1141. NICE::MultiChannelImageT<double> & probabilities,
  1142. const int & xsize, const int & ysize, const int & featdim )
  1143. {
  1144. double gpNoise = 0.01;
  1145. //TODO getMethod for GPHIK
  1146. //conf->gD("GPHIK", "noise", 0.01);
  1147. #pragma omp parallel for
  1148. for ( int y = 0; y < ysize; y += testWSize )
  1149. {
  1150. Example example;
  1151. example.vec = NULL;
  1152. example.svec = new SparseVector ( featdim );
  1153. for ( int x = 0; x < xsize; x += testWSize)
  1154. {
  1155. for ( int f = 0; f < featdim; f++ )
  1156. {
  1157. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  1158. if ( val > 1e-10 )
  1159. ( *example.svec ) [f] = val;
  1160. }
  1161. example.svec->normalize();
  1162. ClassificationResult cr = classifier->classify ( example );
  1163. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  1164. double gpWeightRatioVal ( 0.0 );
  1165. if ( numberOfClasses > 2)
  1166. {
  1167. //compute the weight in the alpha-vector for every sample after assuming it to be
  1168. // added to the training set.
  1169. // Thereby, we measure its "importance" for the current model
  1170. //
  1171. //double firstTerm is already computed
  1172. //
  1173. //the second term is only needed when computing impacts
  1174. //double secondTerm; //this is the nasty guy :/
  1175. //--- compute the third term
  1176. // this is the difference between predicted label and GT label
  1177. std::vector<double> diffToPositive; diffToPositive.clear();
  1178. std::vector<double> diffToNegative; diffToNegative.clear();
  1179. double diffToNegativeSum(0.0);
  1180. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1181. {
  1182. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1183. {
  1184. continue;
  1185. }
  1186. // look at the difference to plus 1
  1187. diffToPositive.push_back(abs(cr.scores[j] - 1));
  1188. }
  1189. //let's subtract for every class its diffToNegative from the sum, add its diffToPositive,
  1190. //and use this as the third term for this specific class.
  1191. //the final value is obtained by minimizing over all classes
  1192. //
  1193. // originally, we minimize over all classes after building the final score
  1194. // however, the first and the second term do not depend on the choice of
  1195. // y*, therefore we minimize here already
  1196. //now look on the ratio of the resulting weights for the most plausible
  1197. // against the second most plausible class
  1198. double thirdTermMostPlausible ( 0.0 ) ;
  1199. double thirdTermSecondMostPlausible ( 0.0 ) ;
  1200. for(uint tmpCnt = 0; tmpCnt < diffToPositive.size(); tmpCnt++)
  1201. {
  1202. if (diffToPositive[tmpCnt] > thirdTermMostPlausible)
  1203. {
  1204. thirdTermSecondMostPlausible = thirdTermMostPlausible;
  1205. thirdTermMostPlausible = diffToPositive[tmpCnt];
  1206. }
  1207. else if (diffToPositive[tmpCnt] > thirdTermSecondMostPlausible)
  1208. {
  1209. thirdTermSecondMostPlausible = diffToPositive[tmpCnt];
  1210. }
  1211. }
  1212. //compute the resulting score
  1213. gpWeightRatioVal = (thirdTermMostPlausible - thirdTermSecondMostPlausible)*firstTerm;
  1214. //finally, look for this feature how it would affect to whole model (summarized by weight-vector alpha), if we would
  1215. //use it as an additional training example
  1216. //TODO this would be REALLY computational demanding. Do we really want to do this?
  1217. // gpImpactAll[s] ( pce[i].second.x, pce[i].second.y ) = thirdTerm*firstTerm*secondTerm;
  1218. // gpImpactRatio[s] ( pce[i].second.x, pce[i].second.y ) = (thirdTermMostPlausible - thirdTermSecondMostPlausible)*firstTerm*secondTerm;
  1219. }
  1220. else //binary scenario
  1221. {
  1222. gpWeightRatioVal = std::min( abs(cr.scores[*classesInUse.begin()]+1), abs(cr.scores[*classesInUse.begin()]-1) );
  1223. gpWeightRatioVal *= firstTerm;
  1224. }
  1225. int xs = std::max(0, x - testWSize/2);
  1226. int xe = std::min(xsize - 1, x + testWSize/2);
  1227. int ys = std::max(0, y - testWSize/2);
  1228. int ye = std::min(ysize - 1, y + testWSize/2);
  1229. for (int yl = ys; yl <= ye; yl++)
  1230. {
  1231. for (int xl = xs; xl <= xe; xl++)
  1232. {
  1233. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1234. {
  1235. probabilities ( xl, yl, j ) = cr.scores[j];
  1236. }
  1237. segresult ( xl, yl ) = cr.classno;
  1238. noveltyImage ( xl, yl ) = gpWeightRatioVal;
  1239. }
  1240. }
  1241. example.svec->clear();
  1242. }
  1243. delete example.svec;
  1244. example.svec = NULL;
  1245. }
  1246. }
  1247. void SemSegNovelty::addNewExample(const NICE::Vector& v_newExample, const int & newClassNo)
  1248. {
  1249. //accept the new class as valid information
  1250. if ( forbidden_classesTrain.find ( newClassNo ) != forbidden_classesTrain.end() )
  1251. {
  1252. forbidden_classesTrain.erase(newClassNo);
  1253. numberOfClasses++;
  1254. }
  1255. if ( classesInUse.find ( newClassNo ) == classesInUse.end() )
  1256. {
  1257. classesInUse.insert( newClassNo );
  1258. }
  1259. //then add it to the classifier used
  1260. if ( classifier != NULL )
  1261. {
  1262. if (this->classifierString.compare("GPHIKClassifier") == 0)
  1263. {
  1264. Example newExample;
  1265. SparseVector svec ( v_newExample );
  1266. newExample.svec = &svec;
  1267. static_cast<GPHIKClassifierNICE*>(classifier)->addExample ( newExample, newClassNo );
  1268. }
  1269. }
  1270. else //vclassifier
  1271. {
  1272. if (this->classifierString.compare("nn") == 0)
  1273. {
  1274. vclassifier->teach ( newClassNo, v_newExample );
  1275. }
  1276. }
  1277. }
  1278. void SemSegNovelty::addNovelExamples()
  1279. {
  1280. Timer timer;
  1281. //show the image that contains the most novel region
  1282. if (b_visualizeALimages)
  1283. showImage(maskedImg, "Most novel region");
  1284. timer.start();
  1285. std::stringstream out;
  1286. std::vector< std::string > list2;
  1287. StringTools::split ( Globals::getCurrentImgFN (), '/', list2 );
  1288. out << resultdir << "/" << list2.back();
  1289. maskedImg.writePPM ( out.str() + "_run_" + NICE::intToString(this->iterationCountSuffix) + "_" + noveltyMethodString+ "_query.ppm" );
  1290. timer.stop();
  1291. std::cerr << "AL time for writing queried image: " << timer.getLast() << std::endl;
  1292. timer.start();
  1293. //check which classes will be added using the features from the novel region
  1294. std::set<int> newClassNumbers;
  1295. newClassNumbers.clear(); //just to be sure
  1296. for ( uint i = 0 ; i < newTrainExamples.size() ; i++ )
  1297. {
  1298. if (newClassNumbers.find(newTrainExamples[i].first /* classNumber*/) == newClassNumbers.end() )
  1299. {
  1300. newClassNumbers.insert(newTrainExamples[i].first );
  1301. }
  1302. }
  1303. //accept the new classes as valid information
  1304. for (std::set<int>::const_iterator clNoIt = newClassNumbers.begin(); clNoIt != newClassNumbers.end(); clNoIt++)
  1305. {
  1306. if ( forbidden_classesTrain.find ( *clNoIt ) != forbidden_classesTrain.end() )
  1307. {
  1308. forbidden_classesTrain.erase(*clNoIt);
  1309. numberOfClasses++;
  1310. }
  1311. if ( classesInUse.find ( *clNoIt ) == classesInUse.end() )
  1312. {
  1313. classesInUse.insert( *clNoIt );
  1314. }
  1315. }
  1316. timer.stop();
  1317. std::cerr << "AL time for accepting possible new classes: " << timer.getLast() << std::endl;
  1318. timer.start();
  1319. //then add the new features to the classifier used
  1320. if ( classifier != NULL )
  1321. {
  1322. if (this->classifierString.compare("GPHIKClassifier") == 0)
  1323. {
  1324. classifier->addMultipleExamples ( this->newTrainExamples );
  1325. }
  1326. }
  1327. else //vclassifier
  1328. {
  1329. //TODO
  1330. }
  1331. timer.stop();
  1332. std::cerr << "AL time for actually updating the classifier: " << timer.getLast() << std::endl;
  1333. std::cerr << "the current region to query is: " << currentRegionToQuery.first << " -- " << currentRegionToQuery.second << std::endl;
  1334. //did we already query a region of this image?
  1335. if ( queriedRegions.find( currentRegionToQuery.first ) != queriedRegions.end() )
  1336. {
  1337. queriedRegions[ currentRegionToQuery.first ].insert(currentRegionToQuery.second);
  1338. }
  1339. else
  1340. {
  1341. std::set<int> tmpSet; tmpSet.insert(currentRegionToQuery.second);
  1342. queriedRegions.insert(std::pair<std::string,std::set<int> > (currentRegionToQuery.first, tmpSet ) );
  1343. }
  1344. std::cerr << "Write already queried regions: " << std::endl;
  1345. for (std::map<std::string,std::set<int> >::const_iterator it = queriedRegions.begin(); it != queriedRegions.end(); it++)
  1346. {
  1347. std::cerr << "image: " << it->first << " -- ";
  1348. for (std::set<int>::const_iterator itReg = it->second.begin(); itReg != it->second.end(); itReg++)
  1349. {
  1350. std::cerr << *itReg << " ";
  1351. }
  1352. std::cerr << std::endl;
  1353. }
  1354. //clear the latest results, since one iteration is over
  1355. globalMaxUncert = -numeric_limits<double>::max();
  1356. if (!mostNoveltyWithMaxScores)
  1357. globalMaxUncert = numeric_limits<double>::max();
  1358. }
  1359. const Examples * SemSegNovelty::getNovelExamples() const
  1360. {
  1361. return &(this->newTrainExamples);
  1362. }
  1363. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1364. // interface specific methods for store and restore
  1365. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1366. void SemSegNovelty::restore ( std::istream & is, int format )
  1367. {
  1368. //delete everything we knew so far...
  1369. this->clear();
  1370. bool b_restoreVerbose ( false );
  1371. #ifdef B_RESTOREVERBOSE
  1372. b_restoreVerbose = true;
  1373. #endif
  1374. if ( is.good() )
  1375. {
  1376. if ( b_restoreVerbose )
  1377. std::cerr << " restore SemSegNovelty" << std::endl;
  1378. std::string tmp;
  1379. is >> tmp; //class name
  1380. if ( ! this->isStartTag( tmp, "SemSegNovelty" ) )
  1381. {
  1382. std::cerr << " WARNING - attempt to restore SemSegNovelty, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1383. throw;
  1384. }
  1385. if (classifier != NULL)
  1386. {
  1387. delete classifier;
  1388. classifier = NULL;
  1389. }
  1390. is.precision (numeric_limits<double>::digits10 + 1);
  1391. bool b_endOfBlock ( false ) ;
  1392. while ( !b_endOfBlock )
  1393. {
  1394. is >> tmp; // start of block
  1395. if ( this->isEndTag( tmp, "SemSegNovelty" ) )
  1396. {
  1397. b_endOfBlock = true;
  1398. continue;
  1399. }
  1400. tmp = this->removeStartTag ( tmp );
  1401. if ( b_restoreVerbose )
  1402. std::cerr << " currently restore section " << tmp << " in SemSegNovelty" << std::endl;
  1403. ///////////////////////////////
  1404. // FEATURE EXTRACTION //
  1405. ///////////////////////////////
  1406. if ( tmp.compare("featExtract") == 0 )
  1407. {
  1408. featExtract->restore(is, format);
  1409. is >> tmp; // end of block
  1410. tmp = this->removeEndTag ( tmp );
  1411. }
  1412. else if ( tmp.compare("trainWSize") == 0 )
  1413. {
  1414. is >> trainWSize;
  1415. is >> tmp; // end of block
  1416. tmp = this->removeEndTag ( tmp );
  1417. }
  1418. else if ( tmp.compare("whs") == 0 )
  1419. {
  1420. is >> whs;
  1421. is >> tmp; // end of block
  1422. tmp = this->removeEndTag ( tmp );
  1423. }
  1424. else if ( tmp.compare("testWSize") == 0 )
  1425. {
  1426. is >> testWSize;
  1427. is >> tmp; // end of block
  1428. tmp = this->removeEndTag ( tmp );
  1429. }
  1430. ///////////////////////////////
  1431. // NOVELTY COMPUTATION //
  1432. ///////////////////////////////
  1433. else if ( tmp.compare("noveltyMethod") == 0 )
  1434. {
  1435. unsigned int ui_noveltyMethod;
  1436. is >> ui_noveltyMethod;
  1437. this->noveltyMethod = static_cast<NoveltyMethod> ( ui_noveltyMethod );
  1438. is >> tmp; // end of block
  1439. tmp = this->removeEndTag ( tmp );
  1440. }
  1441. else if ( tmp.compare("noveltyMethodString") == 0 )
  1442. {
  1443. is >> noveltyMethodString;
  1444. is >> tmp; // end of block
  1445. tmp = this->removeEndTag ( tmp );
  1446. }
  1447. else if ( tmp.compare("globalMaxUncert") == 0 )
  1448. {
  1449. is >> globalMaxUncert;
  1450. is >> tmp; // end of block
  1451. tmp = this->removeEndTag ( tmp );
  1452. }
  1453. else if ( tmp.compare("mostNoveltyWithMaxScores") == 0 )
  1454. {
  1455. is >> mostNoveltyWithMaxScores;
  1456. is >> tmp; // end of block
  1457. tmp = this->removeEndTag ( tmp );
  1458. }
  1459. else if ( tmp.compare("findMaximumUncert") == 0 )
  1460. {
  1461. is >> findMaximumUncert;
  1462. is >> tmp; // end of block
  1463. tmp = this->removeEndTag ( tmp );
  1464. }
  1465. //TODO maskedImg
  1466. else if ( tmp.compare("b_visualizeALimages") == 0 )
  1467. {
  1468. is >> b_visualizeALimages;
  1469. is >> tmp; // end of block
  1470. tmp = this->removeEndTag ( tmp );
  1471. }
  1472. ///////////////////////////////
  1473. // CLASSIFICATION STUFF //
  1474. ///////////////////////////////
  1475. else if ( tmp.compare("classifier") == 0 )
  1476. {
  1477. std::string isNull;
  1478. is >> isNull;
  1479. // check whether we originally used a classifier
  1480. if ( isNull.compare( "NULL" ) == 0 )
  1481. {
  1482. if ( classifier != NULL )
  1483. delete classifier;
  1484. classifier = NULL;
  1485. }
  1486. else
  1487. {
  1488. if ( classifier == NULL )
  1489. classifier = new OBJREC::GPHIKClassifierNICE();
  1490. classifier->restore(is, format);
  1491. }
  1492. is >> tmp; // end of block
  1493. tmp = this->removeEndTag ( tmp );
  1494. }
  1495. else if ( tmp.compare("vclassifier") == 0 )
  1496. {
  1497. std::string isNull;
  1498. is >> isNull;
  1499. // check whether we originally used a vclassifier
  1500. if ( isNull.compare( "NULL" ) == 0 )
  1501. {
  1502. if ( vclassifier != NULL )
  1503. delete vclassifier;
  1504. vclassifier = NULL;
  1505. }
  1506. else
  1507. {
  1508. fthrow ( NICE::Exception, "Restoring of VecClassifiers is not implemented yet!" );
  1509. /* if ( vclassifier == NULL )
  1510. vclassifier = new OBJREC::VecClassifier();
  1511. vclassifier->restore(is, format); */
  1512. }
  1513. is >> tmp; // end of block
  1514. tmp = this->removeEndTag ( tmp );
  1515. }
  1516. else if ( tmp.compare("forbidden_classesTrain") == 0 )
  1517. {
  1518. is >> tmp; // size
  1519. int forbClTrainSize ( 0 );
  1520. is >> forbClTrainSize;
  1521. forbidden_classesTrain.clear();
  1522. if ( b_restoreVerbose )
  1523. std::cerr << "restore forbidden_classesTrain with size: " << forbClTrainSize << std::endl;
  1524. if ( forbClTrainSize > 0 )
  1525. {
  1526. if ( b_restoreVerbose )
  1527. std::cerr << " restore forbidden_classesTrain" << std::endl;
  1528. for (int i = 0; i < forbClTrainSize; i++)
  1529. {
  1530. int classNo;
  1531. is >> classNo;
  1532. forbidden_classesTrain.insert ( classNo );
  1533. }
  1534. }
  1535. else
  1536. {
  1537. if ( b_restoreVerbose )
  1538. std::cerr << " skip restoring forbidden_classesTrain" << std::endl;
  1539. }
  1540. is >> tmp; // end of block
  1541. tmp = this->removeEndTag ( tmp );
  1542. }
  1543. else if ( tmp.compare("forbidden_classesActiveLearning") == 0 )
  1544. {
  1545. is >> tmp; // size
  1546. int forbClALSize ( 0 );
  1547. is >> forbClALSize;
  1548. forbidden_classesActiveLearning.clear();
  1549. if ( b_restoreVerbose )
  1550. std::cerr << "restore forbidden_classesActiveLearning with size: " << forbClALSize << std::endl;
  1551. if ( forbClALSize > 0 )
  1552. {
  1553. if ( b_restoreVerbose )
  1554. std::cerr << " restore forbidden_classesActiveLearning" << std::endl;
  1555. for (int i = 0; i < forbClALSize; i++)
  1556. {
  1557. int classNo;
  1558. is >> classNo;
  1559. forbidden_classesActiveLearning.insert ( classNo );
  1560. }
  1561. }
  1562. else
  1563. {
  1564. if ( b_restoreVerbose )
  1565. std::cerr << " skip restoring forbidden_classesActiveLearning" << std::endl;
  1566. }
  1567. is >> tmp; // end of block
  1568. tmp = this->removeEndTag ( tmp );
  1569. }
  1570. else if ( tmp.compare("classesInUse") == 0 )
  1571. {
  1572. is >> tmp; // size
  1573. int clInUseSize ( 0 );
  1574. is >> clInUseSize;
  1575. classesInUse.clear();
  1576. if ( b_restoreVerbose )
  1577. std::cerr << "restore classesInUse with size: " << clInUseSize << std::endl;
  1578. if ( clInUseSize > 0 )
  1579. {
  1580. if ( b_restoreVerbose )
  1581. std::cerr << " restore classesInUse" << std::endl;
  1582. for (int i = 0; i < clInUseSize; i++)
  1583. {
  1584. int classNo;
  1585. is >> classNo;
  1586. classesInUse.insert ( classNo );
  1587. }
  1588. }
  1589. else
  1590. {
  1591. if ( b_restoreVerbose )
  1592. std::cerr << " skip restoring classesInUse" << std::endl;
  1593. }
  1594. is >> tmp; // end of block
  1595. tmp = this->removeEndTag ( tmp );
  1596. }
  1597. else if ( tmp.compare("numberOfClasses") == 0 )
  1598. {
  1599. is >> numberOfClasses;
  1600. is >> tmp; // end of block
  1601. tmp = this->removeEndTag ( tmp );
  1602. }
  1603. else if ( tmp.compare("read_classifier") == 0 )
  1604. {
  1605. is >> read_classifier;
  1606. is >> tmp; // end of block
  1607. tmp = this->removeEndTag ( tmp );
  1608. }
  1609. else if ( tmp.compare("save_classifier") == 0 )
  1610. {
  1611. is >> save_classifier;
  1612. is >> tmp; // end of block
  1613. tmp = this->removeEndTag ( tmp );
  1614. }
  1615. else if ( tmp.compare("cache") == 0 )
  1616. {
  1617. is >> cache;
  1618. is >> tmp; // end of block
  1619. tmp = this->removeEndTag ( tmp );
  1620. }
  1621. else if ( tmp.compare("resultdir") == 0 )
  1622. {
  1623. is >> resultdir;
  1624. is >> tmp; // end of block
  1625. tmp = this->removeEndTag ( tmp );
  1626. }
  1627. //TODO newTrainExamples
  1628. ///////////////////////////////
  1629. // SEGMENTATION STUFF //
  1630. ///////////////////////////////
  1631. //TODO regionSeg
  1632. else if ( tmp.compare("s_rsMethode") == 0 )
  1633. {
  1634. is >> this->s_rsMethode;
  1635. // theoretically, we should properly store and restore the regionSeg object. However, its parent class does not provide
  1636. // a Persistent interface yet. Hence, we perform this tiny workaround which works, since regionSeg is not changed over time...
  1637. // only be aware of parameters originally set via config...
  1638. is >> tmp; // end of block
  1639. tmp = this->removeEndTag ( tmp );
  1640. }
  1641. //NOTE regionSeg seems really important to keep track off
  1642. else if ( tmp.compare("reuseSegmentation") == 0 )
  1643. {
  1644. is >> reuseSegmentation;
  1645. is >> tmp; // end of block
  1646. tmp = this->removeEndTag ( tmp );
  1647. }
  1648. else if ( tmp.compare("queriedRegions") == 0 )
  1649. {
  1650. is >> tmp; // size
  1651. int queriedRegionsSize ( 0 );
  1652. is >> queriedRegionsSize;
  1653. queriedRegions.clear();
  1654. if ( b_restoreVerbose )
  1655. std::cerr << "restore queriedRegions with size: " << queriedRegionsSize << std::endl;
  1656. for ( int i = 0; i < queriedRegionsSize; i++ )
  1657. {
  1658. // restore key
  1659. std::string key;
  1660. is >> key;
  1661. // restore values -- inner loop over sets
  1662. is >> tmp; // size
  1663. int regionsOfImgSize ( 0 );
  1664. is >> regionsOfImgSize;
  1665. std::set< int > regionsOfImg;
  1666. regionsOfImg.clear();
  1667. for (int i = 0; i < regionsOfImgSize; i++)
  1668. {
  1669. int idxRegion;
  1670. is >> idxRegion;
  1671. regionsOfImg.insert ( idxRegion );
  1672. }
  1673. queriedRegions.insert ( std::pair<std::string, std::set< int > > ( key, regionsOfImg ) );
  1674. }
  1675. is >> tmp; // end of block
  1676. tmp = this->removeEndTag ( tmp );
  1677. }
  1678. //
  1679. //TODO currentRegionToQuery
  1680. //
  1681. ///////////////////////////////
  1682. // PARENT OBJECT //
  1683. ///////////////////////////////
  1684. else if ( tmp.compare("SemSegNovelty--Parent") == 0 )
  1685. {
  1686. // restore parent object
  1687. SemanticSegmentation::restore(is);
  1688. }
  1689. else
  1690. {
  1691. std::cerr << "WARNING -- unexpected SemSegNovelty object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1692. throw;
  1693. }
  1694. // INSTANTIATE (YET) NON-RESTORABLE OBJECTS
  1695. //TODO destructor of regionSeg is non-virtual so far - change this accordingly!
  1696. if ( this->regionSeg != NULL )
  1697. delete this->regionSeg;
  1698. if( this->s_rsMethode == "none" )
  1699. {
  1700. this->regionSeg = NULL;
  1701. }
  1702. else
  1703. {
  1704. //NOTE using an empty config file might not be save...
  1705. NICE::Config tmpConfEmpty;
  1706. RegionSegmentationMethod *tmpRegionSeg = GenericRegionSegmentationMethodSelection::selectRegionSegmentationMethod( &tmpConfEmpty, this->s_rsMethode );
  1707. if ( reuseSegmentation )
  1708. this->regionSeg = new RSCache ( &tmpConfEmpty, tmpRegionSeg );
  1709. else
  1710. this->regionSeg = tmpRegionSeg;
  1711. }
  1712. // done restoration
  1713. }
  1714. }
  1715. else
  1716. {
  1717. std::cerr << "SemSegNovelty::restore -- InStream not initialized - restoring not possible!" << std::endl;
  1718. throw;
  1719. }
  1720. }
  1721. void SemSegNovelty::store ( std::ostream & os, int format ) const
  1722. {
  1723. if (os.good())
  1724. {
  1725. // show starting point
  1726. os << this->createStartTag( "SemSegNovelty" ) << std::endl;
  1727. ///////////////////////////////
  1728. // FEATURE EXTRACTION //
  1729. ///////////////////////////////
  1730. os << this->createStartTag( "featExtract" ) << std::endl;
  1731. featExtract->store ( os );
  1732. os << this->createStartTag( "featExtract" ) << std::endl;
  1733. os << this->createStartTag( "trainWsize" ) << std::endl;
  1734. os << this->trainWSize << std::endl;
  1735. os << this->createStartTag( "trainWsize" ) << std::endl;
  1736. os << this->createStartTag( "whs" ) << std::endl;
  1737. os << this->whs << std::endl;
  1738. os << this->createStartTag( "whs" ) << std::endl;
  1739. os << this->createStartTag( "testWSize" ) << std::endl;
  1740. os << this->testWSize << std::endl;
  1741. os << this->createStartTag( "testWSize" ) << std::endl;
  1742. ///////////////////////////////
  1743. // NOVELTY COMPUTATION //
  1744. ///////////////////////////////
  1745. os << this->createStartTag( "noveltyMethod" ) << std::endl;
  1746. os << this->noveltyMethod << std::endl;
  1747. os << this->createStartTag( "noveltyMethod" ) << std::endl;
  1748. os << this->createStartTag( "noveltyMethodString" ) << std::endl;
  1749. os << this->noveltyMethodString << std::endl;
  1750. os << this->createStartTag( "noveltyMethodString" ) << std::endl;
  1751. os << this->createStartTag( "globalMaxUncert" ) << std::endl;
  1752. os << this->globalMaxUncert << std::endl;
  1753. os << this->createStartTag( "globalMaxUncert" ) << std::endl;
  1754. os << this->createStartTag( "mostNoveltyWithMaxScores" ) << std::endl;
  1755. os << this->mostNoveltyWithMaxScores << std::endl;
  1756. os << this->createStartTag( "mostNoveltyWithMaxScores" ) << std::endl;
  1757. os << this->createStartTag( "findMaximumUncert" ) << std::endl;
  1758. os << this->findMaximumUncert << std::endl;
  1759. os << this->createStartTag( "findMaximumUncert" ) << std::endl;
  1760. //TODO maskedImg
  1761. os << this->createStartTag( "b_visualizeALimages" ) << std::endl;
  1762. os << this->b_visualizeALimages << std::endl;
  1763. os << this->createStartTag( "b_visualizeALimages" ) << std::endl;
  1764. ///////////////////////////////
  1765. // CLASSIFICATION STUFF //
  1766. ///////////////////////////////
  1767. os << this->createStartTag( "classifierString" ) << std::endl;
  1768. os << this->classifierString << std::endl;
  1769. os << this->createStartTag( "classifierString" ) << std::endl;
  1770. os << this->createStartTag( "classifier" ) << std::endl;
  1771. if ( this->classifier != NULL )
  1772. {
  1773. os << "NOTNULL" << std::endl;
  1774. classifier->store ( os, format );
  1775. }
  1776. else
  1777. {
  1778. os << "NULL" << std::endl;
  1779. }
  1780. os << this->createEndTag( "classifier" ) << std::endl;
  1781. //
  1782. os << this->createStartTag( "vclassifier" ) << std::endl;
  1783. if ( this->classifier != NULL )
  1784. {
  1785. os << "NOTNULL" << std::endl;
  1786. vclassifier->store ( os, format );
  1787. }
  1788. else
  1789. {
  1790. os << "NULL" << std::endl;
  1791. }
  1792. os << this->createEndTag( "vclassifier" ) << std::endl;
  1793. os << this->createStartTag( "forbidden_classesTrain" ) << std::endl;
  1794. os << "size: " << forbidden_classesTrain.size() << std::endl;
  1795. for ( std::set< int >::const_iterator itForbClassTrain = forbidden_classesTrain.begin();
  1796. itForbClassTrain != forbidden_classesTrain.end();
  1797. itForbClassTrain++
  1798. )
  1799. {
  1800. os << *itForbClassTrain << " " << std::endl;
  1801. }
  1802. os << this->createEndTag( "forbidden_classesTrain" ) << std::endl;
  1803. //
  1804. os << this->createStartTag( "forbidden_classesActiveLearning" ) << std::endl;
  1805. os << "size: " << forbidden_classesActiveLearning.size() << std::endl;
  1806. for ( std::set< int >::const_iterator itForbClassAL = forbidden_classesActiveLearning.begin();
  1807. itForbClassAL != forbidden_classesActiveLearning.end();
  1808. itForbClassAL++
  1809. )
  1810. {
  1811. os << *itForbClassAL << " " << std::endl;
  1812. }
  1813. os << this->createEndTag( "forbidden_classesActiveLearning" ) << std::endl;
  1814. //
  1815. os << this->createStartTag( "classesInUse" ) << std::endl;
  1816. os << "size: " << classesInUse.size() << std::endl;
  1817. for ( std::set< int >::const_iterator itClassesInUse = classesInUse.begin();
  1818. itClassesInUse != classesInUse.end();
  1819. itClassesInUse++
  1820. )
  1821. {
  1822. os << *itClassesInUse << " " << std::endl;
  1823. }
  1824. os << this->createEndTag( "classesInUse" ) << std::endl;
  1825. os << this->createStartTag( "numberOfClasses" ) << std::endl;
  1826. os << this->numberOfClasses << std::endl;
  1827. os << this->createStartTag( "numberOfClasses" ) << std::endl;
  1828. os << this->createStartTag( "read_classifier" ) << std::endl;
  1829. os << this->read_classifier << std::endl;
  1830. os << this->createStartTag( "read_classifier" ) << std::endl;
  1831. os << this->createStartTag( "save_classifier" ) << std::endl;
  1832. os << this->save_classifier << std::endl;
  1833. os << this->createStartTag( "save_classifier" ) << std::endl;
  1834. os << this->createStartTag( "cache" ) << std::endl;
  1835. os << this->cache << std::endl;
  1836. os << this->createStartTag( "cache" ) << std::endl;
  1837. os << this->createStartTag( "resultdir" ) << std::endl;
  1838. os << this->resultdir << std::endl;
  1839. os << this->createStartTag( "resultdir" ) << std::endl;
  1840. //TODO newTrainExamples
  1841. ///////////////////////////////
  1842. // SEGMENTATION STUFF //
  1843. ///////////////////////////////
  1844. // theoretically, we should properly store and restore the regionSeg object. However, its parent class does not provide
  1845. // a Persistent interface yet. Hence, we perform this tiny workaround which works, since regionSeg is not changed over time...
  1846. // only be aware of parameters originally set via config...
  1847. os << this->createStartTag( "s_rsMethode" ) << std::endl;
  1848. os << this->s_rsMethode << std::endl;
  1849. os << this->createStartTag( "s_rsMethode" ) << std::endl;
  1850. os << this->createStartTag( "reuseSegmentation" ) << std::endl;
  1851. os << this->reuseSegmentation << std::endl;
  1852. os << this->createStartTag( "reuseSegmentation" ) << std::endl;
  1853. os << this->createStartTag( "queriedRegions" ) << std::endl;
  1854. os << "size: " << queriedRegions.size() << std::endl;
  1855. std::map< std::string, std::set< int > >::const_iterator itQueriedRegions = queriedRegions.begin();
  1856. for ( uint i = 0; i < queriedRegions.size(); i++ )
  1857. {
  1858. // store key
  1859. os << itQueriedRegions->first << std::endl;
  1860. // store values -- inner loop over sets
  1861. os << "size: " << ( itQueriedRegions->second ).size() << std::endl;
  1862. for ( std::set< int >::const_iterator itRegionsOfImg = ( itQueriedRegions->second ).begin();
  1863. itRegionsOfImg != ( itQueriedRegions->second ).end();
  1864. itRegionsOfImg++
  1865. )
  1866. {
  1867. os << *itRegionsOfImg << " " << std::endl;
  1868. }
  1869. itQueriedRegions++;
  1870. }
  1871. os << this->createStartTag( "queriedRegions" ) << std::endl;
  1872. //
  1873. //TODO currentRegionToQuery
  1874. ///////////////////////////////
  1875. // PARENT OBJECT //
  1876. ///////////////////////////////
  1877. os << this->createStartTag( "SemSegNovelty--Parent" ) << std::endl;
  1878. SemanticSegmentation::store(os);
  1879. os << this->createStartTag( "SemSegNovelty--Parent" ) << std::endl;
  1880. // done
  1881. os << this->createEndTag( "SemSegNovelty" ) << std::endl;
  1882. }
  1883. else
  1884. {
  1885. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1886. }
  1887. }
  1888. void SemSegNovelty::clear ()
  1889. {
  1890. //TODO
  1891. }