SemSegNovelty.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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 <vislearning/classifier/fpclassifier/gphik/FPCGPHIK.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 FPCGPHIK ( 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 (
  401. CachedExample *ce,
  402. NICE::ImageT<int> & segresult,
  403. NICE::MultiChannelImageT<double> & probabilities )
  404. {
  405. Timer timer;
  406. timer.start();
  407. //segResult contains the GT labels when this method is called
  408. // we simply store them in labels, to have an easy access to the GT information lateron
  409. NICE::ImageT<int> labels = segresult;
  410. //just to be sure that we do not have a GT-biased result :)
  411. segresult.set(0);
  412. int featdim = -1;
  413. std::string currentFile = Globals::getCurrentImgFN();
  414. int xsize, ysize;
  415. ce->getImageSize ( xsize, ysize );
  416. probabilities.reInit( xsize, ysize, this->classNames->getMaxClassno() + 1);
  417. probabilities.setAll ( -std::numeric_limits<double>::max() );
  418. NICE::ColorImage img;
  419. try {
  420. img = ColorImage ( currentFile );
  421. } catch ( Exception ) {
  422. cerr << "SemSegNovelty: error opening image file <" << currentFile << ">" << endl;
  423. return;
  424. }
  425. // MultiChannelImageT<double> m_CurrentImageFeatures;
  426. // extract features
  427. m_CurrentImageFeatures.freeData();
  428. featExtract->getFeats ( img, m_CurrentImageFeatures );
  429. featdim = m_CurrentImageFeatures.channels();
  430. m_CurrentImageFeatures.addChannel(featdim);
  431. for (int c = 0; c < featdim; c++)
  432. {
  433. ImageT<double> tmp = m_CurrentImageFeatures[c];
  434. ImageT<double> tmp2 = m_CurrentImageFeatures[c+featdim];
  435. NICE::FilterT<double, double, double>::gradientStrength (tmp, tmp2);
  436. }
  437. featdim += featdim;
  438. // compute integral images
  439. for ( int c = 0; c < featdim; c++ )
  440. {
  441. m_CurrentImageFeatures.calcIntegral ( c );
  442. }
  443. timer.stop();
  444. std::cout << "AL time for preparation: " << timer.getLastAbsolute() << std::endl;
  445. timer.start();
  446. //classification results currently only needed to be computed separately if we use the vclassifier, i.e., the nearest neighbor used
  447. // for the "novel feature learning" approach
  448. //in all other settings, such as active sem seg in general, we do this within the novelty-computation-methods
  449. if ( classifier == NULL )
  450. {
  451. this->computeClassificationResults( m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim);
  452. }
  453. // timer.stop();
  454. //
  455. // std::cerr << "classification results computed" << std::endl;
  456. FloatImage noveltyImage ( xsize, ysize );
  457. noveltyImage.set ( 0.0 );
  458. switch (noveltyMethod)
  459. {
  460. case GPVARIANCE:
  461. {
  462. this->computeNoveltyByVariance( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  463. break;
  464. }
  465. case GPUNCERTAINTY:
  466. {
  467. this->computeNoveltyByGPUncertainty( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  468. break;
  469. }
  470. case GPMINMEAN:
  471. {
  472. std::cerr << "compute novelty using the minimum mean" << std::endl;
  473. this->computeNoveltyByGPMean( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  474. break;
  475. }
  476. case GPMEANRATIO:
  477. {
  478. this->computeNoveltyByGPMeanRatio( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  479. break;
  480. }
  481. case GPWEIGHTALL:
  482. {
  483. this->computeNoveltyByGPWeightAll( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  484. break;
  485. }
  486. case GPWEIGHTRATIO:
  487. {
  488. this->computeNoveltyByGPWeightRatio( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  489. break;
  490. }
  491. case RANDOM:
  492. {
  493. this->computeNoveltyByRandom( noveltyImage, m_CurrentImageFeatures, segresult, probabilities, xsize, ysize, featdim );
  494. break;
  495. }
  496. default:
  497. {
  498. //do nothing, keep the image constant to 0.0
  499. break;
  500. }
  501. }
  502. timer.stop();
  503. std::cout << "AL time for novelty score computation: " << timer.getLastAbsolute() << std::endl;
  504. if (b_visualizeALimages)
  505. {
  506. ColorImage imgrgbTmp (xsize, ysize);
  507. ICETools::convertToRGB ( noveltyImage, imgrgbTmp );
  508. showImage(imgrgbTmp, "Novelty Image without Region Segmentation");
  509. }
  510. timer.start();
  511. //Regionen ermitteln
  512. if(regionSeg != NULL)
  513. {
  514. NICE::Matrix mask;
  515. int amountRegions = regionSeg->segRegions ( img, mask );
  516. //compute probs per region
  517. std::vector<std::vector<double> > regionProb(amountRegions, std::vector<double>(probabilities.channels(), -std::numeric_limits<double>::max() ));
  518. std::vector<double> regionNoveltyMeasure (amountRegions, 0.0);
  519. std::vector<int> regionCounter(amountRegions, 0);
  520. std::vector<int> regionCounterNovelty(amountRegions, 0);
  521. for ( int y = 0; y < ysize; y += testWSize) //y++)
  522. {
  523. for (int x = 0; x < xsize; x += testWSize) //x++)
  524. {
  525. int r = mask(x,y);
  526. regionCounter[r]++;
  527. for(int j = 0; j < probabilities.channels(); j++)
  528. {
  529. if( regionProb[r][j] == -std::numeric_limits<double>::max() )
  530. regionProb[r][j] = 0.0f;
  531. regionProb[r][j] += probabilities ( x, y, j );
  532. }
  533. if ( forbidden_classesActiveLearning.find( labels(x,y) ) == forbidden_classesActiveLearning.end() )
  534. {
  535. //count the amount of "novelty" for the corresponding region
  536. regionNoveltyMeasure[r] += noveltyImage(x,y);
  537. regionCounterNovelty[r]++;
  538. }
  539. }
  540. }
  541. //find best class per region
  542. std::vector<int> bestClassPerRegion(amountRegions,0);
  543. double maxNoveltyScore = -numeric_limits<double>::max();
  544. if (!mostNoveltyWithMaxScores)
  545. {
  546. maxNoveltyScore = numeric_limits<double>::max();
  547. }
  548. int maxUncertRegion = -1;
  549. //loop over all regions and compute averaged novelty scores
  550. for(int r = 0; r < amountRegions; r++)
  551. {
  552. //check for the most plausible class per region
  553. double maxval = -numeric_limits<double>::max();
  554. //loop over all classes
  555. for(int c = 0; c < probabilities.channels(); c++)
  556. {
  557. regionProb[r][c] /= regionCounter[r];
  558. if( (maxval < regionProb[r][c]) ) //&& (regionProb[r][c] != 0.0) )
  559. {
  560. maxval = regionProb[r][c];
  561. bestClassPerRegion[r] = c;
  562. }
  563. }
  564. //if the region only contains unvalid information (e.g., background) skip it
  565. if (regionCounterNovelty[r] == 0)
  566. {
  567. continue;
  568. }
  569. //normalize summed novelty scores to region size
  570. regionNoveltyMeasure[r] /= regionCounterNovelty[r];
  571. //did we find a region that has a higher score as the most novel region known so far within this image?
  572. if( ( mostNoveltyWithMaxScores && (maxNoveltyScore < regionNoveltyMeasure[r]) ) // if we look for large novelty scores, e.g., variance
  573. || ( !mostNoveltyWithMaxScores && (maxNoveltyScore > regionNoveltyMeasure[r]) ) ) // if we look for small novelty scores, e.g., min mean
  574. {
  575. //did we already query a region of this image? -- and it was this specific region
  576. if ( (queriedRegions.find( currentFile ) != queriedRegions.end() ) && ( queriedRegions[currentFile].find(r) != queriedRegions[currentFile].end() ) )
  577. {
  578. continue;
  579. }
  580. else //only accept the region as novel if we never queried it before
  581. {
  582. maxNoveltyScore = regionNoveltyMeasure[r];
  583. maxUncertRegion = r;
  584. }
  585. }
  586. }
  587. // after finding the most novel region for the current image, check whether this region is also the most novel with respect
  588. // to all previously seen test images
  589. // if so, store the corresponding features, since we want to "actively" query them to incorporate useful information
  590. if(findMaximumUncert)
  591. {
  592. if( ( mostNoveltyWithMaxScores && (maxNoveltyScore > globalMaxUncert) )
  593. || ( !mostNoveltyWithMaxScores && (maxNoveltyScore < globalMaxUncert) ) )
  594. {
  595. //current most novel region of the image has "higher" novelty score then previous most novel region of all test images worked on so far
  596. // -> save new important features of this region
  597. Examples examples;
  598. for ( int y = 0; y < ysize; y += testWSize )
  599. {
  600. for ( int x = 0; x < xsize; x += testWSize)
  601. {
  602. if(mask(x,y) == maxUncertRegion)
  603. {
  604. int classnoTmp = labels(x,y);
  605. if ( forbidden_classesActiveLearning.find(classnoTmp) != forbidden_classesActiveLearning.end() )
  606. continue;
  607. Example t_Example(NULL, x, y);
  608. t_Example.vec = NULL;
  609. t_Example.svec = new SparseVector ( featdim );
  610. for ( int f = 0; f < featdim; f++ )
  611. {
  612. // double val = ( *example.svec ) [f];
  613. double val = m_CurrentImageFeatures.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  614. if ( val > 1e-10 )
  615. ( *t_Example.svec ) [f] = val;
  616. }
  617. examples.push_back ( pair<int, Example> ( classnoTmp, t_Example ) );
  618. }
  619. }
  620. }
  621. if(examples.size() > 0)
  622. {
  623. std::cerr << "found " << examples.size() << " new examples in the queried region" << std::endl << std::endl;
  624. // sauber aufräumen
  625. for( int i=0; i< newTrainExamples.size(); i++)
  626. {
  627. delete newTrainExamples.at(i).second.svec;
  628. newTrainExamples.at(i).second.svec = NULL;
  629. }
  630. newTrainExamples.clear();
  631. newTrainExamples = examples;
  632. globalMaxUncert = maxNoveltyScore;
  633. //prepare for later visualization
  634. // if (b_visualizeALimages)
  635. visualizeRegion(img,mask,maxUncertRegion,maskedImg);
  636. }
  637. else
  638. {
  639. std::cerr << "the queried region has no valid information" << std::endl << std::endl;
  640. }
  641. //save filename and region index
  642. currentRegionToQuery.first = currentFile;
  643. currentRegionToQuery.second = maxUncertRegion;
  644. }
  645. }
  646. //write back best results per region
  647. //i.e., write normalized novelty scores for every region into the novelty image
  648. for ( int y = 0; y < ysize; y++)
  649. {
  650. for (int x = 0; x < xsize; x++)
  651. {
  652. int r = mask(x,y);
  653. for(int j = 0; j < probabilities.channels(); j++)
  654. {
  655. probabilities ( x, y, j ) = regionProb[r][j];
  656. }
  657. segresult(x,y) = bestClassPerRegion[r];
  658. // write novelty scores for every segment into the "final" image
  659. noveltyImage(x,y) = regionNoveltyMeasure[r];
  660. }
  661. }
  662. } // if regionSeg != null
  663. timer.stop();
  664. std::cout << "AL time for determination of novel regions: " << timer.getLastAbsolute() << std::endl;
  665. if (b_visualizeALimages)
  666. {
  667. timer.start();
  668. std::stringstream out;
  669. std::vector< std::string > list2;
  670. StringTools::split ( Globals::getCurrentImgFN (), '/', list2 );
  671. out << resultdir << "/" << list2.back();
  672. noveltyImage.writeRaw(out.str() + "_run_" + NICE::intToString(this->iterationCountSuffix) + "_" + noveltyMethodString+".rawfloat");
  673. ColorImage imgrgb ( xsize, ysize );
  674. ICETools::convertToRGB ( noveltyImage, imgrgb );
  675. showImage(imgrgb, "Novelty Image");
  676. timer.stop();
  677. cout << "AL time for writing the raw novelty image: " << timer.getLastAbsolute() << endl;
  678. }
  679. }
  680. inline void SemSegNovelty::computeClassificationResults( const NICE::MultiChannelImageT<double> & feats,
  681. NICE::ImageT<int> & segresult,
  682. NICE::MultiChannelImageT<double> & probabilities,
  683. const int & xsize,
  684. const int & ysize,
  685. const int & featdim
  686. )
  687. {
  688. std::cerr << "featdim: " << featdim << std::endl;
  689. if ( classifier != NULL )
  690. {
  691. #pragma omp parallel for
  692. for ( int y = 0; y < ysize; y += testWSize )
  693. {
  694. Example example;
  695. example.vec = NULL;
  696. example.svec = new SparseVector ( featdim );
  697. for ( int x = 0; x < xsize; x += testWSize)
  698. {
  699. for ( int f = 0; f < featdim; f++ )
  700. {
  701. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  702. if ( val > 1e-10 )
  703. ( *example.svec ) [f] = val;
  704. }
  705. example.svec->normalize();
  706. ClassificationResult cr = classifier->classify ( example );
  707. int xs = std::max(0, x - testWSize/2);
  708. int xe = std::min(xsize - 1, x + testWSize/2);
  709. int ys = std::max(0, y - testWSize/2);
  710. int ye = std::min(ysize - 1, y + testWSize/2);
  711. for (int yl = ys; yl <= ye; yl++)
  712. {
  713. for (int xl = xs; xl <= xe; xl++)
  714. {
  715. for ( int j = 0 ; j < cr.scores.size(); j++ )
  716. {
  717. probabilities ( xl, yl, j ) = cr.scores[j];
  718. }
  719. segresult ( xl, yl ) = cr.classno;
  720. }
  721. }
  722. example.svec->clear();
  723. }
  724. delete example.svec;
  725. example.svec = NULL;
  726. }
  727. }
  728. else //vclassifier
  729. {
  730. std::cerr << "compute classification results with vclassifier" << std::endl;
  731. #pragma omp parallel for
  732. for ( int y = 0; y < ysize; y += testWSize )
  733. {
  734. for ( int x = 0; x < xsize; x += testWSize)
  735. {
  736. NICE::Vector v(featdim);
  737. for ( int f = 0; f < featdim; f++ )
  738. {
  739. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  740. v[f] = val;
  741. }
  742. v.normalizeL1();
  743. ClassificationResult cr = vclassifier->classify ( v );
  744. int xs = std::max(0, x - testWSize/2);
  745. int xe = std::min(xsize - 1, x + testWSize/2);
  746. int ys = std::max(0, y - testWSize/2);
  747. int ye = std::min(ysize - 1, y + testWSize/2);
  748. for (int yl = ys; yl <= ye; yl++)
  749. {
  750. for (int xl = xs; xl <= xe; xl++)
  751. {
  752. for ( int j = 0 ; j < cr.scores.size(); j++ )
  753. {
  754. probabilities ( xl, yl, j ) = cr.scores[j];
  755. }
  756. segresult ( xl, yl ) = cr.classno;
  757. }
  758. }
  759. }
  760. }
  761. }
  762. }
  763. // compute novelty images depending on the strategy chosen
  764. void SemSegNovelty::computeNoveltyByRandom( NICE::FloatImage & noveltyImage,
  765. const NICE::MultiChannelImageT<double> & feats,
  766. NICE::ImageT<int> & segresult,
  767. NICE::MultiChannelImageT<double> & probabilities,
  768. const int & xsize, const int & ysize, const int & featdim )
  769. {
  770. #pragma omp parallel for
  771. for ( int y = 0; y < ysize; y += testWSize )
  772. {
  773. Example example;
  774. example.vec = NULL;
  775. example.svec = new SparseVector ( featdim );
  776. for ( int x = 0; x < xsize; x += testWSize)
  777. {
  778. for ( int f = 0; f < featdim; f++ )
  779. {
  780. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  781. if ( val > 1e-10 )
  782. ( *example.svec ) [f] = val;
  783. }
  784. example.svec->normalize();
  785. ClassificationResult cr = classifier->classify ( example );
  786. int xs = std::max(0, x - testWSize/2);
  787. int xe = std::min(xsize - 1, x + testWSize/2);
  788. int ys = std::max(0, y - testWSize/2);
  789. int ye = std::min(ysize - 1, y + testWSize/2);
  790. double randVal = randDouble();
  791. for (int yl = ys; yl <= ye; yl++)
  792. {
  793. for (int xl = xs; xl <= xe; xl++)
  794. {
  795. for ( int j = 0 ; j < cr.scores.size(); j++ )
  796. {
  797. probabilities ( xl, yl, j ) = cr.scores[j];
  798. }
  799. segresult ( xl, yl ) = cr.classno;
  800. noveltyImage ( xl, yl ) = randVal;
  801. }
  802. }
  803. }
  804. }
  805. }
  806. void SemSegNovelty::computeNoveltyByVariance( NICE::FloatImage & noveltyImage,
  807. const NICE::MultiChannelImageT<double> & feats,
  808. NICE::ImageT<int> & segresult,
  809. NICE::MultiChannelImageT<double> & probabilities,
  810. const int & xsize, const int & ysize, const int & featdim )
  811. {
  812. #pragma omp parallel for
  813. for ( int y = 0; y < ysize; y += testWSize )
  814. {
  815. Example example;
  816. example.vec = NULL;
  817. example.svec = new SparseVector ( featdim );
  818. for ( int x = 0; x < xsize; x += testWSize)
  819. {
  820. for ( int f = 0; f < featdim; f++ )
  821. {
  822. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  823. if ( val > 1e-10 )
  824. ( *example.svec ) [f] = val;
  825. }
  826. example.svec->normalize();
  827. ClassificationResult cr = classifier->classify ( example );
  828. int xs = std::max(0, x - testWSize/2);
  829. int xe = std::min(xsize - 1, x + testWSize/2);
  830. int ys = std::max(0, y - testWSize/2);
  831. int ye = std::min(ysize - 1, y + testWSize/2);
  832. for (int yl = ys; yl <= ye; yl++)
  833. {
  834. for (int xl = xs; xl <= xe; xl++)
  835. {
  836. for ( int j = 0 ; j < cr.scores.size(); j++ )
  837. {
  838. probabilities ( xl, yl, j ) = cr.scores[j];
  839. }
  840. segresult ( xl, yl ) = cr.classno;
  841. noveltyImage ( xl, yl ) = cr.uncertainty;
  842. }
  843. }
  844. example.svec->clear();
  845. }
  846. delete example.svec;
  847. example.svec = NULL;
  848. }
  849. }
  850. void SemSegNovelty::computeNoveltyByGPUncertainty( NICE::FloatImage & noveltyImage,
  851. const NICE::MultiChannelImageT<double> & feats,
  852. NICE::ImageT<int> & segresult,
  853. NICE::MultiChannelImageT<double> & probabilities,
  854. const int & xsize, const int & ysize, const int & featdim )
  855. {
  856. double gpNoise = 0.01;
  857. //TODO getMethod for GPHIK
  858. //conf->gD("GPHIK", "noise", 0.01);
  859. #pragma omp parallel for
  860. for ( int y = 0; y < ysize; y += testWSize )
  861. {
  862. Example example;
  863. example.vec = NULL;
  864. example.svec = new SparseVector ( featdim );
  865. for ( int x = 0; x < xsize; x += testWSize)
  866. {
  867. for ( int f = 0; f < featdim; f++ )
  868. {
  869. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  870. if ( val > 1e-10 )
  871. ( *example.svec ) [f] = val;
  872. }
  873. example.svec->normalize();
  874. ClassificationResult cr = classifier->classify ( example );
  875. double maxMeanAbs ( 0.0 );
  876. for ( int j = 0 ; j < cr.scores.size(); j++ )
  877. {
  878. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  879. {
  880. continue;
  881. }
  882. //check for larger abs mean
  883. if (abs(cr.scores[j]) > maxMeanAbs)
  884. {
  885. maxMeanAbs = abs(cr.scores[j]);
  886. }
  887. }
  888. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  889. //compute the heuristic GP-UNCERTAINTY, as proposed by Kapoor et al. in IJCV 2010
  890. // GP-UNCERTAINTY : |mean| / sqrt(var^2 + gpnoise^2)
  891. double gpUncertaintyVal = maxMeanAbs*firstTerm; //firstTerm = 1.0 / sqrt(r.uncertainty+gpNoise))
  892. int xs = std::max(0, x - testWSize/2);
  893. int xe = std::min(xsize - 1, x + testWSize/2);
  894. int ys = std::max(0, y - testWSize/2);
  895. int ye = std::min(ysize - 1, y + testWSize/2);
  896. for (int yl = ys; yl <= ye; yl++)
  897. {
  898. for (int xl = xs; xl <= xe; xl++)
  899. {
  900. for ( int j = 0 ; j < cr.scores.size(); j++ )
  901. {
  902. probabilities ( xl, yl, j ) = cr.scores[j];
  903. }
  904. segresult ( xl, yl ) = cr.classno;
  905. noveltyImage ( xl, yl ) = gpUncertaintyVal;
  906. }
  907. }
  908. example.svec->clear();
  909. }
  910. delete example.svec;
  911. example.svec = NULL;
  912. }
  913. }
  914. void SemSegNovelty::computeNoveltyByGPMean( NICE::FloatImage & noveltyImage,
  915. const NICE::MultiChannelImageT<double> & feats,
  916. NICE::ImageT<int> & segresult,
  917. NICE::MultiChannelImageT<double> & probabilities,
  918. const int & xsize, const int & ysize, const int & featdim )
  919. {
  920. double gpNoise = 0.01;
  921. //TODO getMethod for GPHIK
  922. //conf->gD("GPHIK", "noise", 0.01);
  923. #pragma omp parallel for
  924. for ( int y = 0; y < ysize; y += testWSize )
  925. {
  926. Example example;
  927. example.vec = NULL;
  928. example.svec = new SparseVector ( featdim );
  929. for ( int x = 0; x < xsize; x += testWSize)
  930. {
  931. for ( int f = 0; f < featdim; f++ )
  932. {
  933. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  934. if ( val > 1e-10 )
  935. ( *example.svec ) [f] = val;
  936. }
  937. example.svec->normalize();
  938. ClassificationResult cr = classifier->classify ( example );
  939. double minMeanAbs ( numeric_limits<double>::max() );
  940. for ( int j = 0 ; j < probabilities.channels(); j++ )
  941. {
  942. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  943. {
  944. continue;
  945. }
  946. //check whether we found a class with higher smaller abs mean than the current minimum
  947. if (abs( cr.scores[j] ) < minMeanAbs)
  948. {
  949. minMeanAbs = abs(cr.scores[j]);
  950. }
  951. }
  952. // compute results when we take the lowest mean value of all classes
  953. double gpMeanVal = minMeanAbs;
  954. int xs = std::max(0, x - testWSize/2);
  955. int xe = std::min(xsize - 1, x + testWSize/2);
  956. int ys = std::max(0, y - testWSize/2);
  957. int ye = std::min(ysize - 1, y + testWSize/2);
  958. for (int yl = ys; yl <= ye; yl++)
  959. {
  960. for (int xl = xs; xl <= xe; xl++)
  961. {
  962. for ( int j = 0 ; j < cr.scores.size(); j++ )
  963. {
  964. probabilities ( xl, yl, j ) = cr.scores[j];
  965. }
  966. segresult ( xl, yl ) = cr.classno;
  967. noveltyImage ( xl, yl ) = gpMeanVal;
  968. }
  969. }
  970. }
  971. }
  972. }
  973. void SemSegNovelty::computeNoveltyByGPMeanRatio( NICE::FloatImage & noveltyImage,
  974. const NICE::MultiChannelImageT<double> & feats,
  975. NICE::ImageT<int> & segresult,
  976. NICE::MultiChannelImageT<double> & probabilities,
  977. const int & xsize, const int & ysize, const int & featdim )
  978. {
  979. double gpNoise = 0.01;
  980. //TODO getMethod for GPHIK
  981. //conf->gD("GPHIK", "noise", 0.01);
  982. #pragma omp parallel for
  983. for ( int y = 0; y < ysize; y += testWSize )
  984. {
  985. Example example;
  986. example.vec = NULL;
  987. example.svec = new SparseVector ( featdim );
  988. for ( int x = 0; x < xsize; x += testWSize)
  989. {
  990. for ( int f = 0; f < featdim; f++ )
  991. {
  992. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  993. if ( val > 1e-10 )
  994. ( *example.svec ) [f] = val;
  995. }
  996. example.svec->normalize();
  997. ClassificationResult cr = classifier->classify ( example );
  998. double maxMean ( -numeric_limits<double>::max() );
  999. double sndMaxMean ( -numeric_limits<double>::max() );
  1000. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1001. {
  1002. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1003. {
  1004. continue;
  1005. }
  1006. //check for larger mean without abs as well
  1007. if (cr.scores[j] > maxMean)
  1008. {
  1009. sndMaxMean = maxMean;
  1010. maxMean = cr.scores[j];
  1011. }
  1012. // and also for the second highest mean of all classes
  1013. else if (cr.scores[j] > sndMaxMean)
  1014. {
  1015. sndMaxMean = cr.scores[j];
  1016. }
  1017. }
  1018. //look at the difference in the absolut mean values for the most plausible class
  1019. // and the second most plausible class
  1020. double gpMeanRatioVal= maxMean - sndMaxMean;
  1021. int xs = std::max(0, x - testWSize/2);
  1022. int xe = std::min(xsize - 1, x + testWSize/2);
  1023. int ys = std::max(0, y - testWSize/2);
  1024. int ye = std::min(ysize - 1, y + testWSize/2);
  1025. for (int yl = ys; yl <= ye; yl++)
  1026. {
  1027. for (int xl = xs; xl <= xe; xl++)
  1028. {
  1029. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1030. {
  1031. probabilities ( xl, yl, j ) = cr.scores[j];
  1032. }
  1033. segresult ( xl, yl ) = cr.classno;
  1034. noveltyImage ( xl, yl ) = gpMeanRatioVal;
  1035. }
  1036. }
  1037. example.svec->clear();
  1038. }
  1039. delete example.svec;
  1040. example.svec = NULL;
  1041. }
  1042. }
  1043. void SemSegNovelty::computeNoveltyByGPWeightAll( NICE::FloatImage & noveltyImage,
  1044. const NICE::MultiChannelImageT<double> & feats,
  1045. NICE::ImageT<int> & segresult,
  1046. NICE::MultiChannelImageT<double> & probabilities,
  1047. const int & xsize, const int & ysize, const int & featdim )
  1048. {
  1049. double gpNoise = 0.01;
  1050. //TODO getMethod for GPHIK
  1051. //conf->gD("GPHIK", "noise", 0.01);
  1052. #pragma omp parallel for
  1053. for ( int y = 0; y < ysize; y += testWSize )
  1054. {
  1055. Example example;
  1056. example.vec = NULL;
  1057. example.svec = new SparseVector ( featdim );
  1058. for ( int x = 0; x < xsize; x += testWSize)
  1059. {
  1060. for ( int f = 0; f < featdim; f++ )
  1061. {
  1062. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  1063. if ( val > 1e-10 )
  1064. ( *example.svec ) [f] = val;
  1065. }
  1066. example.svec->normalize();
  1067. ClassificationResult cr = classifier->classify ( example );
  1068. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  1069. double gpWeightAllVal ( 0.0 );
  1070. if ( numberOfClasses > 2)
  1071. {
  1072. //compute the weight in the alpha-vector for every sample after assuming it to be
  1073. // added to the training set.
  1074. // Thereby, we measure its "importance" for the current model
  1075. //
  1076. //double firstTerm is already computed
  1077. //
  1078. //the second term is only needed when computing impacts
  1079. //double secondTerm; //this is the nasty guy :/
  1080. //--- compute the third term
  1081. // this is the difference between predicted label and GT label
  1082. std::vector<double> diffToPositive; diffToPositive.clear();
  1083. std::vector<double> diffToNegative; diffToNegative.clear();
  1084. double diffToNegativeSum(0.0);
  1085. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1086. {
  1087. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1088. {
  1089. continue;
  1090. }
  1091. // look at the difference to plus 1
  1092. diffToPositive.push_back(abs(cr.scores[j] - 1));
  1093. // look at the difference to -1
  1094. diffToNegative.push_back(abs(cr.scores[j] + 1));
  1095. //sum up the difference to -1
  1096. diffToNegativeSum += abs(cr.scores[j] - 1);
  1097. }
  1098. //let's subtract for every class its diffToNegative from the sum, add its diffToPositive,
  1099. //and use this as the third term for this specific class.
  1100. //the final value is obtained by minimizing over all classes
  1101. //
  1102. // originally, we minimize over all classes after building the final score
  1103. // however, the first and the second term do not depend on the choice of
  1104. // y*, therefore we minimize here already
  1105. double thirdTerm (numeric_limits<double>::max()) ;
  1106. for(uint tmpCnt = 0; tmpCnt < diffToPositive.size(); tmpCnt++)
  1107. {
  1108. double tmpVal ( diffToPositive[tmpCnt] + (diffToNegativeSum-diffToNegative[tmpCnt]) );
  1109. if (tmpVal < thirdTerm)
  1110. thirdTerm = tmpVal;
  1111. }
  1112. gpWeightAllVal = thirdTerm*firstTerm;
  1113. }
  1114. else //binary scenario
  1115. {
  1116. gpWeightAllVal = std::min( abs(cr.scores[*classesInUse.begin()]+1), abs(cr.scores[*classesInUse.begin()]-1) );
  1117. gpWeightAllVal *= firstTerm;
  1118. }
  1119. int xs = std::max(0, x - testWSize/2);
  1120. int xe = std::min(xsize - 1, x + testWSize/2);
  1121. int ys = std::max(0, y - testWSize/2);
  1122. int ye = std::min(ysize - 1, y + testWSize/2);
  1123. for (int yl = ys; yl <= ye; yl++)
  1124. {
  1125. for (int xl = xs; xl <= xe; xl++)
  1126. {
  1127. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1128. {
  1129. probabilities ( xl, yl, j ) = cr.scores[j];
  1130. }
  1131. segresult ( xl, yl ) = cr.classno;
  1132. noveltyImage ( xl, yl ) = gpWeightAllVal;
  1133. }
  1134. }
  1135. example.svec->clear();
  1136. }
  1137. delete example.svec;
  1138. example.svec = NULL;
  1139. }
  1140. }
  1141. void SemSegNovelty::computeNoveltyByGPWeightRatio( NICE::FloatImage & noveltyImage,
  1142. const NICE::MultiChannelImageT<double> & feats,
  1143. NICE::ImageT<int> & segresult,
  1144. NICE::MultiChannelImageT<double> & probabilities,
  1145. const int & xsize, const int & ysize, const int & featdim )
  1146. {
  1147. double gpNoise = 0.01;
  1148. //TODO getMethod for GPHIK
  1149. //conf->gD("GPHIK", "noise", 0.01);
  1150. #pragma omp parallel for
  1151. for ( int y = 0; y < ysize; y += testWSize )
  1152. {
  1153. Example example;
  1154. example.vec = NULL;
  1155. example.svec = new SparseVector ( featdim );
  1156. for ( int x = 0; x < xsize; x += testWSize)
  1157. {
  1158. for ( int f = 0; f < featdim; f++ )
  1159. {
  1160. double val = feats.getIntegralValue ( x - whs, y - whs, x + whs, y + whs, f );
  1161. if ( val > 1e-10 )
  1162. ( *example.svec ) [f] = val;
  1163. }
  1164. example.svec->normalize();
  1165. ClassificationResult cr = classifier->classify ( example );
  1166. double firstTerm (1.0 / sqrt(cr.uncertainty+gpNoise));
  1167. double gpWeightRatioVal ( 0.0 );
  1168. if ( numberOfClasses > 2)
  1169. {
  1170. //compute the weight in the alpha-vector for every sample after assuming it to be
  1171. // added to the training set.
  1172. // Thereby, we measure its "importance" for the current model
  1173. //
  1174. //double firstTerm is already computed
  1175. //
  1176. //the second term is only needed when computing impacts
  1177. //double secondTerm; //this is the nasty guy :/
  1178. //--- compute the third term
  1179. // this is the difference between predicted label and GT label
  1180. std::vector<double> diffToPositive; diffToPositive.clear();
  1181. std::vector<double> diffToNegative; diffToNegative.clear();
  1182. double diffToNegativeSum(0.0);
  1183. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1184. {
  1185. if ( forbidden_classesTrain.find ( j ) != forbidden_classesTrain.end() )
  1186. {
  1187. continue;
  1188. }
  1189. // look at the difference to plus 1
  1190. diffToPositive.push_back(abs(cr.scores[j] - 1));
  1191. }
  1192. //let's subtract for every class its diffToNegative from the sum, add its diffToPositive,
  1193. //and use this as the third term for this specific class.
  1194. //the final value is obtained by minimizing over all classes
  1195. //
  1196. // originally, we minimize over all classes after building the final score
  1197. // however, the first and the second term do not depend on the choice of
  1198. // y*, therefore we minimize here already
  1199. //now look on the ratio of the resulting weights for the most plausible
  1200. // against the second most plausible class
  1201. double thirdTermMostPlausible ( 0.0 ) ;
  1202. double thirdTermSecondMostPlausible ( 0.0 ) ;
  1203. for(uint tmpCnt = 0; tmpCnt < diffToPositive.size(); tmpCnt++)
  1204. {
  1205. if (diffToPositive[tmpCnt] > thirdTermMostPlausible)
  1206. {
  1207. thirdTermSecondMostPlausible = thirdTermMostPlausible;
  1208. thirdTermMostPlausible = diffToPositive[tmpCnt];
  1209. }
  1210. else if (diffToPositive[tmpCnt] > thirdTermSecondMostPlausible)
  1211. {
  1212. thirdTermSecondMostPlausible = diffToPositive[tmpCnt];
  1213. }
  1214. }
  1215. //compute the resulting score
  1216. gpWeightRatioVal = (thirdTermMostPlausible - thirdTermSecondMostPlausible)*firstTerm;
  1217. //finally, look for this feature how it would affect to whole model (summarized by weight-vector alpha), if we would
  1218. //use it as an additional training example
  1219. //TODO this would be REALLY computational demanding. Do we really want to do this?
  1220. // gpImpactAll[s] ( pce[i].second.x, pce[i].second.y ) = thirdTerm*firstTerm*secondTerm;
  1221. // gpImpactRatio[s] ( pce[i].second.x, pce[i].second.y ) = (thirdTermMostPlausible - thirdTermSecondMostPlausible)*firstTerm*secondTerm;
  1222. }
  1223. else //binary scenario
  1224. {
  1225. gpWeightRatioVal = std::min( abs(cr.scores[*classesInUse.begin()]+1), abs(cr.scores[*classesInUse.begin()]-1) );
  1226. gpWeightRatioVal *= firstTerm;
  1227. }
  1228. int xs = std::max(0, x - testWSize/2);
  1229. int xe = std::min(xsize - 1, x + testWSize/2);
  1230. int ys = std::max(0, y - testWSize/2);
  1231. int ye = std::min(ysize - 1, y + testWSize/2);
  1232. for (int yl = ys; yl <= ye; yl++)
  1233. {
  1234. for (int xl = xs; xl <= xe; xl++)
  1235. {
  1236. for ( int j = 0 ; j < cr.scores.size(); j++ )
  1237. {
  1238. probabilities ( xl, yl, j ) = cr.scores[j];
  1239. }
  1240. segresult ( xl, yl ) = cr.classno;
  1241. noveltyImage ( xl, yl ) = gpWeightRatioVal;
  1242. }
  1243. }
  1244. example.svec->clear();
  1245. }
  1246. delete example.svec;
  1247. example.svec = NULL;
  1248. }
  1249. }
  1250. void SemSegNovelty::addNewExample(const NICE::Vector& v_newExample, const int & newClassNo)
  1251. {
  1252. //accept the new class as valid information
  1253. if ( forbidden_classesTrain.find ( newClassNo ) != forbidden_classesTrain.end() )
  1254. {
  1255. forbidden_classesTrain.erase(newClassNo);
  1256. numberOfClasses++;
  1257. }
  1258. if ( classesInUse.find ( newClassNo ) == classesInUse.end() )
  1259. {
  1260. classesInUse.insert( newClassNo );
  1261. }
  1262. //then add it to the classifier used
  1263. if ( classifier != NULL )
  1264. {
  1265. if (this->classifierString.compare("GPHIKClassifier") == 0)
  1266. {
  1267. Example newExample;
  1268. SparseVector svec ( v_newExample );
  1269. newExample.svec = &svec;
  1270. static_cast<FPCGPHIK*>(classifier)->addExample ( newExample, newClassNo );
  1271. }
  1272. }
  1273. else //vclassifier
  1274. {
  1275. if (this->classifierString.compare("nn") == 0)
  1276. {
  1277. vclassifier->teach ( newClassNo, v_newExample );
  1278. }
  1279. }
  1280. }
  1281. void SemSegNovelty::addNovelExamples()
  1282. {
  1283. Timer timer;
  1284. //show the image that contains the most novel region
  1285. if (b_visualizeALimages)
  1286. showImage(maskedImg, "Most novel region");
  1287. timer.start();
  1288. std::stringstream out;
  1289. std::vector< std::string > list2;
  1290. StringTools::split ( Globals::getCurrentImgFN (), '/', list2 );
  1291. out << resultdir << "/" << list2.back();
  1292. maskedImg.writePPM ( out.str() + "_run_" + NICE::intToString(this->iterationCountSuffix) + "_" + noveltyMethodString+ "_query.ppm" );
  1293. timer.stop();
  1294. std::cerr << "AL time for writing queried image: " << timer.getLast() << std::endl;
  1295. timer.start();
  1296. //check which classes will be added using the features from the novel region
  1297. std::set<int> newClassNumbers;
  1298. newClassNumbers.clear(); //just to be sure
  1299. for ( uint i = 0 ; i < newTrainExamples.size() ; i++ )
  1300. {
  1301. if (newClassNumbers.find(newTrainExamples[i].first /* classNumber*/) == newClassNumbers.end() )
  1302. {
  1303. newClassNumbers.insert(newTrainExamples[i].first );
  1304. }
  1305. }
  1306. //accept the new classes as valid information
  1307. for (std::set<int>::const_iterator clNoIt = newClassNumbers.begin(); clNoIt != newClassNumbers.end(); clNoIt++)
  1308. {
  1309. if ( forbidden_classesTrain.find ( *clNoIt ) != forbidden_classesTrain.end() )
  1310. {
  1311. forbidden_classesTrain.erase(*clNoIt);
  1312. numberOfClasses++;
  1313. }
  1314. if ( classesInUse.find ( *clNoIt ) == classesInUse.end() )
  1315. {
  1316. classesInUse.insert( *clNoIt );
  1317. }
  1318. }
  1319. timer.stop();
  1320. std::cerr << "AL time for accepting possible new classes: " << timer.getLast() << std::endl;
  1321. timer.start();
  1322. //then add the new features to the classifier used
  1323. if ( classifier != NULL )
  1324. {
  1325. if (this->classifierString.compare("GPHIKClassifier") == 0)
  1326. {
  1327. classifier->addMultipleExamples ( this->newTrainExamples );
  1328. }
  1329. }
  1330. else //vclassifier
  1331. {
  1332. //TODO
  1333. }
  1334. timer.stop();
  1335. std::cerr << "AL time for actually updating the classifier: " << timer.getLast() << std::endl;
  1336. std::cerr << "the current region to query is: " << currentRegionToQuery.first << " -- " << currentRegionToQuery.second << std::endl;
  1337. //did we already query a region of this image?
  1338. if ( queriedRegions.find( currentRegionToQuery.first ) != queriedRegions.end() )
  1339. {
  1340. queriedRegions[ currentRegionToQuery.first ].insert(currentRegionToQuery.second);
  1341. }
  1342. else
  1343. {
  1344. std::set<int> tmpSet; tmpSet.insert(currentRegionToQuery.second);
  1345. queriedRegions.insert(std::pair<std::string,std::set<int> > (currentRegionToQuery.first, tmpSet ) );
  1346. }
  1347. std::cerr << "Write already queried regions: " << std::endl;
  1348. for (std::map<std::string,std::set<int> >::const_iterator it = queriedRegions.begin(); it != queriedRegions.end(); it++)
  1349. {
  1350. std::cerr << "image: " << it->first << " -- ";
  1351. for (std::set<int>::const_iterator itReg = it->second.begin(); itReg != it->second.end(); itReg++)
  1352. {
  1353. std::cerr << *itReg << " ";
  1354. }
  1355. std::cerr << std::endl;
  1356. }
  1357. //clear the latest results, since one iteration is over
  1358. globalMaxUncert = -numeric_limits<double>::max();
  1359. if (!mostNoveltyWithMaxScores)
  1360. globalMaxUncert = numeric_limits<double>::max();
  1361. }
  1362. const Examples * SemSegNovelty::getNovelExamples() const
  1363. {
  1364. return &(this->newTrainExamples);
  1365. }
  1366. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1367. // interface specific methods for store and restore
  1368. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1369. void SemSegNovelty::restore ( std::istream & is, int format )
  1370. {
  1371. //delete everything we knew so far...
  1372. this->clear();
  1373. bool b_restoreVerbose ( false );
  1374. #ifdef B_RESTOREVERBOSE
  1375. b_restoreVerbose = true;
  1376. #endif
  1377. if ( is.good() )
  1378. {
  1379. if ( b_restoreVerbose )
  1380. std::cerr << " restore SemSegNovelty" << std::endl;
  1381. std::string tmp;
  1382. is >> tmp; //class name
  1383. if ( ! this->isStartTag( tmp, "SemSegNovelty" ) )
  1384. {
  1385. std::cerr << " WARNING - attempt to restore SemSegNovelty, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1386. throw;
  1387. }
  1388. if (classifier != NULL)
  1389. {
  1390. delete classifier;
  1391. classifier = NULL;
  1392. }
  1393. is.precision (numeric_limits<double>::digits10 + 1);
  1394. bool b_endOfBlock ( false ) ;
  1395. while ( !b_endOfBlock )
  1396. {
  1397. is >> tmp; // start of block
  1398. if ( this->isEndTag( tmp, "SemSegNovelty" ) )
  1399. {
  1400. b_endOfBlock = true;
  1401. continue;
  1402. }
  1403. tmp = this->removeStartTag ( tmp );
  1404. if ( b_restoreVerbose )
  1405. std::cerr << " currently restore section " << tmp << " in SemSegNovelty" << std::endl;
  1406. ///////////////////////////////
  1407. // FEATURE EXTRACTION //
  1408. ///////////////////////////////
  1409. if ( tmp.compare("featExtract") == 0 )
  1410. {
  1411. featExtract->restore(is, format);
  1412. is >> tmp; // end of block
  1413. tmp = this->removeEndTag ( tmp );
  1414. }
  1415. else if ( tmp.compare("trainWSize") == 0 )
  1416. {
  1417. is >> trainWSize;
  1418. is >> tmp; // end of block
  1419. tmp = this->removeEndTag ( tmp );
  1420. }
  1421. else if ( tmp.compare("whs") == 0 )
  1422. {
  1423. is >> whs;
  1424. is >> tmp; // end of block
  1425. tmp = this->removeEndTag ( tmp );
  1426. }
  1427. else if ( tmp.compare("testWSize") == 0 )
  1428. {
  1429. is >> testWSize;
  1430. is >> tmp; // end of block
  1431. tmp = this->removeEndTag ( tmp );
  1432. }
  1433. ///////////////////////////////
  1434. // NOVELTY COMPUTATION //
  1435. ///////////////////////////////
  1436. else if ( tmp.compare("noveltyMethod") == 0 )
  1437. {
  1438. unsigned int ui_noveltyMethod;
  1439. is >> ui_noveltyMethod;
  1440. this->noveltyMethod = static_cast<NoveltyMethod> ( ui_noveltyMethod );
  1441. is >> tmp; // end of block
  1442. tmp = this->removeEndTag ( tmp );
  1443. }
  1444. else if ( tmp.compare("noveltyMethodString") == 0 )
  1445. {
  1446. is >> noveltyMethodString;
  1447. is >> tmp; // end of block
  1448. tmp = this->removeEndTag ( tmp );
  1449. }
  1450. else if ( tmp.compare("globalMaxUncert") == 0 )
  1451. {
  1452. is >> globalMaxUncert;
  1453. is >> tmp; // end of block
  1454. tmp = this->removeEndTag ( tmp );
  1455. }
  1456. else if ( tmp.compare("mostNoveltyWithMaxScores") == 0 )
  1457. {
  1458. is >> mostNoveltyWithMaxScores;
  1459. is >> tmp; // end of block
  1460. tmp = this->removeEndTag ( tmp );
  1461. }
  1462. else if ( tmp.compare("findMaximumUncert") == 0 )
  1463. {
  1464. is >> findMaximumUncert;
  1465. is >> tmp; // end of block
  1466. tmp = this->removeEndTag ( tmp );
  1467. }
  1468. //TODO maskedImg
  1469. else if ( tmp.compare("b_visualizeALimages") == 0 )
  1470. {
  1471. is >> b_visualizeALimages;
  1472. is >> tmp; // end of block
  1473. tmp = this->removeEndTag ( tmp );
  1474. }
  1475. ///////////////////////////////
  1476. // CLASSIFICATION STUFF //
  1477. ///////////////////////////////
  1478. else if ( tmp.compare("classifier") == 0 )
  1479. {
  1480. std::string isNull;
  1481. is >> isNull;
  1482. // check whether we originally used a classifier
  1483. if ( isNull.compare( "NULL" ) == 0 )
  1484. {
  1485. if ( classifier != NULL )
  1486. delete classifier;
  1487. classifier = NULL;
  1488. }
  1489. else
  1490. {
  1491. if ( classifier == NULL )
  1492. classifier = new OBJREC::FPCGPHIK();
  1493. classifier->restore(is, format);
  1494. }
  1495. is >> tmp; // end of block
  1496. tmp = this->removeEndTag ( tmp );
  1497. }
  1498. else if ( tmp.compare("vclassifier") == 0 )
  1499. {
  1500. std::string isNull;
  1501. is >> isNull;
  1502. // check whether we originally used a vclassifier
  1503. if ( isNull.compare( "NULL" ) == 0 )
  1504. {
  1505. if ( vclassifier != NULL )
  1506. delete vclassifier;
  1507. vclassifier = NULL;
  1508. }
  1509. else
  1510. {
  1511. fthrow ( NICE::Exception, "Restoring of VecClassifiers is not implemented yet!" );
  1512. /* if ( vclassifier == NULL )
  1513. vclassifier = new OBJREC::VecClassifier();
  1514. vclassifier->restore(is, format); */
  1515. }
  1516. is >> tmp; // end of block
  1517. tmp = this->removeEndTag ( tmp );
  1518. }
  1519. else if ( tmp.compare("forbidden_classesTrain") == 0 )
  1520. {
  1521. is >> tmp; // size
  1522. int forbClTrainSize ( 0 );
  1523. is >> forbClTrainSize;
  1524. forbidden_classesTrain.clear();
  1525. if ( b_restoreVerbose )
  1526. std::cerr << "restore forbidden_classesTrain with size: " << forbClTrainSize << std::endl;
  1527. if ( forbClTrainSize > 0 )
  1528. {
  1529. if ( b_restoreVerbose )
  1530. std::cerr << " restore forbidden_classesTrain" << std::endl;
  1531. for (int i = 0; i < forbClTrainSize; i++)
  1532. {
  1533. int classNo;
  1534. is >> classNo;
  1535. forbidden_classesTrain.insert ( classNo );
  1536. }
  1537. }
  1538. else
  1539. {
  1540. if ( b_restoreVerbose )
  1541. std::cerr << " skip restoring forbidden_classesTrain" << std::endl;
  1542. }
  1543. is >> tmp; // end of block
  1544. tmp = this->removeEndTag ( tmp );
  1545. }
  1546. else if ( tmp.compare("forbidden_classesActiveLearning") == 0 )
  1547. {
  1548. is >> tmp; // size
  1549. int forbClALSize ( 0 );
  1550. is >> forbClALSize;
  1551. forbidden_classesActiveLearning.clear();
  1552. if ( b_restoreVerbose )
  1553. std::cerr << "restore forbidden_classesActiveLearning with size: " << forbClALSize << std::endl;
  1554. if ( forbClALSize > 0 )
  1555. {
  1556. if ( b_restoreVerbose )
  1557. std::cerr << " restore forbidden_classesActiveLearning" << std::endl;
  1558. for (int i = 0; i < forbClALSize; i++)
  1559. {
  1560. int classNo;
  1561. is >> classNo;
  1562. forbidden_classesActiveLearning.insert ( classNo );
  1563. }
  1564. }
  1565. else
  1566. {
  1567. if ( b_restoreVerbose )
  1568. std::cerr << " skip restoring forbidden_classesActiveLearning" << std::endl;
  1569. }
  1570. is >> tmp; // end of block
  1571. tmp = this->removeEndTag ( tmp );
  1572. }
  1573. else if ( tmp.compare("classesInUse") == 0 )
  1574. {
  1575. is >> tmp; // size
  1576. int clInUseSize ( 0 );
  1577. is >> clInUseSize;
  1578. classesInUse.clear();
  1579. if ( b_restoreVerbose )
  1580. std::cerr << "restore classesInUse with size: " << clInUseSize << std::endl;
  1581. if ( clInUseSize > 0 )
  1582. {
  1583. if ( b_restoreVerbose )
  1584. std::cerr << " restore classesInUse" << std::endl;
  1585. for (int i = 0; i < clInUseSize; i++)
  1586. {
  1587. int classNo;
  1588. is >> classNo;
  1589. classesInUse.insert ( classNo );
  1590. }
  1591. }
  1592. else
  1593. {
  1594. if ( b_restoreVerbose )
  1595. std::cerr << " skip restoring classesInUse" << std::endl;
  1596. }
  1597. is >> tmp; // end of block
  1598. tmp = this->removeEndTag ( tmp );
  1599. }
  1600. else if ( tmp.compare("numberOfClasses") == 0 )
  1601. {
  1602. is >> numberOfClasses;
  1603. is >> tmp; // end of block
  1604. tmp = this->removeEndTag ( tmp );
  1605. }
  1606. else if ( tmp.compare("read_classifier") == 0 )
  1607. {
  1608. is >> read_classifier;
  1609. is >> tmp; // end of block
  1610. tmp = this->removeEndTag ( tmp );
  1611. }
  1612. else if ( tmp.compare("save_classifier") == 0 )
  1613. {
  1614. is >> save_classifier;
  1615. is >> tmp; // end of block
  1616. tmp = this->removeEndTag ( tmp );
  1617. }
  1618. else if ( tmp.compare("cache") == 0 )
  1619. {
  1620. is >> cache;
  1621. is >> tmp; // end of block
  1622. tmp = this->removeEndTag ( tmp );
  1623. }
  1624. else if ( tmp.compare("resultdir") == 0 )
  1625. {
  1626. is >> resultdir;
  1627. is >> tmp; // end of block
  1628. tmp = this->removeEndTag ( tmp );
  1629. }
  1630. //TODO newTrainExamples
  1631. ///////////////////////////////
  1632. // SEGMENTATION STUFF //
  1633. ///////////////////////////////
  1634. //TODO regionSeg
  1635. else if ( tmp.compare("s_rsMethode") == 0 )
  1636. {
  1637. is >> this->s_rsMethode;
  1638. // theoretically, we should properly store and restore the regionSeg object. However, its parent class does not provide
  1639. // a Persistent interface yet. Hence, we perform this tiny workaround which works, since regionSeg is not changed over time...
  1640. // only be aware of parameters originally set via config...
  1641. is >> tmp; // end of block
  1642. tmp = this->removeEndTag ( tmp );
  1643. }
  1644. //NOTE regionSeg seems really important to keep track off
  1645. else if ( tmp.compare("reuseSegmentation") == 0 )
  1646. {
  1647. is >> reuseSegmentation;
  1648. is >> tmp; // end of block
  1649. tmp = this->removeEndTag ( tmp );
  1650. }
  1651. else if ( tmp.compare("queriedRegions") == 0 )
  1652. {
  1653. is >> tmp; // size
  1654. int queriedRegionsSize ( 0 );
  1655. is >> queriedRegionsSize;
  1656. queriedRegions.clear();
  1657. if ( b_restoreVerbose )
  1658. std::cerr << "restore queriedRegions with size: " << queriedRegionsSize << std::endl;
  1659. for ( int i = 0; i < queriedRegionsSize; i++ )
  1660. {
  1661. // restore key
  1662. std::string key;
  1663. is >> key;
  1664. // restore values -- inner loop over sets
  1665. is >> tmp; // size
  1666. int regionsOfImgSize ( 0 );
  1667. is >> regionsOfImgSize;
  1668. std::set< int > regionsOfImg;
  1669. regionsOfImg.clear();
  1670. for (int i = 0; i < regionsOfImgSize; i++)
  1671. {
  1672. int idxRegion;
  1673. is >> idxRegion;
  1674. regionsOfImg.insert ( idxRegion );
  1675. }
  1676. queriedRegions.insert ( std::pair<std::string, std::set< int > > ( key, regionsOfImg ) );
  1677. }
  1678. is >> tmp; // end of block
  1679. tmp = this->removeEndTag ( tmp );
  1680. }
  1681. //
  1682. //TODO currentRegionToQuery
  1683. //
  1684. ///////////////////////////////
  1685. // PARENT OBJECT //
  1686. ///////////////////////////////
  1687. else if ( tmp.compare("SemSegNovelty--Parent") == 0 )
  1688. {
  1689. // restore parent object
  1690. SemanticSegmentation::restore(is);
  1691. }
  1692. else
  1693. {
  1694. std::cerr << "WARNING -- unexpected SemSegNovelty object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1695. throw;
  1696. }
  1697. // INSTANTIATE (YET) NON-RESTORABLE OBJECTS
  1698. //TODO destructor of regionSeg is non-virtual so far - change this accordingly!
  1699. if ( this->regionSeg != NULL )
  1700. delete this->regionSeg;
  1701. if( this->s_rsMethode == "none" )
  1702. {
  1703. this->regionSeg = NULL;
  1704. }
  1705. else
  1706. {
  1707. //NOTE using an empty config file might not be save...
  1708. NICE::Config tmpConfEmpty;
  1709. RegionSegmentationMethod *tmpRegionSeg = GenericRegionSegmentationMethodSelection::selectRegionSegmentationMethod( &tmpConfEmpty, this->s_rsMethode );
  1710. if ( reuseSegmentation )
  1711. this->regionSeg = new RSCache ( &tmpConfEmpty, tmpRegionSeg );
  1712. else
  1713. this->regionSeg = tmpRegionSeg;
  1714. }
  1715. // done restoration
  1716. }
  1717. }
  1718. else
  1719. {
  1720. std::cerr << "SemSegNovelty::restore -- InStream not initialized - restoring not possible!" << std::endl;
  1721. throw;
  1722. }
  1723. }
  1724. void SemSegNovelty::store ( std::ostream & os, int format ) const
  1725. {
  1726. if (os.good())
  1727. {
  1728. // show starting point
  1729. os << this->createStartTag( "SemSegNovelty" ) << std::endl;
  1730. ///////////////////////////////
  1731. // FEATURE EXTRACTION //
  1732. ///////////////////////////////
  1733. os << this->createStartTag( "featExtract" ) << std::endl;
  1734. featExtract->store ( os );
  1735. os << this->createStartTag( "featExtract" ) << std::endl;
  1736. os << this->createStartTag( "trainWsize" ) << std::endl;
  1737. os << this->trainWSize << std::endl;
  1738. os << this->createStartTag( "trainWsize" ) << std::endl;
  1739. os << this->createStartTag( "whs" ) << std::endl;
  1740. os << this->whs << std::endl;
  1741. os << this->createStartTag( "whs" ) << std::endl;
  1742. os << this->createStartTag( "testWSize" ) << std::endl;
  1743. os << this->testWSize << std::endl;
  1744. os << this->createStartTag( "testWSize" ) << std::endl;
  1745. ///////////////////////////////
  1746. // NOVELTY COMPUTATION //
  1747. ///////////////////////////////
  1748. os << this->createStartTag( "noveltyMethod" ) << std::endl;
  1749. os << this->noveltyMethod << std::endl;
  1750. os << this->createStartTag( "noveltyMethod" ) << std::endl;
  1751. os << this->createStartTag( "noveltyMethodString" ) << std::endl;
  1752. os << this->noveltyMethodString << std::endl;
  1753. os << this->createStartTag( "noveltyMethodString" ) << std::endl;
  1754. os << this->createStartTag( "globalMaxUncert" ) << std::endl;
  1755. os << this->globalMaxUncert << std::endl;
  1756. os << this->createStartTag( "globalMaxUncert" ) << std::endl;
  1757. os << this->createStartTag( "mostNoveltyWithMaxScores" ) << std::endl;
  1758. os << this->mostNoveltyWithMaxScores << std::endl;
  1759. os << this->createStartTag( "mostNoveltyWithMaxScores" ) << std::endl;
  1760. os << this->createStartTag( "findMaximumUncert" ) << std::endl;
  1761. os << this->findMaximumUncert << std::endl;
  1762. os << this->createStartTag( "findMaximumUncert" ) << std::endl;
  1763. //TODO maskedImg
  1764. os << this->createStartTag( "b_visualizeALimages" ) << std::endl;
  1765. os << this->b_visualizeALimages << std::endl;
  1766. os << this->createStartTag( "b_visualizeALimages" ) << std::endl;
  1767. ///////////////////////////////
  1768. // CLASSIFICATION STUFF //
  1769. ///////////////////////////////
  1770. os << this->createStartTag( "classifierString" ) << std::endl;
  1771. os << this->classifierString << std::endl;
  1772. os << this->createStartTag( "classifierString" ) << std::endl;
  1773. os << this->createStartTag( "classifier" ) << std::endl;
  1774. if ( this->classifier != NULL )
  1775. {
  1776. os << "NOTNULL" << std::endl;
  1777. classifier->store ( os, format );
  1778. }
  1779. else
  1780. {
  1781. os << "NULL" << std::endl;
  1782. }
  1783. os << this->createEndTag( "classifier" ) << std::endl;
  1784. //
  1785. os << this->createStartTag( "vclassifier" ) << std::endl;
  1786. if ( this->classifier != NULL )
  1787. {
  1788. os << "NOTNULL" << std::endl;
  1789. vclassifier->store ( os, format );
  1790. }
  1791. else
  1792. {
  1793. os << "NULL" << std::endl;
  1794. }
  1795. os << this->createEndTag( "vclassifier" ) << std::endl;
  1796. os << this->createStartTag( "forbidden_classesTrain" ) << std::endl;
  1797. os << "size: " << forbidden_classesTrain.size() << std::endl;
  1798. for ( std::set< int >::const_iterator itForbClassTrain = forbidden_classesTrain.begin();
  1799. itForbClassTrain != forbidden_classesTrain.end();
  1800. itForbClassTrain++
  1801. )
  1802. {
  1803. os << *itForbClassTrain << " " << std::endl;
  1804. }
  1805. os << this->createEndTag( "forbidden_classesTrain" ) << std::endl;
  1806. //
  1807. os << this->createStartTag( "forbidden_classesActiveLearning" ) << std::endl;
  1808. os << "size: " << forbidden_classesActiveLearning.size() << std::endl;
  1809. for ( std::set< int >::const_iterator itForbClassAL = forbidden_classesActiveLearning.begin();
  1810. itForbClassAL != forbidden_classesActiveLearning.end();
  1811. itForbClassAL++
  1812. )
  1813. {
  1814. os << *itForbClassAL << " " << std::endl;
  1815. }
  1816. os << this->createEndTag( "forbidden_classesActiveLearning" ) << std::endl;
  1817. //
  1818. os << this->createStartTag( "classesInUse" ) << std::endl;
  1819. os << "size: " << classesInUse.size() << std::endl;
  1820. for ( std::set< int >::const_iterator itClassesInUse = classesInUse.begin();
  1821. itClassesInUse != classesInUse.end();
  1822. itClassesInUse++
  1823. )
  1824. {
  1825. os << *itClassesInUse << " " << std::endl;
  1826. }
  1827. os << this->createEndTag( "classesInUse" ) << std::endl;
  1828. os << this->createStartTag( "numberOfClasses" ) << std::endl;
  1829. os << this->numberOfClasses << std::endl;
  1830. os << this->createStartTag( "numberOfClasses" ) << std::endl;
  1831. os << this->createStartTag( "read_classifier" ) << std::endl;
  1832. os << this->read_classifier << std::endl;
  1833. os << this->createStartTag( "read_classifier" ) << std::endl;
  1834. os << this->createStartTag( "save_classifier" ) << std::endl;
  1835. os << this->save_classifier << std::endl;
  1836. os << this->createStartTag( "save_classifier" ) << std::endl;
  1837. os << this->createStartTag( "cache" ) << std::endl;
  1838. os << this->cache << std::endl;
  1839. os << this->createStartTag( "cache" ) << std::endl;
  1840. os << this->createStartTag( "resultdir" ) << std::endl;
  1841. os << this->resultdir << std::endl;
  1842. os << this->createStartTag( "resultdir" ) << std::endl;
  1843. //TODO newTrainExamples
  1844. ///////////////////////////////
  1845. // SEGMENTATION STUFF //
  1846. ///////////////////////////////
  1847. // theoretically, we should properly store and restore the regionSeg object. However, its parent class does not provide
  1848. // a Persistent interface yet. Hence, we perform this tiny workaround which works, since regionSeg is not changed over time...
  1849. // only be aware of parameters originally set via config...
  1850. os << this->createStartTag( "s_rsMethode" ) << std::endl;
  1851. os << this->s_rsMethode << std::endl;
  1852. os << this->createStartTag( "s_rsMethode" ) << std::endl;
  1853. os << this->createStartTag( "reuseSegmentation" ) << std::endl;
  1854. os << this->reuseSegmentation << std::endl;
  1855. os << this->createStartTag( "reuseSegmentation" ) << std::endl;
  1856. os << this->createStartTag( "queriedRegions" ) << std::endl;
  1857. os << "size: " << queriedRegions.size() << std::endl;
  1858. std::map< std::string, std::set< int > >::const_iterator itQueriedRegions = queriedRegions.begin();
  1859. for ( uint i = 0; i < queriedRegions.size(); i++ )
  1860. {
  1861. // store key
  1862. os << itQueriedRegions->first << std::endl;
  1863. // store values -- inner loop over sets
  1864. os << "size: " << ( itQueriedRegions->second ).size() << std::endl;
  1865. for ( std::set< int >::const_iterator itRegionsOfImg = ( itQueriedRegions->second ).begin();
  1866. itRegionsOfImg != ( itQueriedRegions->second ).end();
  1867. itRegionsOfImg++
  1868. )
  1869. {
  1870. os << *itRegionsOfImg << " " << std::endl;
  1871. }
  1872. itQueriedRegions++;
  1873. }
  1874. os << this->createStartTag( "queriedRegions" ) << std::endl;
  1875. //
  1876. //TODO currentRegionToQuery
  1877. ///////////////////////////////
  1878. // PARENT OBJECT //
  1879. ///////////////////////////////
  1880. os << this->createStartTag( "SemSegNovelty--Parent" ) << std::endl;
  1881. SemanticSegmentation::store(os);
  1882. os << this->createStartTag( "SemSegNovelty--Parent" ) << std::endl;
  1883. // done
  1884. os << this->createEndTag( "SemSegNovelty" ) << std::endl;
  1885. }
  1886. else
  1887. {
  1888. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1889. }
  1890. }
  1891. void SemSegNovelty::clear ()
  1892. {
  1893. //TODO
  1894. }