Michael Kemmler 13 lat temu
rodzic
commit
24e41dbd07
45 zmienionych plików z 4607 dodań i 4760 usunięć
  1. 132 133
      baselib/ColorSpace.cpp
  2. 34 37
      baselib/ColorSpace.h
  3. 9 3
      baselib/Globals.cpp
  4. 16 16
      baselib/Globals.h
  5. 9 10
      baselib/ProgressBar.cpp
  6. 7 7
      baselib/ProgressBar.h
  7. 128 128
      baselib/ProgressBarQt.cpp
  8. 44 44
      baselib/ProgressBarQt.h
  9. 26 26
      baselib/RunningStat.h
  10. 225 225
      cbaselib/CachedExample.cpp
  11. 340 338
      cbaselib/ClassNames.cpp
  12. 80 80
      cbaselib/ClassNames.h
  13. 1 0
      cbaselib/Example.cpp
  14. 107 107
      cbaselib/Example.h
  15. 317 317
      cbaselib/LabeledSet.cpp
  16. 107 95
      cbaselib/LabeledSet.h
  17. 229 0
      cbaselib/MutualInformation.cpp
  18. 93 0
      cbaselib/MutualInformation.h
  19. 127 127
      classifier/fpclassifier/logisticregression/FPCSMLR.cpp
  20. 431 431
      classifier/fpclassifier/logisticregression/SLR.cpp
  21. 93 93
      classifier/fpclassifier/logisticregression/SLR.h
  22. 71 72
      classifier/genericClassifierSelection.h
  23. 0 1
      classifier/kernelclassifier/progs/laplaceTests.cpp
  24. 0 1
      classifier/progs/toyExampleUnsupervisedGP.cpp
  25. 157 157
      classifier/vclassifier/VCDTSVM.cpp
  26. 50 50
      classifier/vclassifier/VCDTSVM.h
  27. 171 174
      features/fpfeatures/HaarFeature.cpp
  28. 40 40
      features/fpfeatures/HaarFeature.h
  29. 0 278
      features/localfeatures/Centrist.cpp~
  30. 0 64
      features/localfeatures/Centrist.h~
  31. 413 416
      features/localfeatures/LFColorWeijer.cpp
  32. 2 1
      features/localfeatures/LFColorWeijer.h
  33. 0 191
      features/localfeatures/LFColorWeijer.h~
  34. 1 1
      features/localfeatures/LFSiftPP.h
  35. 1 1
      features/localfeatures/LFonHSG.h
  36. 1 1
      features/localfeatures/LocalFeatureSift.h
  37. 1 1
      features/localfeatures/progs/sift-driver.cpp
  38. 71 30
      features/simplefeatures/FCCodebookHistBin.h
  39. 669 669
      math/cluster/GMM.cpp
  40. 210 206
      math/cluster/GMM.h
  41. 1 1
      math/cluster/GSCluster.h
  42. 0 1
      math/cluster/progs/testKMeans.cpp
  43. 135 129
      math/ftransform/PCA.cpp
  44. 56 58
      math/ftransform/PCA.h
  45. 2 0
      math/mathbase/Featuretype.cpp

+ 132 - 133
baselib/ColorSpace.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ColorSpace.cpp
  * @brief __DESC__
  * @author Michael Koch
@@ -20,153 +20,152 @@ using namespace std;
 using namespace NICE;
 
 //bad position for this function
-void ColorSpace::ColorImagetoMultiChannelImage(const NICE::ColorImage &imgrgb,NICE::MultiChannelImageT<double> &genimg)
+void ColorSpace::ColorImagetoMultiChannelImage(  const NICE::ColorImage &imgrgb, NICE::MultiChannelImageT<double> &genimg )
 {
-     genimg.reInit(imgrgb.width(),imgrgb.height(),3,true);
-     for(int y=0;y<imgrgb.height();y++)
-     {
-          for(int x=0;x<imgrgb.width();x++)
-          {
-               double r,g,b;
-               r=imgrgb.getPixelQuick(x,y,0);
-               g=imgrgb.getPixelQuick(x,y,1);
-               b=imgrgb.getPixelQuick(x,y,2);
-               genimg.set(x,y,r,0);
-               genimg.set(x,y,g,1);
-               genimg.set(x,y,b,2);
-          }
-     }
+  genimg.reInit( imgrgb.width(), imgrgb.height(), 3, true );
+  for ( int y = 0;y < imgrgb.height();y++ )
+  {
+    for ( int x = 0;x < imgrgb.width();x++ )
+    {
+      double r, g, b;
+      r = imgrgb.getPixelQuick( x, y, 0 );
+      g = imgrgb.getPixelQuick( x, y, 1 );
+      b = imgrgb.getPixelQuick( x, y, 2 );
+      genimg.set( x, y, r, 0 );
+      genimg.set( x, y, g, 1 );
+      genimg.set( x, y, b, 2 );
+    }
+  }
 }
 
-/*
+
 //TODO test it
-int checkRange(int in,int min=0,int max=255)
+int checkRange( int in, int min = 0, int max = 255 )
 {
-     int out=in;
-     
-     if(in<min)
-     {
-          out=min;
-     }
-     if(in>max)
-     {
-          out=max;
-     }
-     return out;
+  int out = in;
+
+  if ( in < min )
+  {
+    out = min;
+  }
+  if ( in > max )
+  {
+    out = max;
+  }
+  return out;
 }
 
-NICE::ColorImage ColorSpace::rgbtohsl(const NICE::ColorImage &imgrgb)
+NICE::MultiChannelImageT<double> ColorSpace::rgbtohsl( const NICE::MultiChannelImageT<double> &imgrgb )
 {
-     NICE::ColorImage imghsl (imgrgb.width(), imgrgb.height());
-
-     for(int x=0;x<imgrgb.width();x++)
-     {
-          for(int y=0;y<imgrgb.height();y++)
-          {
-               double R,G,B,H,S,L;
-
-               R=(double)imgrgb.getPixel(x,y,0)/255.0;
-               G=(double)imgrgb.getPixel(x,y,1)/255.0;
-               B=(double)imgrgb.getPixel(x,y,2)/255.0;
-               ColorConversion::ccRGBtoHSL(R,G,B,&H,&S,&L);
-               imghsl.setPixel(x,y,0,(int)round(H*255.0));
-               imghsl.setPixel(x,y,1,(int)round(S*255.0));
-               imghsl.setPixel(x,y,2,(int)round(L*255.0));
-          }
-     }     
-     return imghsl;
+  NICE::MultiChannelImageT<double> imghsl( imgrgb.width(), imgrgb.height(), 3 );
+
+  for ( int x = 0;x < imgrgb.width();x++ )
+  {
+    for ( int y = 0;y < imgrgb.height();y++ )
+    {
+      double R, G, B, H, S, L;
+
+      R = ( double )imgrgb.get( x, y, 0 );
+      G = ( double )imgrgb.get( x, y, 1 );
+      B = ( double )imgrgb.get( x, y, 2 );
+      ColorConversion::ccRGBtoHSL( R, G, B, &H, &S, &L );
+      imghsl.set( x, y, H, 0 );
+      imghsl.set( x, y, S, 1 );
+      imghsl.set( x, y, L, 2 );
+    }
+  }
+  return imghsl;
 }
 
-NICE::ColorImage ColorSpace::hsltorgb(const NICE::ColorImage &imghsl)
+NICE::MultiChannelImageT<double> ColorSpace::hsltorgb( const NICE::MultiChannelImageT<double> &imghsl )
 {
-     NICE::ColorImage imgrgb (imghsl.width(), imghsl.height());
-
-     for(int x=0;x<imghsl.width();x++)
-     {
-          for(int y=0;y<imghsl.height();y++)
-          {
-               double R,G,B,H,S,L;
-               H=(double)imghsl.getPixel(x,y,0)/255.0;
-               S=(double)imghsl.getPixel(x,y,1)/255.0;
-               L=(double)imghsl.getPixel(x,y,2)/255.0;
-             
-               ColorConversion::ccHSLtoRGB(H,S,L,&R,&G,&B);
-
-               imgrgb.setPixel(x,y,0,(int)round(R*255.0));
-
-               imgrgb.setPixel(x,y,1,(int)round(G*255.0));
-
-               imgrgb.setPixel(x,y,2,(int)round(B*255.0));
-          }
-     }     
-     return imgrgb;
+  NICE::MultiChannelImageT<double> imgrgb( imghsl.width(), imghsl.height(), 3 );
+
+  for ( int x = 0;x < imghsl.width();x++ )
+  {
+    for ( int y = 0;y < imghsl.height();y++ )
+    {
+      double R, G, B, H, S, L;
+      H = ( double )imghsl.get( x, y, 0 );
+      S = ( double )imghsl.get( x, y, 1 );
+      L = ( double )imghsl.get( x, y, 2 );
+
+      ColorConversion::ccHSLtoRGB( H, S, L, &R, &G, &B );
+
+      imgrgb.set( x, y, ( int )round( R*255.0 ), 0 );
+      imgrgb.set( x, y, ( int )round( G*255.0 ), 1 );
+      imgrgb.set( x, y, ( int )round( B*255.0 ), 2 );
+    }
+  }
+  return imgrgb;
 }
-        
-NICE::ColorImage ColorSpace::rgbtolab(const NICE::ColorImage &imgrgb)
+
+NICE::MultiChannelImageT<double> ColorSpace::rgbtolab( const NICE::MultiChannelImageT<double> &imgrgb )
 {
-     NICE::ColorImage imglab (imgrgb.width(), imgrgb.height());
-     //preprocessing RGB to XYZ
-     for(int x=0;x<imgrgb.width();x++)
-     {
-          for(int y=0;y<imgrgb.height();y++)
-          {
-               double R,G,B,X,Y,Z,L,a,b;
-               R=(double)imgrgb.getPixel(x,y,0)/255.0;
-               G=(double)imgrgb.getPixel(x,y,1)/255.0;
-               B=(double)imgrgb.getPixel(x,y,2)/255.0;
-               ColorConversion::ccRGBtoXYZ(R,G,B,&X,&Y,&Z,0);
-               ColorConversion::ccXYZtoCIE_Lab(X,Y,Z,&L,&a,&b,0);
-               imglab.setPixel(x,y,0,(int)round(L*255.0));
-               imglab.setPixel(x,y,1,(int)round(a*255.0));
-               imglab.setPixel(x,y,2,(int)round(b*255.0));
-          }
-     }     
-	 showImage ( *imglab.getChannel(0), "L" );
-     return imglab;
+  NICE::MultiChannelImageT<double> imglab( imgrgb.width(), imgrgb.height(), 3 );
+  //preprocessing RGB to XYZ
+  for ( int x = 0;x < imgrgb.width();x++ )
+  {
+    for ( int y = 0;y < imgrgb.height();y++ )
+    {
+      double R, G, B, X, Y, Z, L, a, b;
+      R = ( double )imgrgb.get( x, y, 0 ) / 255.0;
+      G = ( double )imgrgb.get( x, y, 1 ) / 255.0;
+      B = ( double )imgrgb.get( x, y, 2 ) / 255.0;
+      
+      ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
+      ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &L, &a, &b, 0 );
+      
+      imglab.set( x, y, L, 0 );
+      imglab.set( x, y, a, 1 );
+      imglab.set( x, y, b, 2 );
+    }
+  }
+  return imglab;
 }
 
-NICE::ColorImage ColorSpace::labtorgb(const NICE::ColorImage &imglab)
+NICE::MultiChannelImageT<double> ColorSpace::labtorgb( const NICE::MultiChannelImageT<double> &imglab )
 {
-     NICE::ColorImage imgrgb (imglab.width(), imglab.height());
-     //preprocessing RGB to XYZ
-     for(int x=0;x<imglab.width();x++)
-     {
-          for(int y=0;y<imglab.height();y++)
-          {
-               double R,G,B,X,Y,Z,L,a,b;
-               L=(double)imglab.getPixel(x,y,0)/255.0;
-               a=(double)imglab.getPixel(x,y,1)/255.0;
-               b=(double)imglab.getPixel(x,y,2)/255.0;
-               
-               ColorConversion::ccCIE_LabtoXYZ(L,a,b,&X,&Y,&Z,0);
-               ColorConversion::ccXYZtoRGB(X,Y,Z,&R,&G,&B,0);
-               imgrgb.setPixel(x,y,0,(int)round(R*255.0));
-               imgrgb.setPixel(x,y,1,(int)round(G*255.0));
-               imgrgb.setPixel(x,y,2,(int)round(B*255.0));
-          }
-     }     
-     return imgrgb;
+  NICE::MultiChannelImageT<double> imgrgb( imglab.width(), imglab.height(), 3 );
+  //preprocessing RGB to XYZ
+  for ( int x = 0;x < imglab.width();x++ )
+  {
+    for ( int y = 0;y < imglab.height();y++ )
+    {
+      double R, G, B, X, Y, Z, L, a, b;
+      L = imglab.get( x, y, 0 );
+      a = imglab.get( x, y, 1 );
+      b = imglab.get( x, y, 2 );
+
+      ColorConversion::ccCIE_LabtoXYZ( L, a, b, &X, &Y, &Z, 0 );
+      ColorConversion::ccXYZtoRGB( X, Y, Z, &R, &G, &B, 0 );
+      imgrgb.set( x, y, round( R*255.0 ), 0 );
+      imgrgb.set( x, y, round( G*255.0 ), 1 );
+      imgrgb.set( x, y, round( B*255.0 ), 2 );
+    }
+  }
+  return imgrgb;
 }
-NICE::ColorImage ColorSpace::rgbtolms(const NICE::ColorImage &imgrgb)
-{
-     NICE::ColorImage imglms=NICE::ColorImage(imgrgb.width(),imgrgb.height());
-     //preprocessing RGB to XYZ
-     for(int x=0;x<imgrgb.width();x++)
-     {
-          for(int y=0;y<imgrgb.height();y++)
-          {
-               double R,G,B,X,Y,Z,L,M,S;
-               R=(double)imgrgb.getPixelQuick(x,y,0)/255.0;
-               G=(double)imgrgb.getPixelQuick(x,y,1)/255.0;
-               B=(double)imgrgb.getPixelQuick(x,y,2)/255.0;
-               
-               ColorConversion::ccRGBtoXYZ(R,G,B,&X,&Y,&Z,0);
-               ColorConversion::ccXYZtoLMS(X,Y,Z,&L,&M,&S);
-               imglms.setPixelQuick(x,y,0,checkRange((int)round(L*255.0)));
-               imglms.setPixelQuick(x,y,1,checkRange((int)round(M*255.0)));
-               imglms.setPixelQuick(x,y,2,checkRange((int)round(S*255.0)));
-          }
-     }     
-     return imglms;
-}*/
 
+NICE::MultiChannelImageT<double> ColorSpace::rgbtolms( const NICE::MultiChannelImageT<double> &imgrgb )
+{
+  NICE::MultiChannelImageT<double> imglms = NICE::MultiChannelImageT<double>( imgrgb.width(), imgrgb.height() );
+  //preprocessing RGB to XYZ
+  for ( int x = 0;x < imgrgb.width();x++ )
+  {
+    for ( int y = 0;y < imgrgb.height();y++ )
+    {
+      double R, G, B, X, Y, Z, L, M, S;
+      R = imgrgb.get( x, y, 0 ) / 255.0;
+      G = imgrgb.get( x, y, 1 ) / 255.0;
+      B = imgrgb.get( x, y, 2 ) / 255.0;
+
+      ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
+      ColorConversion::ccXYZtoLMS( X, Y, Z, &L, &M, &S );
+      imglms.set( x, y, L, 0 );
+      imglms.set( x, y, M, 1 );
+      imglms.set( x, y, S, 2 );
+    }
+  }
+  return imglms;
+}

+ 34 - 37
baselib/ColorSpace.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ColorSpace.h
 * @brief color space conversion routines
 * @author Michael Koch
@@ -22,44 +22,41 @@ namespace OBJREC {
 class ColorSpace
 {
 
-    protected:
-
-    public:
-	enum {
-	    COLORSPACE_RGB = 0,
-	    COLORSPACE_HSL,
-	    COLORSPACE_LAB,
-        COLORSPACE_LMS,
-        COLORSPACE_OPP,
-	    NUM_COLORSPACES
-	};
+protected:
+
+public:
+  enum {
+    COLORSPACE_RGB = 0,
+    COLORSPACE_HSL,
+    COLORSPACE_LAB,
+    COLORSPACE_LMS,
+    COLORSPACE_OPP,
+    NUM_COLORSPACES
+  };
 //bad position choose better one
-    static void ColorImagetoMultiChannelImage(const NICE::ColorImage &imgrgb,NICE::MultiChannelImageT<double> &genimg);
-    
-#if 0	//entfernt, da Probleme mit Wertebereich, bitte GenericImage und generisches convert benutzen
-         /** convert RGB to hsl*/
-        static NICE::ColorImage rgbtohsl(const NICE::ColorImage &imgrgb);
-        /** convert hsl to RGB*/
-        static NICE::ColorImage hsltorgb(const NICE::ColorImage &imghsl);
-        
-        /** convert RGB to LAB*/
-        static NICE::ColorImage rgbtolab(const NICE::ColorImage &imgrgb);
-        
-        /** convert LAB to RGB*/
-        static NICE::ColorImage labtorgb(const NICE::ColorImage &imglab);
-        
-        /** convert RGB to LMS*/
-        
-        static NICE::ColorImage rgbtolms(const NICE::ColorImage &imgrgb);*/
-#endif
+  static void ColorImagetoMultiChannelImage( const NICE::ColorImage &imgrgb, NICE::MultiChannelImageT<double> &genimg );
+
+  /** convert RGB to hsl*/
+  static NICE::MultiChannelImageT<double> rgbtohsl( const NICE::MultiChannelImageT<double> &imgrgb );
+  /** convert hsl to RGB*/
+  static NICE::MultiChannelImageT<double> hsltorgb( const NICE::MultiChannelImageT<double> &imghsl );
+
+  /** convert RGB to LAB*/
+  static NICE::MultiChannelImageT<double> rgbtolab( const NICE::MultiChannelImageT<double> &imgrgb );
+
+  /** convert LAB to RGB*/
+  static NICE::MultiChannelImageT<double> labtorgb( const NICE::MultiChannelImageT<double> &imglab );
+
+  /** convert RGB to LMS*/
+  static NICE::MultiChannelImageT<double> rgbtolms( const NICE::MultiChannelImageT<double> &imgrgb );
 
-	template<class SrcPixelType,class DstPixelType>
-	static void convert ( NICE::MultiChannelImageT<DstPixelType> & dst, 
-			      const NICE::MultiChannelImageT<SrcPixelType> & src,
-			      int dstColorSpace = COLORSPACE_HSL, 
-			      int srcColorSpace = COLORSPACE_RGB,
-			      double dstM = 255.0,
-			      double srcM = 255.0);
+  template<class SrcPixelType, class DstPixelType>
+  static void convert( NICE::MultiChannelImageT<DstPixelType> & dst,
+                       const NICE::MultiChannelImageT<SrcPixelType> & src,
+                       int dstColorSpace = COLORSPACE_HSL,
+                       int srcColorSpace = COLORSPACE_RGB,
+                       double dstM = 255.0,
+                       double srcM = 255.0 );
 };
 
 } // namespace

+ 9 - 3
baselib/Globals.cpp

@@ -3,6 +3,7 @@
 #include "core/basics/StringTools.h"
 #include "vislearning/baselib/Globals.h"
 #include "core/basics/ossettings.h"
+#include "core/basics/Exception.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -28,9 +29,14 @@ std::string Globals::getCurrentImgFN ( )
 
 std::string Globals::getCacheFilename ( const std::string & root, int cache_mode )
 {
-    std::string filename = Globals::getCurrentImgFN();
-    vector<string> mylistdir;
-    StringTools::split ( filename, FILESEP, mylistdir );
+  std::string filename = Globals::getCurrentImgFN();
+
+  if ( filename.length() == 0 ) {
+    fthrow(Exception, "Globals::getCacheFilename: current image filename was not set, please use Globals::setCurrentImgFN()");
+  }
+
+  vector<string> mylistdir;
+  StringTools::split ( filename, FILESEP, mylistdir );
 
 	int dirpart = 2;
 	if ( cache_mode == SORT_CATEGORIES_SECONDPART )

+ 16 - 16
baselib/Globals.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file Globals.h
 * @brief some routines which provide access to global variables
 * @author Erik Rodner
@@ -14,22 +14,22 @@ namespace OBJREC {
 
 /** @brief some routines which provide access to global variables */
 class Globals {
-    
-    private:
+
+  private:
 
     /** image filename which is currently processed */
     static std::string currentImgFN;
 
-    public:
+  public:
 
-	/** cache mode: none "none" (<root>/<imgfn>), categories "cat" (<root>/<last-dir-part>/<imgfn>),
-	    categories_secondpart "cat2" (<root>/<second-last-dir-part>/<imgfn>) */
+    /** cache mode: none "none" (<root>/<imgfn>), categories "cat" (<root>/<last-dir-part>/<imgfn>),
+        categories_secondpart "cat2" (<root>/<second-last-dir-part>/<imgfn>) */
     enum {
-		SORT_NONE = 0,
-		SORT_CATEGORIES,
-		SORT_CATEGORIES_SECONDPART
+      SORT_NONE = 0,
+      SORT_CATEGORIES,
+      SORT_CATEGORIES_SECONDPART
     };
-   
+
     /** set filename of the image which is currently processed */
     static void setCurrentImgFN ( const std::string & imgfn );
 
@@ -37,15 +37,15 @@ class Globals {
     static std::string getCurrentImgFN ();
 
     /** get a filename which can be used for caching
-	@param root root directory of the global cache
-	@param cache_mode mode of the caching
-	@return cache filename
+    @param root root directory of the global cache
+    @param cache_mode mode of the caching
+    @return cache filename
     */
     static std::string getCacheFilename ( const std::string & root, int cache_mode );
-    
+
     /** get cache mode
-	@param desc description of the cache
-	@return determined cache mode
+    @param desc description of the cache
+    @return determined cache mode
     */
     static int getCacheMode ( const std::string & desc );
 

+ 9 - 10
baselib/ProgressBar.cpp

@@ -1,9 +1,8 @@
-/** 
+/**
  * @file ProgressBar.cpp
  * @brief Show a Progress-Bar with time estimation - threaded
  * @author Michael Koch
  * @date 25/03/2010
-
  */
 #include "core/image/ImageT.h"
 #include "core/vector/VectorT.h"
@@ -22,20 +21,20 @@ using namespace std;
 
 using namespace NICE;
 
-ProgressBar::ProgressBar( std::string a ) : ProgressBarQt(a, true)
+ProgressBar::ProgressBar ( std::string a ) : ProgressBarQt ( a, true )
 {
-    start();
+  start();
 }
 ProgressBar::~ProgressBar()
 {
-	terminate();
-	wait();
+  terminate();
+  wait();
 }
 void ProgressBar::run()
 {
- if(working)
- {
-	 sleep(1);
- }
+  if ( working )
+  {
+    sleep ( 1 );
+  }
 }
 

+ 7 - 7
baselib/ProgressBar.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBar.h
  * @brief Show a Progress-Bar with time estimation - threaded
  * @author Michael Koch
@@ -19,12 +19,12 @@ namespace OBJREC
 /** @brief show a Progress-Bar with time estimation */
 class ProgressBar: public QThread, public ProgressBarQt
 {
-public:
-	ProgressBar(std::string a = "ProgressBar");
-	/** simple destructor */
-	virtual ~ProgressBar();
-	virtual void run();
-private:
+  public:
+    ProgressBar ( std::string a = "ProgressBar" );
+    /** simple destructor */
+    virtual ~ProgressBar();
+    virtual void run();
+  private:
 
 };
 

+ 128 - 128
baselib/ProgressBarQt.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBarQt.cpp
  * @brief Show a Progress-Bar with time estimation
  * @author Michael Koch
@@ -24,174 +24,174 @@ using namespace std;
 
 using namespace NICE;
 
-ProgressBarQt::ProgressBarQt(const std::string & _name, bool _useGraphics)
-	: useGraphics (_useGraphics)
+ProgressBarQt::ProgressBarQt ( const std::string & _name, bool _useGraphics )
+    : useGraphics ( _useGraphics )
 {
-	name = _name;
-	step = 0;
-
-	display_on = false;
-	working = true;
-	if (graphicIsAvailable())
-	{
-		if (qApp == NULL)
-		{
-			QtFramework::instance();
-		}
-
-		dialogwindow = new QWidget;
-
-		progressdialog = new QProgressDialog("Process at work ...", "Cancel",
-				0, 100);
-		layout = new QGridLayout(dialogwindow, 1, 1);
-		layout->addWidget(progressdialog, 0, 0);
-		dialogwindow->setLayout(layout);
-	}
-	reset(_name);
+  name = _name;
+  step = 0;
+
+  display_on = false;
+  working = true;
+  if ( graphicIsAvailable() )
+  {
+    if ( qApp == NULL )
+    {
+      QtFramework::instance();
+    }
+
+    dialogwindow = new QWidget;
+
+    progressdialog = new QProgressDialog ( "Process at work ...", "Cancel",
+                                           0, 100 );
+    layout = new QGridLayout ( dialogwindow, 1, 1 );
+    layout->addWidget ( progressdialog, 0, 0 );
+    dialogwindow->setLayout ( layout );
+  }
+  reset ( _name );
 }
 
 ProgressBarQt::~ProgressBarQt()
 {
 }
 
-void ProgressBarQt::timediff2str(char *text, long time)
+void ProgressBarQt::timediff2str ( char *text, long time )
 {
-	int seconds;
-	int minutes;
-	int hours;
-	int milliseconds;
-
-	milliseconds = time % 100;
-	time /= 100;
-	seconds = time % 60;
-	time /= 60;
-	minutes = time % 60;
-	time /= 60;
-	hours = time;
-
-	if (hours != 0)
-	{
-		sprintf(text, "%dh %dm %d.%d s", hours, minutes, seconds, milliseconds);
-	}
-	else if (minutes != 0)
-	{
-		sprintf(text, "%dm %d.%d s", minutes, seconds, milliseconds);
-	}
-	else
-	{
-		sprintf(text, "%d.%d s", seconds, milliseconds);
-	}
+  int seconds;
+  int minutes;
+  int hours;
+  int milliseconds;
+
+  milliseconds = time % 100;
+  time /= 100;
+  seconds = time % 60;
+  time /= 60;
+  minutes = time % 60;
+  time /= 60;
+  hours = time;
+
+  if ( hours != 0 )
+  {
+    sprintf ( text, "%dh %dm %d.%d s", hours, minutes, seconds, milliseconds );
+  }
+  else if ( minutes != 0 )
+  {
+    sprintf ( text, "%dm %d.%d s", minutes, seconds, milliseconds );
+  }
+  else
+  {
+    sprintf ( text, "%d.%d s", seconds, milliseconds );
+  }
 }
 
-void ProgressBarQt::displayTimeStat(int posy, char *text, long time)
+void ProgressBarQt::displayTimeStat ( int posy, char *text, long time )
 {
-	// Text (char *str,int x0,int y0,int val,int exp,Image img);
-	char disptext[200];
-	char timetext[200];
+  // Text (char *str,int x0,int y0,int val,int exp,Image img);
+  char disptext[200];
+  char timetext[200];
 
-	timediff2str(timetext, time);
-	sprintf(disptext, "%s %s", text, timetext);
+  timediff2str ( timetext, time );
+  sprintf ( disptext, "%s %s", text, timetext );
 
 }
 
 double ProgressBarQt::getCurrentTime()
 {
-	struct timeval curtime;
+  struct timeval curtime;
 
-	gettimeofday(&curtime, NULL);
+  gettimeofday ( &curtime, NULL );
 
-	return curtime.tv_sec * 100.0 + curtime.tv_usec / 10000.0;
+  return curtime.tv_sec * 100.0 + curtime.tv_usec / 10000.0;
 }
 
 void ProgressBarQt::show()
 {
-	if (!display_on)
-	{
-		display_on = true;
-	}
-	if (graphicIsAvailable())
-	{
-		if (qApp == NULL)
-		{
-			QtFramework::instance();
-		}
-		dialogwindow->show();
-	}
+  if ( !display_on )
+  {
+    display_on = true;
+  }
+  if ( graphicIsAvailable() )
+  {
+    if ( qApp == NULL )
+    {
+      QtFramework::instance();
+    }
+    dialogwindow->show();
+  }
 }
 
 void ProgressBarQt::hide()
 {
 
-	if (display_on)
-	{
-		//		Show ( OFF, display, name );
-		display_on = false;
-	}
-	if (graphicIsAvailable())
-	{
-		dialogwindow->hide();
-	}
+  if ( display_on )
+  {
+    //  Show ( OFF, display, name );
+    display_on = false;
+  }
+  if ( graphicIsAvailable() )
+  {
+    dialogwindow->hide();
+  }
 }
 
 void ProgressBarQt::stop()
 {
 
-	working = false;
+  working = false;
 }
 
-void ProgressBarQt::reset(const std::string & _name)
+void ProgressBarQt::reset ( const std::string & _name )
 {
-	name = _name;
-	step = 0;
-	elapsed_time = 0;
-	avg_time_step = 0;
-	start_time = getCurrentTime();
+  name = _name;
+  step = 0;
+  elapsed_time = 0;
+  avg_time_step = 0;
+  start_time = getCurrentTime();
 }
 
-void ProgressBarQt::update(int count)
+void ProgressBarQt::update ( int count )
 {
-	step++;
-
-	double progress = step / (double) count;
-
-	elapsed_time = getCurrentTime() - start_time;
-	avg_time_step = elapsed_time / step;
-	estimated_time = (count - step) * avg_time_step;
-
-	size_t mod;
-	if (avg_time_step > 50.0)
-		mod = 1;
-	else
-		mod = (size_t) (50.0 / avg_time_step) + 1;
-
-	if ((mod <= 1) || (step % mod == 0))
-	{
-		char percent_text[10];
-		sprintf(percent_text, "%4.2f %%", step * 100.0 / count);
-
-		displayTimeStat(0, "Elapsed Time : ", (long int) elapsed_time);
-		displayTimeStat(1, "Estimated Time : ", (long int) estimated_time);
-		displayTimeStat(2, "Avg. Time per step : ", (long int) avg_time_step);
-
-		char eltime[200];
-		char estime[200];
-		char avgtime[200];
-		timediff2str(eltime, (long int) elapsed_time);
-		timediff2str(estime, (long int) estimated_time);
-		timediff2str(avgtime, (long int) avg_time_step);
-		fprintf(
-				stderr,
-				"[PROGRESS] %s %s (elapsed time %s, estimated time %s, avg %s), \n",
-				name.c_str(), percent_text, eltime, estime, avgtime);
-		//set progress value.
-		if (graphicIsAvailable())
-		{
-			progressdialog->setValue(progress * 100);
-		}
-	}
+  step++;
+
+  double progress = step / ( double ) count;
+
+  elapsed_time = getCurrentTime() - start_time;
+  avg_time_step = elapsed_time / step;
+  estimated_time = ( count - step ) * avg_time_step;
+
+  size_t mod;
+  if ( avg_time_step > 50.0 )
+    mod = 1;
+  else
+    mod = ( size_t ) ( 50.0 / avg_time_step ) + 1;
+
+  if ( ( mod <= 1 ) || ( step % mod == 0 ) )
+  {
+    char percent_text[10];
+    sprintf ( percent_text, "%4.2f %%", step * 100.0 / count );
+
+    displayTimeStat ( 0, "Elapsed Time : ", ( long int ) elapsed_time );
+    displayTimeStat ( 1, "Estimated Time : ", ( long int ) estimated_time );
+    displayTimeStat ( 2, "Avg. Time per step : ", ( long int ) avg_time_step );
+
+    char eltime[200];
+    char estime[200];
+    char avgtime[200];
+    timediff2str ( eltime, ( long int ) elapsed_time );
+    timediff2str ( estime, ( long int ) estimated_time );
+    timediff2str ( avgtime, ( long int ) avg_time_step );
+    fprintf (
+      stderr,
+      "[PROGRESS] %s %s (elapsed time %s, estimated time %s, avg %s), \n",
+      name.c_str(), percent_text, eltime, estime, avgtime );
+    //set progress value.
+    if ( graphicIsAvailable() )
+    {
+      progressdialog->setValue ( progress * 100 );
+    }
+  }
 }
 
 bool ProgressBarQt::graphicIsAvailable()
 {
-	return (useGraphics && (getenv("DISPLAY") != NULL));
+  return ( useGraphics && ( getenv ( "DISPLAY" ) != NULL ) );
 }

+ 44 - 44
baselib/ProgressBarQt.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBarQt.h
  * @brief Show a Progress-Bar with time estimation
  * @author Michael Koch
@@ -20,66 +20,66 @@ namespace OBJREC {
 class ProgressBarQt
 {
 
-protected:
+  protected:
 
-	QGridLayout* layout;
-	QWidget* dialogwindow;
-	QProgressDialog* progressdialog;
+    QGridLayout* layout;
+    QWidget* dialogwindow;
+    QProgressDialog* progressdialog;
 
 
-	NICE::Image display;
-	bool display_on;
-	bool working;
-	double start_time;
-	double avg_time_step;
-	double elapsed_time;
-	double estimated_time;
+    NICE::Image display;
+    bool display_on;
+    bool working;
+    double start_time;
+    double avg_time_step;
+    double elapsed_time;
+    double estimated_time;
 
-	int step;
+    int step;
 
-	int bar_width;
-	int bar_height;
-	int bar_top;
-	int bar_borderx;
+    int bar_width;
+    int bar_height;
+    int bar_top;
+    int bar_borderx;
 
-	int text_top;
-	int text_height;
+    int text_top;
+    int text_height;
 
-	std::string name;
+    std::string name;
 
-	bool useGraphics;
+    bool useGraphics;
 
-	void timediff2str(char *text, long time);
-	void displayTimeStat(int posy, char *text, long time);
-	double getCurrentTime();
-	bool graphicIsAvailable();
+    void timediff2str ( char *text, long time );
+    void displayTimeStat ( int posy, char *text, long time );
+    double getCurrentTime();
+    bool graphicIsAvailable();
 
-public:
+  public:
 
-	/** constructor 
-	 @param name name of the operation
-	 */
-	ProgressBarQt(const std::string & name, bool useGraphics = true);
+    /** constructor
+     @param name name of the operation
+     */
+    ProgressBarQt ( const std::string & name, bool useGraphics = true );
 
-	/** simple destructor */
-	virtual ~ProgressBarQt();
+    /** simple destructor */
+    virtual ~ProgressBarQt();
 
-	/** reset the progress bar and the corresponding
-	 name of the operation */
+    /** reset the progress bar and the corresponding
+     name of the operation */
 
-	void reset(const std::string & name);
+    void reset ( const std::string & name );
 
-	/** show the progress bar */
-	void show();
-	/** hide the progress bar */
-	void hide();
+    /** show the progress bar */
+    void show();
+    /** hide the progress bar */
+    void hide();
 
-	void stop();
+    void stop();
 
-	/** update the progress bar
-	 @param count number of total steps of this operation
-	 */
-	void update(int count);
+    /** update the progress bar
+     @param count number of total steps of this operation
+     */
+    void update ( int count );
 
 };
 } // namespace

+ 26 - 26
baselib/RunningStat.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file RunningStat.h
  * @brief B. P. Welford Computation of Mean and Variance download at: http://www.johndcook.com/standard_deviation.html
  * @author Michael Koch
@@ -12,31 +12,31 @@ namespace OBJREC {
 /** @brief online statistics */
 class RunningStat
 {
-     public:
-          RunningStat() : m_n(0) {}
-
-	  /** clear the current statistics */
-          void Clear();
-          
-	  /** add a new data element */
-          void Push(double x);
-          
-	  /** get number of data elements */
-          size_t NumDataValues() const;
-
-	  /** get mean value */
-          double Mean() const;
-          
-	  /** get variance */
-	  double Variance() const;
-          
-	  /** get standard deviation */
-          double StandardDeviation() const;
-         
-
-     private:
-          size_t m_n;
-          double m_oldM, m_newM, m_oldS, m_newS;
+  public:
+    RunningStat() : m_n ( 0 ) {}
+
+    /** clear the current statistics */
+    void Clear();
+
+    /** add a new data element */
+    void Push ( double x );
+
+    /** get number of data elements */
+    size_t NumDataValues() const;
+
+    /** get mean value */
+    double Mean() const;
+
+    /** get variance */
+    double Variance() const;
+
+    /** get standard deviation */
+    double StandardDeviation() const;
+
+
+  private:
+    size_t m_n;
+    double m_oldM, m_newM, m_oldS, m_newS;
 };
 
 }

+ 225 - 225
cbaselib/CachedExample.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file CachedExample.cpp
 * @brief data caching
 * @author Erik Rodner
@@ -23,292 +23,292 @@ using namespace NICE;
 
 void CachedExample::init ()
 {
-    dchannels = new MultiChannelImageT<double> [D_NUMCHANNELS];
-    ichannels = new MultiChannelImageT<int> [I_NUMCHANNELS];
-    lchannels = new MultiChannelImageT<long> [L_NUMCHANNELS];
-
-    svmap = new SparseVector *[SVNUMCHANNELS];
-    svmap_xsize = new int [SVNUMCHANNELS];
-    svmap_ysize = new int [SVNUMCHANNELS];
-    for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
-    {
-	svmap[k] = NULL;
-	svmap_xsize[k] = 0;
-	svmap_ysize[k] = 0;
-    }
+  dchannels = new MultiChannelImageT<double> [D_NUMCHANNELS];
+  ichannels = new MultiChannelImageT<int> [I_NUMCHANNELS];
+  lchannels = new MultiChannelImageT<long> [L_NUMCHANNELS];
+
+  svmap = new SparseVector *[SVNUMCHANNELS];
+  svmap_xsize = new int [SVNUMCHANNELS];
+  svmap_ysize = new int [SVNUMCHANNELS];
+  for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
+  {
+    svmap[k] = NULL;
+    svmap_xsize[k] = 0;
+    svmap_ysize[k] = 0;
+  }
+}
+
+CachedExample::CachedExample ( const std::string & _imgfn,
+                               int _newWidth,
+                               int _newHeight )
+{
+  imgfn = _imgfn;
+  newWidth = _newWidth;
+  newHeight = _newHeight;
+  Preprocess::getImageSize ( _imgfn, oxsize, oysize );
+  init();
+  hasColorInformation = true;
 }
 
-CachedExample::CachedExample( const std::string & _imgfn,
-			      int _newWidth,
-			      int _newHeight )
+CachedExample::CachedExample ( const NICE::Image & _img )
 {
-    imgfn = _imgfn;
-    newWidth = _newWidth;
-    newHeight = _newHeight;
-    Preprocess::getImageSize ( _imgfn, oxsize, oysize );
-    init();
-    hasColorInformation = true;
+  imgfn = "";
+  newWidth = -1;
+  newHeight = -1;
+  init();
+
+  oxsize = _img.width();
+  oysize = _img.height();
+  int *gray = new int [ oxsize*oysize ];
+  int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+      gray[k] = _img.getPixel ( x, y );
+
+  ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, false );
+  ichannels[I_GRAYVALUES].setImage ( gray, oxsize, oysize, 0 );
+
+  hasColorInformation = false;
 }
 
-CachedExample::CachedExample( const NICE::Image & _img )
+CachedExample::CachedExample ( const NICE::ColorImage & img, bool disableGrayConversion )
 {
-    imgfn = "";
-    newWidth = -1;
-    newHeight = -1;
-    init();
-
-    oxsize = _img.width();
-    oysize = _img.height();
-    int *gray = new int [ oxsize*oysize ];
+  imgfn = "";
+  oxsize = img.width();
+  oysize = img.height();
+  newWidth = -1;
+  newHeight = -1;
+  init();
+
+  if ( ! disableGrayConversion )
+  {
+    // refactor-nice.pl: check this substitution
+    // old: Image imggray;
+    NICE::Image imggray;
+    ICETools::calcGrayImage ( img, imggray );
+
+    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
+    int *gray = ichannels[I_GRAYVALUES].data[0];
     int k = 0;
     for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	    gray[k] = _img.getPixel(x,y);
+      for ( int x = 0 ; x < oxsize ; x++, k++ )
+        // refactor-nice.pl: check this substitution
+        // old: gray[k] = GetVal(imggray,x,y);
+        gray[k] = imggray.getPixel ( x, y );
+  }
 
-    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, false );
-    ichannels[I_GRAYVALUES].setImage ( gray, oxsize, oysize, 0 );
+  ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
 
-    hasColorInformation = false;
-}
-
-CachedExample::CachedExample( const NICE::ColorImage & img, bool disableGrayConversion )
-{
-    imgfn = "";
-    oxsize = img.width();
-    oysize = img.height();
-    newWidth = -1;
-    newHeight = -1;
-    init();
-
-    if ( ! disableGrayConversion )
+  long int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
     {
-	// refactor-nice.pl: check this substitution
-	// old: Image imggray;
-	NICE::Image imggray;
-	ICETools::calcGrayImage ( img, imggray );
-
-	ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
-	int *gray = ichannels[I_GRAYVALUES].data[0];
-	int k = 0;
-	for ( int y = 0 ; y < oysize ; y++ )
-	    for ( int x = 0 ; x < oxsize ; x++,k++ )
-		// refactor-nice.pl: check this substitution
-		// old: gray[k] = GetVal(imggray,x,y);
-		gray[k] = imggray.getPixel(x,y);
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[0][k] = GetVal(img.RedImage(), x, y);
+      ichannels[I_COLOR].data[0][k] = img.getPixel ( x, y, 0 );
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[1][k] = GetVal(img.GreenImage(), x, y);
+      ichannels[I_COLOR].data[1][k] = img.getPixel ( x, y, 1 );
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[2][k] = GetVal(img.BlueImage(), x, y);
+      ichannels[I_COLOR].data[2][k] = img.getPixel ( x, y, 2 );
     }
 
-    ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
-
-    long int k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	{
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[0][k] = GetVal(img.RedImage(), x, y);
-	    ichannels[I_COLOR].data[0][k] = img.getPixel(x,y,0);
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[1][k] = GetVal(img.GreenImage(), x, y);
-	    ichannels[I_COLOR].data[1][k] = img.getPixel(x,y,1);
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[2][k] = GetVal(img.BlueImage(), x, y);
-	    ichannels[I_COLOR].data[2][k] = img.getPixel(x,y,2);
-	}
-
-    hasColorInformation = true;
+  hasColorInformation = true;
 }
-	
+
 CachedExample::~CachedExample()
 {
-    delete [] dchannels;
-    delete [] ichannels;
-    delete [] lchannels;
-
-    for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
-	if ( svmap[k] != NULL )
-	    delete [] (svmap[k]);
-
-    delete [] svmap;
-    delete [] svmap_xsize;
-    delete [] svmap_ysize;
-
-    // remove all temporary files
-    for ( map<int, string>::const_iterator j = dtemps.begin();
-					   j != dtemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
-    
-    for ( map<int, string>::const_iterator j = itemps.begin();
-					   j != itemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
-
-    for ( map<int, string>::const_iterator j = ltemps.begin();
-					   j != ltemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
+  delete [] dchannels;
+  delete [] ichannels;
+  delete [] lchannels;
+
+  for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
+    if ( svmap[k] != NULL )
+      delete [] ( svmap[k] );
+
+  delete [] svmap;
+  delete [] svmap_xsize;
+  delete [] svmap_ysize;
+
+  // remove all temporary files
+  for ( map<int, string>::const_iterator j = dtemps.begin();
+        j != dtemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
+
+  for ( map<int, string>::const_iterator j = itemps.begin();
+        j != itemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
+
+  for ( map<int, string>::const_iterator j = ltemps.begin();
+        j != ltemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
 
 }
 
 void CachedExample::readImageData ()
 {
-    if ( imgfn == "" ) return;
+  if ( imgfn == "" ) return;
 
-    NICE::Image orig = Preprocess::ReadImgAdv(imgfn);
-    NICE::Image imggray;
+  NICE::Image orig = Preprocess::ReadImgAdv ( imgfn );
+  NICE::Image imggray;
 
-    if ( newWidth > 0 )
-	Conversions::resizeImage ( orig, imggray, newWidth, newHeight );
-    else
-	imggray = orig;
+  if ( newWidth > 0 )
+    Conversions::resizeImage ( orig, imggray, newWidth, newHeight );
+  else
+    imggray = orig;
 
-    oxsize = imggray.width();
-    oysize = imggray.height();
+  oxsize = imggray.width();
+  oysize = imggray.height();
 
-    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
-    int *gray = ichannels[I_GRAYVALUES].data[0];
-    int k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	    gray[k] = imggray.getPixel(x,y);
+  ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
+  int *gray = ichannels[I_GRAYVALUES].data[0];
+  int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+      gray[k] = imggray.getPixel ( x, y );
 }
 
 void CachedExample::readImageDataRGB ()
 {
-    if ( imgfn == "" ) return;
-
-    NICE::ColorImage img;
-    try {
-	img = Preprocess::ReadImgAdvRGB(imgfn);
-    } catch ( NICE::ImageException & ) {
-	fprintf (stderr, "error reading rgb image %s\n", imgfn.c_str());
-	hasColorInformation = false;
-	return;
-    }
+  if ( imgfn == "" ) return;
 
-    oxsize = img.width();
-    oysize = img.height();
+  NICE::ColorImage img;
+  try {
+    img = Preprocess::ReadImgAdvRGB ( imgfn );
+  } catch ( NICE::ImageException & ) {
+    fprintf ( stderr, "error reading rgb image %s\n", imgfn.c_str() );
+    hasColorInformation = false;
+    return;
+  }
 
-    hasColorInformation = true;
-    
-    ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
+  oxsize = img.width();
+  oysize = img.height();
 
-    long k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	{
-	    ichannels[I_COLOR].data[0][k] = img.getPixel(x,y,0);
-	    ichannels[I_COLOR].data[1][k] = img.getPixel(x,y,1);
-	    ichannels[I_COLOR].data[2][k] = img.getPixel(x,y,2);
-	}
+  hasColorInformation = true;
+
+  ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
+
+  long k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+    {
+      ichannels[I_COLOR].data[0][k] = img.getPixel ( x, y, 0 );
+      ichannels[I_COLOR].data[1][k] = img.getPixel ( x, y, 1 );
+      ichannels[I_COLOR].data[2][k] = img.getPixel ( x, y, 2 );
+    }
 }
 
 void CachedExample::calcIntegralImage ()
 {
-    if (ichannels[I_GRAYVALUES].xsize == 0)
+  if ( ichannels[I_GRAYVALUES].xsize == 0 )
+  {
+    readImageData ();
+    if ( ichannels[I_GRAYVALUES].xsize == 0 )
     {
-	readImageData ();
-	if ( ichannels[I_GRAYVALUES].xsize == 0 )
-	{
-	    fprintf (stderr, "CachedExample::getChannel: unable to recover data channel\n");
-	    exit(-1);
-	}
+      fprintf ( stderr, "CachedExample::getChannel: unable to recover data channel\n" );
+      exit ( -1 );
     }
+  }
 
-    lchannels[L_INTEGRALIMAGE].reInit ( ichannels[I_GRAYVALUES].xsize,
-					ichannels[I_GRAYVALUES].ysize,
-					1, true );
-    
-		GenericImageTools::calcIntegralImage ( 
-		lchannels[L_INTEGRALIMAGE].data[0], 
-		ichannels[I_GRAYVALUES].data[0], 
-		ichannels[I_GRAYVALUES].xsize, 
-		ichannels[I_GRAYVALUES].ysize );
+  lchannels[L_INTEGRALIMAGE].reInit ( ichannels[I_GRAYVALUES].xsize,
+                                      ichannels[I_GRAYVALUES].ysize,
+                                      1, true );
+
+  GenericImageTools::calcIntegralImage (
+    lchannels[L_INTEGRALIMAGE].data[0],
+    ichannels[I_GRAYVALUES].data[0],
+    ichannels[I_GRAYVALUES].xsize,
+    ichannels[I_GRAYVALUES].ysize );
 
 }
 
-void CachedExample::buildIntegralSV ( int svchannel, 
-				      SparseVector *_map, 
-				      int xsize_s, int ysize_s )
+void CachedExample::buildIntegralSV ( int svchannel,
+                                      SparseVector *_map,
+                                      int xsize_s, int ysize_s )
 {
-    SparseVector *map = _map;
-    svmap[svchannel] = _map;
-    svmap_xsize[svchannel] = xsize_s;
-    svmap_ysize[svchannel] = ysize_s;
+  SparseVector *map = _map;
+  svmap[svchannel] = _map;
+  svmap_xsize[svchannel] = xsize_s;
+  svmap_ysize[svchannel] = ysize_s;
 
-    int k = xsize_s;
-    for ( int y = 1 ; y < ysize_s; y++, k+=xsize_s )
-	map[k].add ( (map[k-xsize_s]) );
+  int k = xsize_s;
+  for ( int y = 1 ; y < ysize_s; y++, k += xsize_s )
+    map[k].add ( ( map[k-xsize_s] ) );
 
-    k = 1;
-    for ( int x = 1 ; x < xsize_s; x++, k++ )
-	map[k].add ( (map[k-1]) );
+  k = 1;
+  for ( int x = 1 ; x < xsize_s; x++, k++ )
+    map[k].add ( ( map[k-1] ) );
 
-    k = xsize_s + 1;
+  k = xsize_s + 1;
 
-    for ( int y = 1 ; y < ysize_s ; y++,k++ )
+  for ( int y = 1 ; y < ysize_s ; y++, k++ )
+  {
+    for ( int x = 1 ; x < xsize_s ; x++, k++ )
     {
-	for ( int x = 1 ; x < xsize_s ; x++,k++ )
-	{
-	    map[k].add ( (map[k-1]) );
-	    map[k].add ( (map[k-xsize_s]) );
-	    map[k].add ( (map[k-xsize_s-1]), -1.0 );
-	}
+      map[k].add ( ( map[k-1] ) );
+      map[k].add ( ( map[k-xsize_s] ) );
+      map[k].add ( ( map[k-xsize_s-1] ), -1.0 );
     }
+  }
 }
 
-void CachedExample::setSVMap ( int svchannel, 
-			      SparseVector *_map, 
-			      int xsize_s, int ysize_s )
+void CachedExample::setSVMap ( int svchannel,
+                               SparseVector *_map,
+                               int xsize_s, int ysize_s )
 {
-    svmap[svchannel] = _map;
-    svmap_xsize[svchannel] = xsize_s;
-    svmap_ysize[svchannel] = ysize_s;
+  svmap[svchannel] = _map;
+  svmap_xsize[svchannel] = xsize_s;
+  svmap_ysize[svchannel] = ysize_s;
 }
 
 SparseVector *CachedExample::getSVMap ( int svchannel,
-				        int & _xsize, int & _ysize,
-				        int & _tm_xsize, int & _tm_ysize ) const
+                                        int & _xsize, int & _ysize,
+                                        int & _tm_xsize, int & _tm_ysize ) const
 {
-    _xsize = oxsize;
-    _ysize = oysize;
-    _tm_xsize = svmap_xsize[svchannel];
-    _tm_ysize = svmap_ysize[svchannel];
-    assert ( svmap[svchannel] != NULL );
-    return svmap[svchannel];
+  _xsize = oxsize;
+  _ysize = oysize;
+  _tm_xsize = svmap_xsize[svchannel];
+  _tm_ysize = svmap_ysize[svchannel];
+  assert ( svmap[svchannel] != NULL );
+  return svmap[svchannel];
 }
 
 bool CachedExample::colorInformationAvailable() const
 {
-    if ( hasColorInformation ) return true;
-    else {
-	if ( imgfn.size() == 0 ) return false;
-
-	int tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr;
-	// refactor: InfImgFile ( imgfn, tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr );
-	ImageFile imgf ( imgfn );
-	const ImageFile::Header & imgfheader = imgf.getHeader();
-	tmp_xsize = imgfheader.width;
-	tmp_ysize = imgfheader.height;
-	tmp_maxval = 255;
-	tmp_nr = imgfheader.channel;
-
-	if ( tmp_nr > 1 ) return true;
-	else return false;
-    }
+  if ( hasColorInformation ) return true;
+  else {
+    if ( imgfn.size() == 0 ) return false;
+
+    int tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr;
+    // refactor: InfImgFile ( imgfn, tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr );
+    ImageFile imgf ( imgfn );
+    const ImageFile::Header & imgfheader = imgf.getHeader();
+    tmp_xsize = imgfheader.width;
+    tmp_ysize = imgfheader.height;
+    tmp_maxval = 255;
+    tmp_nr = imgfheader.channel;
+
+    if ( tmp_nr > 1 ) return true;
+    else return false;
+  }
 }
 
 void CachedExample::dropPreCached()
 {
-    dropImages<double> ( dchannels, dtemps, D_NUMCHANNELS );
-    dropImages<int> ( ichannels, itemps, I_NUMCHANNELS );
-    dropImages<long> ( lchannels, ltemps, L_NUMCHANNELS );
+  dropImages<double> ( dchannels, dtemps, D_NUMCHANNELS );
+  dropImages<int> ( ichannels, itemps, I_NUMCHANNELS );
+  dropImages<long> ( lchannels, ltemps, L_NUMCHANNELS );
 }

+ 340 - 338
cbaselib/ClassNames.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ClassNames.cpp
 * @brief simple interface for class name confusion
 * @author Erik Rodner
@@ -27,454 +27,456 @@ using namespace NICE;
 
 ClassNames::ClassNames()
 {
-	maxClassNo = 0;
+  maxClassNo = 0;
 }
 
-ClassNames::ClassNames ( const ClassNames & cn, 
-			 const std::string & classselection )
+ClassNames::ClassNames ( const ClassNames & cn,
+                         const std::string & classselection )
 {
-	std::set<int> selection;
-	cn.getSelection ( classselection, selection );
-	maxClassNo = 0;
-
-	store ( cerr );
-
-	for ( map<string, string>::const_iterator i  = cn.tbl_code_text.begin();
-						  i != cn.tbl_code_text.end();
-						  i++ )
-	{
-		const std::string & classname = i->second;
-		std::string code = i->first;
-
-		if ( cn.tbl_code_classno.find(code) == cn.tbl_code_classno.end() )
-		{
-			fprintf (stderr, "class %s excluded in base classnames\n", code.c_str() );
-			continue;
-		}
-
-		int classno = cn.classno(code);
-		if ( selection.find(classno) != selection.end() )
-		{
-			addClass( classno, code, classname );
-			if ( classno > maxClassNo ) maxClassNo = classno;
+  std::set<int> selection;
+  cn.getSelection ( classselection, selection );
+  maxClassNo = 0;
+
+  store ( cerr );
+
+  for ( map<string, string>::const_iterator i  = cn.tbl_code_text.begin();
+        i != cn.tbl_code_text.end();
+        i++ )
+  {
+    const std::string & classname = i->second;
+    std::string code = i->first;
+
+    if ( cn.tbl_code_classno.find ( code ) == cn.tbl_code_classno.end() )
+    {
+      fprintf ( stderr, "class %s excluded in base classnames\n", code.c_str() );
+      continue;
+    }
+
+    int classno = cn.classno ( code );
+    if ( selection.find ( classno ) != selection.end() )
+    {
+      addClass ( classno, code, classname );
+      if ( classno > maxClassNo ) maxClassNo = classno;
 #ifdef DEBUG_ClassNames
-			fprintf (stderr, "class %s (%d) inherited\n", code.c_str(), classno );
+      fprintf ( stderr, "class %s (%d) inherited\n", code.c_str(), classno );
 #endif
-		} else {
+    } else {
 #ifdef DEBUG_ClassNames
-			fprintf (stderr, "class %s (%d) excluded in selection\n", code.c_str(), classno );
+      fprintf ( stderr, "class %s (%d) excluded in selection\n", code.c_str(), classno );
 #endif
-		}
-	}
+    }
+  }
 }
 
 ClassNames::ClassNames ( const ClassNames & cn )
-	: tbl_code_text(cn.tbl_code_text), tbl_text_code(cn.tbl_text_code),
-	  tbl_classno_code(cn.tbl_classno_code), tbl_code_classno(cn.tbl_code_classno),
-	  tbl_color_classno(tbl_color_classno), tbl_classno_color(cn.tbl_classno_color), maxClassNo(cn.maxClassNo)
+    : tbl_code_text ( cn.tbl_code_text ), tbl_text_code ( cn.tbl_text_code ),
+    tbl_classno_code ( cn.tbl_classno_code ), tbl_code_classno ( cn.tbl_code_classno ),
+    tbl_color_classno ( tbl_color_classno ), tbl_classno_color ( cn.tbl_classno_color ), maxClassNo ( cn.maxClassNo )
 {
 }
 
 ClassNames::~ClassNames()
 {
 }
-	
+
 
 int ClassNames::classnoFromText ( std::string text ) const
 {
-	map<string, string>::const_iterator j = tbl_text_code.find(text);
-	if ( j == tbl_text_code.end() ) return -1;
+  map<string, string>::const_iterator j = tbl_text_code.find ( text );
+  if ( j == tbl_text_code.end() ) return -1;
 
-	map<string, int>::const_iterator jj = tbl_code_classno.find(j->second);
-	if ( jj == tbl_code_classno.end() ) return -1;
+  map<string, int>::const_iterator jj = tbl_code_classno.find ( j->second );
+  if ( jj == tbl_code_classno.end() ) return -1;
 
-	return jj->second;
+  return jj->second;
 }
 
 void ClassNames::getSelection ( const std::string & classselection,
-				std::set<int> & classnos ) const
+                                std::set<int> & classnos ) const
 {
-	if ( classselection.size() <= 0 ) return;
-
-	std::vector<string> classlist;
-	StringTools::split ( classselection, ',', classlist );
-
-	if ( classlist.size() <= 0 )
-	{
-	fprintf (stderr, "FATAL ERROR: wrong format for classselection\n");
-	exit(-1);
-	} else if ( classlist[0] == "*" )
-	{
-	map<string, bool> forbidden_classes;
-	for ( size_t k = 1 ; k < classlist.size() ; k++ )
-		if ( classlist[k].substr(0,1) == "-" )
-		{
-			std::string f_class = classlist[k].substr(1);
+  if ( classselection.size() <= 0 ) return;
+
+  std::vector<string> classlist;
+  StringTools::split ( classselection, ',', classlist );
+
+  if ( classlist.size() <= 0 )
+  {
+    fprintf ( stderr, "FATAL ERROR: wrong format for classselection\n" );
+    exit ( -1 );
+  } else if ( classlist[0] == "*" )
+  {
+    map<string, bool> forbidden_classes;
+    for ( size_t k = 1 ; k < classlist.size() ; k++ )
+      if ( classlist[k].substr ( 0, 1 ) == "-" )
+      {
+        std::string f_class = classlist[k].substr ( 1 );
 #if defined DEBUG_ClassNames
-			fprintf (stderr, "ClassNames: class %s excluded !\n", f_class.c_str() );
+        fprintf ( stderr, "ClassNames: class %s excluded !\n", f_class.c_str() );
 #endif
-			forbidden_classes[ f_class ] = true;
-		} else {
-			fprintf (stderr, "FATAL ERROR: wrong format for classselection: *,-class0,class1,...\n");
-			exit(-1);
-		}
-   
-	for ( map<int, string>::const_iterator i  = tbl_classno_code.begin();
-						  i != tbl_classno_code.end();
-						  i++ )
-	{
-		int myclassno = i->first;
-		const std::string & classname = text(myclassno);
-		if ( forbidden_classes.find(classname) != forbidden_classes.end() )
-		continue;
-		
-		classnos.insert ( myclassno );
-	}
-	} else {
-		for ( vector<string>::const_iterator i  = classlist.begin();
-							i != classlist.end();
-							i++ )
-		{
-			const std::string & classname = *i;
-			map<string, string>::const_iterator j = tbl_text_code.find(classname);
-	
-			if ( j == tbl_text_code.end() )
-			{
-				fprintf (stderr, "ClassNames: FATAL ERROR This is not a selection of a subset: %s [%s]\n",
-					classname.c_str(), classselection.c_str());
-				exit(-1);
-			}
-	
-			const std::string & code = j->second;
-			int myclassno = classno (code);
-	
-			if ( myclassno < 0 ) {
-				fprintf (stderr, "ClassNames: FATAL ERROR This is not a selection of a subset\n");
-				exit(-1);
-			}
-			classnos.insert ( myclassno );
-		}
-	}
+        forbidden_classes[ f_class ] = true;
+      } else {
+        fprintf ( stderr, "FATAL ERROR: wrong format for classselection: *,-class0,class1,...\n" );
+        exit ( -1 );
+      }
+
+    for ( map<int, string>::const_iterator i  = tbl_classno_code.begin();
+          i != tbl_classno_code.end();
+          i++ )
+    {
+      int myclassno = i->first;
+      const std::string & classname = text ( myclassno );
+      if ( forbidden_classes.find ( classname ) != forbidden_classes.end() )
+        continue;
+
+      classnos.insert ( myclassno );
+    }
+  } else {
+    for ( vector<string>::const_iterator i  = classlist.begin();
+          i != classlist.end();
+          i++ )
+    {
+      const std::string & classname = *i;
+      map<string, string>::const_iterator j = tbl_text_code.find ( classname );
+
+      if ( j == tbl_text_code.end() )
+      {
+        fprintf ( stderr, "ClassNames: FATAL ERROR This is not a selection of a subset: %s [%s]\n",
+                  classname.c_str(), classselection.c_str() );
+        exit ( -1 );
+      }
+
+      const std::string & code = j->second;
+      int myclassno = classno ( code );
+
+      if ( myclassno < 0 ) {
+        fprintf ( stderr, "ClassNames: FATAL ERROR This is not a selection of a subset\n" );
+        exit ( -1 );
+      }
+      classnos.insert ( myclassno );
+    }
+  }
 
 }
 
 std::string ClassNames::text ( int classno ) const
-{  
-	map<string, string>::const_iterator i = 
-		tbl_code_text.find ( code(classno) );
-
-	if ( i == tbl_code_text.end() )
-	{
-		fprintf (stderr, "ClassNames: no name found for classno %d\n", classno );
-		return "unknown";
-	} else {
-		return i->second;
-	}
+{
+  map<string, string>::const_iterator i =
+    tbl_code_text.find ( code ( classno ) );
+
+  if ( i == tbl_code_text.end() )
+  {
+    fprintf ( stderr, "ClassNames: no name found for classno %d\n", classno );
+    return "unknown";
+  } else {
+    return i->second;
+  }
 
 }
 
 std::string ClassNames::code ( int classno ) const
 {
-	map<int, string>::const_iterator i = 
-		tbl_classno_code.find ( classno );
+  map<int, string>::const_iterator i =
+    tbl_classno_code.find ( classno );
 
-	if ( i == tbl_classno_code.end() )
-	{
-		fprintf (stderr, "ClassNames: no code found for classno %d\n", classno );
-		return "unknown";
-	} else {
-		return i->second;
-	}
+  if ( i == tbl_classno_code.end() )
+  {
+    fprintf ( stderr, "ClassNames: no code found for classno %d\n", classno );
+    return "unknown";
+  } else {
+    return i->second;
+  }
 
 }
 
 int ClassNames::classno ( std::string code ) const
 {
-	map<string, int>::const_iterator i = 
-		tbl_code_classno.find ( code );
-
-	if ( i == tbl_code_classno.end() )
-	{
-		fthrow(Exception, "no classno found for code <" << code << ">" );
-	} else {
-		return i->second;
-	}
+  map<string, int>::const_iterator i =
+    tbl_code_classno.find ( code );
+
+  if ( i == tbl_code_classno.end() )
+  {
+    fthrow ( Exception, "no classno found for code <" << code << ">" );
+  } else {
+    return i->second;
+  }
 }
 
 int ClassNames::numClasses () const
 {
-	return tbl_classno_code.size();
+  return tbl_classno_code.size();
 }
 
 
-void ClassNames::addClass ( int classno, const std::string & code, 
-	const std::string & text )
+void ClassNames::addClass ( int classno, const std::string & code,
+                            const std::string & text )
 {
-	tbl_classno_code[classno] = code;
-	tbl_text_code[text]	   = code;
-	tbl_code_text[code]	   = text;
-	tbl_code_classno[code]	= classno;
+  tbl_classno_code[classno] = code;
+  tbl_text_code[text]    = code;
+  tbl_code_text[code]    = text;
+  tbl_code_classno[code] = classno;
 
-	if ( classno > maxClassNo ) maxClassNo = classno;
+  if ( classno > maxClassNo ) maxClassNo = classno;
 }
-	
+
 bool ClassNames::existsClassno ( int classno ) const
 {
-	return (tbl_classno_code.find(classno) != tbl_classno_code.end());
+  return ( tbl_classno_code.find ( classno ) != tbl_classno_code.end() );
 }
 
 // refactor-nice.pl: check this substitution
 // old: bool ClassNames::existsClassCode ( const string & classcode ) const
 bool ClassNames::existsClassCode ( const std::string & classcode ) const
 {
-	return (tbl_code_classno.find(classcode) != tbl_code_classno.end());
+  return ( tbl_code_classno.find ( classcode ) != tbl_code_classno.end() );
 }
 
-bool ClassNames::readFromConfig ( const Config & datasetconf, 
-			// refactor-nice.pl: check this substitution
-			// old: const string & classselection )
-			const std::string & classselection )
+bool ClassNames::readFromConfig ( const Config & datasetconf,
+                                  // refactor-nice.pl: check this substitution
+                                  // old: const string & classselection )
+                                  const std::string & classselection )
 {
 
-	datasetconf.getAllS ( "classnames", tbl_code_text );
+  datasetconf.getAllS ( "classnames", tbl_code_text );
 
-	if ( tbl_code_text.size() <= 0 ) {
-		fprintf (stderr, "ClassNames: no classnames specified\n");
-		return false;
-	}
+  if ( tbl_code_text.size() <= 0 ) {
+    fprintf ( stderr, "ClassNames: no classnames specified\n" );
+    return false;
+  }
 
-	// reverse map and lower case
-	for ( map<string, string>::const_iterator i  = tbl_code_text.begin();
-									   i != tbl_code_text.end(); i++ )
-		tbl_text_code [ i->second ] = i->first;	
+  // reverse map and lower case
+  for ( map<string, string>::const_iterator i  = tbl_code_text.begin();
+        i != tbl_code_text.end(); i++ )
+    tbl_text_code [ i->second ] = i->first;
 
 #if defined DEBUG_ClassNames
-	cerr << "ClassNames::read: selection = " << classselection << endl;
+  cerr << "ClassNames::read: selection = " << classselection << endl;
 #endif
 
-	std::vector<string> classlist;
-	StringTools::split ( classselection, ',', classlist );
-
-	if ( classlist.size() <= 0 )
-	{
-	fprintf (stderr, "FATAL ERROR: wrong format for classselection\n");
-	exit(-1);
-	} else if ( classlist[0] == "*" )
-	{
-	map<string, bool> forbidden_classes;
-	for ( size_t k = 1 ; k < classlist.size() ; k++ )
-		if ( classlist[k].substr(0,1) == "-" )
-		{
-		// refactor-nice.pl: check this substitution
-		// old: string f_class = classlist[k].substr(1);
-		std::string f_class = classlist[k].substr(1);
+  std::vector<string> classlist;
+  StringTools::split ( classselection, ',', classlist );
+
+  if ( classlist.size() <= 0 )
+  {
+    fprintf ( stderr, "FATAL ERROR: wrong format for classselection\n" );
+    exit ( -1 );
+  } else if ( classlist[0] == "*" )
+  {
+    map<string, bool> forbidden_classes;
+    for ( size_t k = 1 ; k < classlist.size() ; k++ )
+      if ( classlist[k].substr ( 0, 1 ) == "-" )
+      {
+        // refactor-nice.pl: check this substitution
+        // old: string f_class = classlist[k].substr(1);
+        std::string f_class = classlist[k].substr ( 1 );
 #if defined DEBUG_ClassNames
-		fprintf (stderr, "ClassNames: class %s excluded !\n", f_class.c_str() );
+        fprintf ( stderr, "ClassNames: class %s excluded !\n", f_class.c_str() );
 #endif
-		forbidden_classes[ f_class ] = true;
-		} else {
-		fprintf (stderr, "FATAL ERROR: wrong format for classselection: *,-class0,class1,...\n");
-		exit(-1);
-		}
-
-	int classno_seq = 0;
-	for ( map<string, string>::const_iterator i  = tbl_code_text.begin();
-						  i != tbl_code_text.end();
-						  i++,classno_seq++ )
-	{
-		const std::string & classname = i->second;
-		if ( forbidden_classes.find(classname) != forbidden_classes.end() )
-			continue;
-
-		// refactor-nice.pl: check this substitution
-		// old: string code = tbl_text_code [ i->second ];
-		std::string code = tbl_text_code [ i->second ];
-		int classno;
-		classno = classno_seq;
-		tbl_classno_code[classno] = code;
-		tbl_code_classno[code] = classno;
-		if ( classno > maxClassNo ) maxClassNo = classno;
+        forbidden_classes[ f_class ] = true;
+      } else {
+        fprintf ( stderr, "FATAL ERROR: wrong format for classselection: *,-class0,class1,...\n" );
+        exit ( -1 );
+      }
+
+    int classno_seq = 0;
+    for ( map<string, string>::const_iterator i  = tbl_code_text.begin();
+          i != tbl_code_text.end();
+          i++, classno_seq++ )
+    {
+      const std::string & classname = i->second;
+      if ( forbidden_classes.find ( classname ) != forbidden_classes.end() )
+        continue;
+
+      // refactor-nice.pl: check this substitution
+      // old: string code = tbl_text_code [ i->second ];
+      std::string code = tbl_text_code [ i->second ];
+      int classno;
+      classno = classno_seq;
+      tbl_classno_code[classno] = code;
+      tbl_code_classno[code] = classno;
+      if ( classno > maxClassNo ) maxClassNo = classno;
 
 #if defined DEBUG_ClassNames
-		fprintf (stderr, "classno %d class code %s class text %s\n", classno, code.c_str(), classname.c_str() );
+      fprintf ( stderr, "classno %d class code %s class text %s\n", classno, code.c_str(), classname.c_str() );
 #endif
-	}
-	} else {
+    }
+  } else {
 
 #if defined DEBUG_ClassNames
-	cerr << "list : " << classlist.size() << endl;
+    cerr << "list : " << classlist.size() << endl;
 #endif
-	for ( size_t classno_seq = 0 ; classno_seq < classlist.size() ; classno_seq++ )
-	{
-		std::string classname = classlist[classno_seq];
-
-		if ( tbl_text_code.find ( classname ) != tbl_text_code.end() )
-		{
-			std::string code = tbl_text_code [ classname ];
-			int classno;
-			classno = classno_seq;
-			tbl_classno_code[classno] = code;
-			tbl_code_classno[code] = classno;
-			if ( classno > maxClassNo ) maxClassNo = classno;
+    for ( size_t classno_seq = 0 ; classno_seq < classlist.size() ; classno_seq++ )
+    {
+      std::string classname = classlist[classno_seq];
+
+      if ( tbl_text_code.find ( classname ) != tbl_text_code.end() )
+      {
+        std::string code = tbl_text_code [ classname ];
+        int classno;
+        classno = classno_seq;
+        tbl_classno_code[classno] = code;
+        tbl_code_classno[code] = classno;
+        if ( classno > maxClassNo ) maxClassNo = classno;
 
 #if defined DEBUG_ClassNames
-			fprintf (stderr, "classno %d class code %s class text %s\n", (int)classno, code.c_str(), classname.c_str() );
+        fprintf ( stderr, "classno %d class code %s class text %s\n", ( int ) classno, code.c_str(), classname.c_str() );
 #endif
-		} else {
-			fprintf (stderr, "ClassNames::ClassNames: FATAL ERROR class >%s< not found in data set\n", classname.c_str() );
-			exit(-1);
-		}
-	}
-	}
-
-	/****** after all, try to read color coding *******/
-	map<string, string> list;
-	datasetconf.getAllS ( "colors", list );
-
-	if ( list.size() > 0 ) {
-		for ( map<string,string>::const_iterator i = list.begin();
-			i != list.end();
-			i++ )
-		{
-			std::string value = i->second;
-			std::string classname = i->first;
-			int _classno = classno(classname);
-			vector<string> submatches;
-			if ( StringTools::regexMatch ( value, "^ *([[:digit:]]+) *: *([[:digit:]]+) *: *([[:digit:]]+) *$", submatches ) 
-				&& ( submatches.size() == 4 ) )
-			{
-				int r = StringTools::convert<int> ( submatches[1] );
-				int g = StringTools::convert<int> ( submatches[2] );
-				int b = StringTools::convert<int> ( submatches[3] );
-				long index = 256*(256*r + g) + b;
-				tbl_color_classno[index] = _classno;
-				tbl_classno_color[_classno] = index;
-			} else {
-				fprintf (stderr, "LabeledFileList: parse error colors >%s<\n", value.c_str() );
-				exit(-1);
-			}
-		}
-	}
-
-	return true;
+      } else {
+        fprintf ( stderr, "ClassNames::ClassNames: FATAL ERROR class >%s< not found in data set\n", classname.c_str() );
+        exit ( -1 );
+      }
+    }
+  }
+
+  /****** after all, try to read color coding *******/
+  map<string, string> list;
+  datasetconf.getAllS ( "colors", list );
+
+  if ( list.size() > 0 ) {
+    for ( map<string, string>::const_iterator i = list.begin();
+          i != list.end();
+          i++ )
+    {
+      std::string value = i->second;
+      std::string classname = i->first;
+      int _classno = classno ( classname );
+      vector<string> submatches;
+      if ( StringTools::regexMatch ( value, "^ *([[:digit:]]+) *: *([[:digit:]]+) *: *([[:digit:]]+) *$", submatches )
+           && ( submatches.size() == 4 ) )
+      {
+        int r = StringTools::convert<int> ( submatches[1] );
+        int g = StringTools::convert<int> ( submatches[2] );
+        int b = StringTools::convert<int> ( submatches[3] );
+        long index = 256 * ( 256 * r + g ) + b;
+        tbl_color_classno[index] = _classno;
+        tbl_classno_color[_classno] = index;
+      } else {
+        fprintf ( stderr, "LabeledFileList: parse error colors >%s<\n", value.c_str() );
+        exit ( -1 );
+      }
+    }
+  }
+
+  return true;
 }
-	
+
 int ClassNames::getMaxClassno () const
 {
-	return maxClassNo;
+  return maxClassNo;
 }
-	
+
 void ClassNames::getRGBColor ( int classno, int & r, int & g, int & b ) const
 {
-	map<int, long>::const_iterator i = tbl_classno_color.find(classno);
-
-	if ( i == tbl_classno_color.end() )
-	{
-		fprintf (stderr, "ClassNames: no color setting found for class %d\n", classno );
-		getchar();
-		double x = classno / (double)numClasses();
-		double rd, gd, bd;
-		ICETools::toColor ( x, rd, gd, bd );
-		r = (int)(255*rd);
-		g = (int)(255*gd);
-		b = (int)(255*bd);
-	} else {
-		long color = i->second;
-		b = color % 256;
-		color /= 256;
-		g = color % 256;
-		color /= 256;
-		r = color % 256;
-	}
+  map<int, long>::const_iterator i = tbl_classno_color.find ( classno );
+
+  if ( i == tbl_classno_color.end() )
+  {
+    fprintf ( stderr, "ClassNames: no color setting found for class %d\n", classno );
+    getchar();
+    double x = classno / ( double ) numClasses();
+    double rd, gd, bd;
+    ICETools::toColor ( x, rd, gd, bd );
+    r = ( int ) ( 255 * rd );
+    g = ( int ) ( 255 * gd );
+    b = ( int ) ( 255 * bd );
+  } else {
+    long color = i->second;
+    b = color % 256;
+    color /= 256;
+    g = color % 256;
+    color /= 256;
+    r = color % 256;
+  }
 }
 
 void ClassNames::getClassnoFromColor ( int & classno, int r, int g, int b ) const
 {
-	long color = 256*(256*r+g) + b;
-	map<long, int>::const_iterator i = tbl_color_classno.find(color);
-
-	if ( i == tbl_color_classno.end() )
-	{
-		classno = -1;
-	} else {
-		classno = i->second;
-	}
+  long color = 256 * ( 256 * r + g ) + b;
+  map<long, int>::const_iterator i = tbl_color_classno.find ( color );
+
+  if ( i == tbl_color_classno.end() )
+  {
+    classno = -1;
+  } else {
+    classno = i->second;
+  }
 }
 
 void ClassNames::labelToRGB ( const NICE::Image & img, NICE::ColorImage & rgb ) const
 {
-	int red, green, blue;
+  int red, green, blue;
 
-	rgb.resize(img.width(), img.height());
+  rgb.resize ( img.width(), img.height() );
 
-	for ( int y = 0 ; y < img.height(); y++ )
-	for ( int x = 0 ; x < img.width(); x++ )
-	{
-		int label = img.getPixel(x,y);
-		getRGBColor ( label, red, green, blue );
-		rgb.setPixel(x,y,0,red);
-		rgb.setPixel(x,y,1,green);
-		rgb.setPixel(x,y,2,blue);
-	}
+  for ( int y = 0 ; y < img.height(); y++ )
+    for ( int x = 0 ; x < img.width(); x++ )
+    {
+      int label = img.getPixel ( x, y );
+      getRGBColor ( label, red, green, blue );
+      rgb.setPixel ( x, y, 0, red );
+      rgb.setPixel ( x, y, 1, green );
+      rgb.setPixel ( x, y, 2, blue );
+    }
 
 }
 
 int ClassNames::getBackgroundClass () const
 {
-	if ( existsClassCode ("various" ) )
-		return classno("various");
-	else if ( existsClassCode ("background" ) )
-		return classno("background");
-	else if ( existsClassCode ("clutter" ) )
-		return classno("clutter");
-	else
-		return 0;
+  if ( existsClassCode ( "various" ) )
+    return classno ( "various" );
+  else if ( existsClassCode ( "background" ) )
+    return classno ( "background" );
+  else if ( existsClassCode ( "clutter" ) )
+    return classno ( "clutter" );
+  else
+    return 0;
 }
 
-void ClassNames::restore (istream & is, int format)
+void ClassNames::restore ( istream & is, int format )
 {
-	maxClassNo = -1;
-	while ( ! is.eof() )
-	{
-		std::string mytext;
-		std::string mycode;
-		int myclassno;
-
-		if ( !(is >> mytext) ) break;
-		if ( !(is >> mycode) ) break;
-		if ( !(is >> myclassno) ) break;
-
-		tbl_code_text.insert ( pair<string, string> ( mycode, mytext ) );
-		tbl_text_code.insert ( pair<string, string> ( mytext, mycode ) );
-		tbl_classno_code.insert ( pair<int, string> ( myclassno, mycode ) );
-		tbl_code_classno.insert ( pair<string, int> ( mycode, myclassno ) );
-
-		if ( myclassno > maxClassNo ) maxClassNo = myclassno;
-	}
+  maxClassNo = -1;
+  while ( ! is.eof() )
+  {
+    std::string mytext;
+    std::string mycode;
+    int myclassno;
+
+    if ( ! ( is >> mytext ) ) break;
+    if ( mytext == "end" ) break;
+    if ( ! ( is >> mycode ) ) break;
+    if ( ! ( is >> myclassno ) ) break;
+
+    tbl_code_text.insert ( pair<string, string> ( mycode, mytext ) );
+    tbl_text_code.insert ( pair<string, string> ( mytext, mycode ) );
+    tbl_classno_code.insert ( pair<int, string> ( myclassno, mycode ) );
+    tbl_code_classno.insert ( pair<string, int> ( mycode, myclassno ) );
+
+    if ( myclassno > maxClassNo ) maxClassNo = myclassno;
+  }
 }
 
-void ClassNames::store (ostream & os, int format) const
+void ClassNames::store ( ostream & os, int format ) const
 {
-	assert ( tbl_classno_code.size() == tbl_code_classno.size() );
-	for ( map<int, string>::const_iterator i  = tbl_classno_code.begin() ;
-						  i != tbl_classno_code.end();
-						  i++ )
-	{
-		int myclassno = i->first;
-		std::string mycode = i->second;
-		std::string mytext = text(myclassno);
-
-		os << mytext << "\t" << mycode << "\t" << myclassno << endl;
-	}	
+  assert ( tbl_classno_code.size() == tbl_code_classno.size() );
+  for ( map<int, string>::const_iterator i  = tbl_classno_code.begin() ;
+        i != tbl_classno_code.end();
+        i++ )
+  {
+    int myclassno = i->first;
+    std::string mycode = i->second;
+    std::string mytext = text ( myclassno );
+
+    os << mytext << "\t" << mycode << "\t" << myclassno << endl;
+  }
+  os << "end" << endl;
 }
 
 void ClassNames::clear ()
 {
-	tbl_code_text.clear();
-	tbl_text_code.clear();
-	tbl_classno_code.clear();
-	tbl_code_classno.clear();
-	tbl_color_classno.clear();
-	tbl_classno_color.clear();
+  tbl_code_text.clear();
+  tbl_text_code.clear();
+  tbl_classno_code.clear();
+  tbl_code_classno.clear();
+  tbl_color_classno.clear();
+  tbl_classno_color.clear();
 }
 

+ 80 - 80
cbaselib/ClassNames.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ClassNames.h
 * @brief simple interface for class name confusion
 * @author Erik Rodner
@@ -11,7 +11,7 @@
 #include "core/image/ImageT.h"
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
- 
+
 #include <string>
 #include <map>
 
@@ -25,84 +25,84 @@ namespace OBJREC {
 class ClassNames : public NICE::Persistent
 {
 
-    protected:
-
-		std::map<std::string, std::string> tbl_code_text;
-		std::map<std::string, std::string> tbl_text_code;
-		std::map<int, std::string> tbl_classno_code;
-		std::map<std::string, int> tbl_code_classno;
-		std::map<long, int> tbl_color_classno;
-		std::map<int, long> tbl_classno_color;
-
-		int maxClassNo;
-
-    public:
-  
-	/** simple constructor */
-	ClassNames();
-    
-	/** copy constructor */
-	ClassNames ( const ClassNames & cn );
-  
-	/** create sub selection */
-	ClassNames ( const ClassNames & cn, 
-		     const std::string & classselection );
-
-	/** simple destructor */
-	virtual ~ClassNames();
-    
-	/** get the readable class number of a class number */
-	std::string text ( int classno ) const;
-
-	/** get the class code (e.g. ascii code) of a class number */
-	std::string code ( int classno ) const;
-
-	/** get the class number corresponding to the code */
-	int classno ( std::string code ) const;
-	
-	/** get the class number corresponding to the name */
-	int classnoFromText ( std::string text ) const;
-
-	/** number of classes */
-	int numClasses () const;
-	void getSelection ( const std::string & classselection,
-			    std::set<int> & classnos ) const;
-
-	/** add new class information 
-	 * @param classno class number
-	 * @param code class code (such as ascii number or just the name)
-	 * @param text class name as readable ascii representation
-	 */
-	void addClass ( int classno, const std::string & code, 
-	    const std::string & text );
-
-	bool readFromConfig ( const NICE::Config & datasetconf, 
-		    const std::string & classselection );
-
-	/** is there any class with this class number */
-	bool existsClassno ( int classno ) const;
-	/** is there any class with this class code */
-	bool existsClassCode ( const std::string & classcode ) const;
-
-	int getMaxClassno () const;
-
-	void getRGBColor ( int classno, int & r, int & g, int & b ) const;
-	
-	void getClassnoFromColor ( int & classno, int r, int g, int b ) const;
-
-	/** colorize a labeled image using color information given in the class 
-	 *  information file */
-	void labelToRGB ( const NICE::Image & img, NICE::ColorImage & rgb ) const;
-
-	int getBackgroundClass () const;
-
-	/** restore classnames in the format <classtext> <classcode> <classno> */ 
-	void restore (std::istream & is, int format = 0);
-
-	/** store classnames in the format <classtext> <classcode> <classno> */ 
-	void store (std::ostream & os, int format = 0) const;
-
-	/** clear class information */
+  protected:
+
+    std::map<std::string, std::string> tbl_code_text;
+    std::map<std::string, std::string> tbl_text_code;
+    std::map<int, std::string> tbl_classno_code;
+    std::map<std::string, int> tbl_code_classno;
+    std::map<long, int> tbl_color_classno;
+    std::map<int, long> tbl_classno_color;
+
+    int maxClassNo;
+
+  public:
+
+    /** simple constructor */
+    ClassNames();
+
+    /** copy constructor */
+    ClassNames ( const ClassNames & cn );
+
+    /** create sub selection */
+    ClassNames ( const ClassNames & cn,
+                 const std::string & classselection );
+
+    /** simple destructor */
+    virtual ~ClassNames();
+
+    /** get the readable class number of a class number */
+    std::string text ( int classno ) const;
+
+    /** get the class code (e.g. ascii code) of a class number */
+    std::string code ( int classno ) const;
+
+    /** get the class number corresponding to the code */
+    int classno ( std::string code ) const;
+
+    /** get the class number corresponding to the name */
+    int classnoFromText ( std::string text ) const;
+
+    /** number of classes */
+    int numClasses () const;
+    void getSelection ( const std::string & classselection,
+                        std::set<int> & classnos ) const;
+
+    /** add new class information
+     * @param classno class number
+     * @param code class code (such as ascii number or just the name)
+     * @param text class name as readable ascii representation
+     */
+    void addClass ( int classno, const std::string & code,
+                    const std::string & text );
+
+    bool readFromConfig ( const NICE::Config & datasetconf,
+                          const std::string & classselection );
+
+    /** is there any class with this class number */
+    bool existsClassno ( int classno ) const;
+    /** is there any class with this class code */
+    bool existsClassCode ( const std::string & classcode ) const;
+
+    int getMaxClassno () const;
+
+    void getRGBColor ( int classno, int & r, int & g, int & b ) const;
+
+    void getClassnoFromColor ( int & classno, int r, int g, int b ) const;
+
+    /** colorize a labeled image using color information given in the class
+     *  information file */
+    void labelToRGB ( const NICE::Image & img, NICE::ColorImage & rgb ) const;
+
+    int getBackgroundClass () const;
+
+    /** restore classnames in the format <classtext> <classcode> <classno> */
+    void restore ( std::istream & is, int format = 0 );
+
+    /** store classnames in the format <classtext> <classcode> <classno> */
+    void store ( std::ostream & os, int format = 0 ) const;
+
+    /** clear class information */
     void clear ();
 };
 

+ 1 - 0
cbaselib/Example.cpp

@@ -13,6 +13,7 @@ Example::Example()
 	y = 0;
 	vec = NULL;
 	svec = NULL;
+  ce = NULL;
 	position = 0;
 }
 

+ 107 - 107
cbaselib/Example.h

@@ -1,7 +1,7 @@
 #ifndef EXAMPLEINCLUDE
 #define EXAMPLEINCLUDE
 
-/** 
+/**
 * @file Example.h
 * @brief data caching of several feature images and many more
 * @author Erik Rodner
@@ -15,121 +15,121 @@ namespace OBJREC {
 /** Cached example with window information */
 class Example
 {
-    public:
-	/** weight of example */
-	double weight;
-
-	/** complete image example */
-	CachedExample *ce;
-
-	/** x position of window */
-	long long int x;
-	/** y position of window */
-	long long int y;
-
-	/** width of window */
-	int width;
-	/** height of window */
-	int height;
-	
-	//! if some examples are related, they have the same position
-	int position;
-	
-	//! scale of the feature
-	double scale;
-	
-	/** evil workaround: store simple vector example */
-	NICE::Vector *vec;
-	
-	/** evil workaround: store sparse vector example */
-	NICE::SparseVector *svec;
-
-	/** simple constructor, initialize everything with 0
-	 */
-	Example();
-
-	/** constructor using a window covering the whole image
-	    @param ce associated image data
-	*/
-	Example ( CachedExample *_ce );
-
-	/** constructor 
-	    @param ce associated image data
-	    @param x x position of window
-	    @param y y position of window
-	    @param weight weight of example
-	*/
-	Example ( CachedExample *ce, int x, int y, double weight = 1.0 );
-	
-	/** constructor 
-	    @param ce associated image data
-	    @param x x position of window
-	    @param y y position of window
-	    @param weight weight of example
-	*/
-	Example ( CachedExample *ce, int x, int y, int width, int height, double weight = 1.0 );
-
-	/** evil workaround: simple constructors for std::vector examples 
-	    @param vec simple feature vector
-	    @param weight optional weight
-	*/
-	Example ( NICE::Vector *vec, double weight = 1.0 );
-
-	/**
-	 * copy constructor
-	 * @param ex input Example
-	 */
-	Example ( const Example &ex);
-	
-	/**
-	 * copies the values of ex in this example
-	 * @param ex input Example
-	 */
-	void copy ( const Example &ex);
-	
-	/** destructor */
-	~Example ();
-
-	/** delete all data associated with this example
-	    (sparse vector, vector, cached example, etc.) */
-	void clean ();
-	
-	/**
-	 * load from file (warning: no cachedexamples supported yet
-	 * @param is file
-	 * @param format 
-	 */
-	void restore (std::istream & is, int format = 0);
-	
-	
-	/**
-	 * write to file (warning: no cachedexamples supported yet
-	 * @param is file
-	 * @param format 
-	 */
-	void store (std::ostream & os, int format = 0) const;
+  public:
+    /** weight of example */
+    double weight;
+
+    /** complete image example */
+    CachedExample *ce;
+
+    /** x position of window */
+    long long int x;
+    /** y position of window */
+    long long int y;
+
+    /** width of window */
+    int width;
+    /** height of window */
+    int height;
+
+    //! if some examples are related, they have the same position
+    int position;
+
+    //! scale of the feature
+    double scale;
+
+    /** evil workaround: store simple vector example */
+    NICE::Vector *vec;
+
+    /** evil workaround: store sparse vector example */
+    NICE::SparseVector *svec;
+
+    /** simple constructor, initialize everything with 0
+     */
+    Example();
+
+    /** constructor using a window covering the whole image
+        @param ce associated image data
+    */
+    Example ( CachedExample *_ce );
+
+    /** constructor
+        @param ce associated image data
+        @param x x position of window
+        @param y y position of window
+        @param weight weight of example
+    */
+    Example ( CachedExample *ce, int x, int y, double weight = 1.0 );
+
+    /** constructor
+        @param ce associated image data
+        @param x x position of window
+        @param y y position of window
+        @param weight weight of example
+    */
+    Example ( CachedExample *ce, int x, int y, int width, int height, double weight = 1.0 );
+
+    /** evil workaround: simple constructors for std::vector examples
+        @param vec simple feature vector
+        @param weight optional weight
+    */
+    Example ( NICE::Vector *vec, double weight = 1.0 );
+
+    /**
+     * copy constructor
+     * @param ex input Example
+     */
+    Example ( const Example &ex );
+
+    /**
+     * copies the values of ex in this example
+     * @param ex input Example
+     */
+    void copy ( const Example &ex );
+
+    /** destructor */
+    ~Example ();
+
+    /** delete all data associated with this example
+        (sparse vector, vector, cached example, etc.) */
+    void clean ();
+
+    /**
+     * load from file (warning: no cachedexamples supported yet
+     * @param is file
+     * @param format
+     */
+    void restore ( std::istream & is, int format = 0 );
+
+
+    /**
+     * write to file (warning: no cachedexamples supported yet
+     * @param is file
+     * @param format
+     */
+    void store ( std::ostream & os, int format = 0 ) const;
 };
 
-/** labeled pair of Example 
+/** labeled pair of Example
     @see Example */
 class Examples : public std::vector< std::pair<int, Example> >
 {
-    public:
-		std::string filename;
+  public:
+    std::string filename;
 
-    inline int getMaxClassNo () const 
+    inline int getMaxClassNo () const
     {
-		int maxClassno = -1;
-		for ( const_iterator i = begin(); i != end(); i++ )
-			if ( i->first > maxClassno )
-			maxClassno = i->first;
-		
-		return maxClassno;
+      int maxClassno = -1;
+      for ( const_iterator i = begin(); i != end(); i++ )
+        if ( i->first > maxClassno )
+          maxClassno = i->first;
+
+      return maxClassno;
     }
 
-	/** delete all data associated with all examples
-	    (sparse vector, vector, cached example, etc.) */
-	void clean ();
+    /** delete all data associated with all examples
+        (sparse vector, vector, cached example, etc.) */
+    void clean ();
 };
 
 

+ 317 - 317
cbaselib/LabeledSet.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LabeledSet.cpp
 * @brief Labeled set of vectors
 * @author Erik Rodner
@@ -23,93 +23,93 @@ using namespace std;
 using namespace NICE;
 
 
-LabeledSet::LabeledSet ( bool _selection ) : selection(_selection)
+LabeledSet::LabeledSet ( bool _selection ) : selection ( _selection )
 {
 }
-	
+
 LabeledSet::~LabeledSet ()
 {
-    //This is a big problem when using selections
-    //clear();
-    //fprintf (stderr, "LabeledSet: destructor (FIXME: memory leak)\n");
+  //This is a big problem when using selections
+  //clear();
+  //fprintf (stderr, "LabeledSet: destructor (FIXME: memory leak)\n");
 }
 
 int LabeledSet::count ( int classno ) const
 {
-    const_iterator i = find(classno);
-    return ( i == end() ) ? 0 : i->second.size();
+  const_iterator i = find ( classno );
+  return ( i == end() ) ? 0 : i->second.size();
 }
 
 int LabeledSet::count () const
 {
-    int mycount = 0;
-    for ( const_iterator i = begin() ; i != end() ; i++ )
-    {
-		mycount += i->second.size();
-    }
-    return mycount;
+  int mycount = 0;
+  for ( const_iterator i = begin() ; i != end() ; i++ )
+  {
+    mycount += i->second.size();
+  }
+  return mycount;
 }
 
 void LabeledSet::clear ()
 {
-    if ( !selection ) 
+  if ( !selection )
+  {
+    for ( Permutation::const_iterator i  = insertOrder.begin();
+          i != insertOrder.end();
+          i++ )
     {
-		for ( Permutation::const_iterator i  = insertOrder.begin(); 
-						  i != insertOrder.end();
-						  i++ )
-		{
-			const ImageInfo *s = i->second;
-			delete s;
-		}
+      const ImageInfo *s = i->second;
+      delete s;
     }
-    
-    std::map< int, vector<ImageInfo *> >::clear();
+  }
+
+  std::map< int, vector<ImageInfo *> >::clear();
 }
 
 void LabeledSet::add ( int classno, ImageInfo *x )
 {
-    if ( selection ) {
-		fprintf (stderr, "Operation not available for selections !\n");
-		exit(-1);
-    }
-
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<ImageInfo *>();
-		i = find(classno);
-    }
-    i->second.push_back ( x ); 
-    insertOrder.push_back ( ElementPointer ( classno, x ) );
+  if ( selection ) {
+    fprintf ( stderr, "Operation not available for selections !\n" );
+    exit ( -1 );
+  }
+
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<ImageInfo *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( x );
+  insertOrder.push_back ( ElementPointer ( classno, x ) );
 }
-	
+
 void LabeledSet::getPermutation ( Permutation & permutation ) const
 {
-    permutation = Permutation ( insertOrder );
+  permutation = Permutation ( insertOrder );
 }
 
 void LabeledSet::add_reference ( int classno, ImageInfo *pointer )
 {
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<ImageInfo *>();
-		i = find(classno);
-    }
-    i->second.push_back ( pointer ); 
-    insertOrder.push_back ( ElementPointer ( classno, pointer ) );
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<ImageInfo *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( pointer );
+  insertOrder.push_back ( ElementPointer ( classno, pointer ) );
 }
 
 void LabeledSet::getClasses ( std::vector<int> & classes ) const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-		classes.push_back ( i->first );
+  for ( const_iterator i = begin(); i != end(); i++ )
+    classes.push_back ( i->first );
 }
 
 void LabeledSet::printInformation () const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-    {
-	cerr << "class " << i->first << ": " << i->second.size() << endl;
-    }
+  for ( const_iterator i = begin(); i != end(); i++ )
+  {
+    cerr << "class " << i->first << ": " << i->second.size() << endl;
+  }
 }
 
 
@@ -118,353 +118,353 @@ void LabeledSet::printInformation () const
 *************************************/
 
 
-LabeledSetVector::LabeledSetVector (bool _selection) : selection(_selection)
+LabeledSetVector::LabeledSetVector ( bool _selection ) : selection ( _selection )
 {}
-	
+
 LabeledSetVector::~LabeledSetVector ()
 {
-    // FIXME: THIS is a big problem with selections !!!
-    //clear();
+  // FIXME: THIS is a big problem with selections !!!
+  //clear();
 }
 
 int LabeledSetVector::dimension () const
 {
-    if ( insertOrder.size() <= 0 ) return -1;
-    return (*(begin()->second.begin()))->size();
-    //insertOrder[0].second->size();
+  if ( insertOrder.size() <= 0 ) return -1;
+  return ( * ( begin()->second.begin() ) )->size();
+  //insertOrder[0].second->size();
 }
 
-void LabeledSetVector::restore (istream & is, int format)
+void LabeledSetVector::restore ( istream & is, int format )
 {
-    if ( format == FILEFORMAT_RAW )
-		restoreRAW ( is );
-    else
-		restoreASCII ( is, format );
+  if ( format == FILEFORMAT_RAW )
+    restoreRAW ( is );
+  else
+    restoreASCII ( is, format );
 }
 
-void LabeledSetVector::restoreASCII (istream & is, int format)
+void LabeledSetVector::restoreASCII ( istream & is, int format )
 {
-    const int bufsize = 1024*1024;
-    char *buf = new char[bufsize];
-    std::string buf_s;
+  const int bufsize = 1024 * 1024;
+  char *buf = new char[bufsize];
+  std::string buf_s;
+
+  vector<string> elements;
+  vector<string> pair;
 
-    vector<string> elements;
-    vector<string> pair;
+  // maximal dimension of all feature vectors;
+  int dataset_dimension = -numeric_limits<int>::max();
 
-	// maximal dimension of all feature vectors;
-	int dataset_dimension = -numeric_limits<int>::max();
+  while ( ! is.eof() )
+  {
+    elements.clear();
+    int classno;
 
-    while (! is.eof())
+    if ( ! ( is >> classno ) ) {
+      break;
+    }
+
+    is.get ( buf, bufsize );
+    buf_s = buf;
+
+    if ( buf_s.size() <= 0 )
+      break;
+
+    StringTools::split ( buf_s, ' ', elements );
+
+    if ( elements.size() <= 1 )
+      break;
+
+    int dimension = - numeric_limits<int>::max();
+    if ( format == FILEFORMAT_INDEX_SPARSE_ONE )
     {
-		elements.clear();
-		int classno;
-		
-		if ( ! (is >> classno) ) {
-			break;
-		}
-
-		is.get ( buf, bufsize );
-		buf_s = buf;
-
-		if ( buf_s.size() <= 0 ) 
-			break;
-
-		StringTools::split ( buf_s, ' ', elements );
-
-		if ( elements.size() <= 1 )
-			break;
-		
-		int dimension = - numeric_limits<int>::max();
-		if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) 
-		{
-			// in this format we have to determine the maximum index
-			for ( vector<string>::const_iterator i  = elements.begin()+1; 
-							 i != elements.end();
-							 i++ ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() != 2 ) continue;
-
-				int index = atoi(pair[0].c_str());
-				
-				if ( index > dimension )
-					dimension = index;
-			}
-
-			if ( dimension > dataset_dimension )
-				dataset_dimension = dimension;
-
-			
-		} else {
-			// skip first element because of white space
-			dimension = elements.size()-1;
-		}
-
-
-		NICE::Vector vec ( dimension, 0.0 );
-		size_t l = 0;
-
-		// skip first element because of white space
-		for ( vector<string>::const_iterator i  = elements.begin()+1; 
-							 i != elements.end();
-							 i++, l++ )
-		{
-			if ( format == FILEFORMAT_INDEX ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() == 2 ) {
-					double val = atof ( pair[1].c_str() );
-					vec[l] = val;
-				}
-			} else if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() == 2 ) {
-					double val = atof ( pair[1].c_str() );
-					int index = atoi ( pair[0].c_str() ) - 1;
-					vec[index] = val;
-				}
-			} else {
-				vec[l] = atof( i->c_str() );
-			}
-		}
-		add( classno, vec );
+      // in this format we have to determine the maximum index
+      for ( vector<string>::const_iterator i  = elements.begin() + 1;
+            i != elements.end();
+            i++ )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() != 2 ) continue;
+
+        int index = atoi ( pair[0].c_str() );
+
+        if ( index > dimension )
+          dimension = index;
+      }
+
+      if ( dimension > dataset_dimension )
+        dataset_dimension = dimension;
+
+
+    } else {
+      // skip first element because of white space
+      dimension = elements.size() - 1;
     }
-    delete [] buf;
-
-	if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) {
-		// we have to resize all feature vectors of the dataset to dataset_dimension
-		for ( LabeledSetVector::iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++)
-			for ( vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); 
-									 jLOOP_ALL != iLOOP_ALL->second.end(); 
-									 jLOOP_ALL++ )
-			{
-				NICE::Vector *x = (*jLOOP_ALL);
-
-				uint old_dimension = x->size();
-
-				// resize the vector to the dataset dimension
-				x->resize(dataset_dimension);
-				
-				// set all elements to zero, which are new after the resize operation
-				for ( uint k = old_dimension; k < x->size(); k++ )
-					(*x)[k] = 0.0;
-			}
-	}
-}
 
-void LabeledSetVector::store (ostream & os, int format) const
-{
-    for ( Permutation::const_iterator i  = insertOrder.begin();
-				      i != insertOrder.end();
-				      i++ )
+
+    NICE::Vector vec ( dimension, 0.0 );
+    size_t l = 0;
+
+    // skip first element because of white space
+    for ( vector<string>::const_iterator i  = elements.begin() + 1;
+          i != elements.end();
+          i++, l++ )
     {
-		int classno = i->first;
-		const NICE::Vector & x = *(i->second);
-		
-		storeElement ( os, classno, x, format );
+      if ( format == FILEFORMAT_INDEX )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() == 2 ) {
+          double val = atof ( pair[1].c_str() );
+          vec[l] = val;
+        }
+      } else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() == 2 ) {
+          double val = atof ( pair[1].c_str() );
+          int index = atoi ( pair[0].c_str() ) - 1;
+          vec[index] = val;
+        }
+      } else {
+        vec[l] = atof ( i->c_str() );
+      }
     }
+    add ( classno, vec );
+  }
+  delete [] buf;
+
+  if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) {
+    // we have to resize all feature vectors of the dataset to dataset_dimension
+    for ( LabeledSetVector::iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++ )
+      for ( vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin();
+            jLOOP_ALL != iLOOP_ALL->second.end();
+            jLOOP_ALL++ )
+      {
+        NICE::Vector *x = ( *jLOOP_ALL );
+
+        uint old_dimension = x->size();
+
+        // resize the vector to the dataset dimension
+        x->resize ( dataset_dimension );
+
+        // set all elements to zero, which are new after the resize operation
+        for ( uint k = old_dimension; k < x->size(); k++ )
+          ( *x ) [k] = 0.0;
+      }
+  }
+}
+
+void LabeledSetVector::store ( ostream & os, int format ) const
+{
+  for ( Permutation::const_iterator i  = insertOrder.begin();
+        i != insertOrder.end();
+        i++ )
+  {
+    int classno = i->first;
+    const NICE::Vector & x = * ( i->second );
+
+    storeElement ( os, classno, x, format );
+  }
 }
 
 void LabeledSetVector::storeElement ( ostream & os, int classno, const NICE::Vector & x, int format )
 {
-    if ( format != FILEFORMAT_RAW ) {
-		os << classno << " ";
-		for ( size_t k = 0 ; k < x.size() ; k++ )
-		{
-			if ( format == FILEFORMAT_INDEX )
-				os << k+1 << ":" << x[k];
-			else if ( format == FILEFORMAT_NOINDEX )  
-				os << x[k];
-			else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )  {
-				if ( x[k] != 0.0 ) 
-					os << k+1 << ":" << x[k];
-			}
-
-			if ( k != x.size() )
-				os << " ";
-		}
-		os << endl;
-	} else {
-		const double *data = x.getDataPointer();
-		int dimension = x.size();
-
-		os.write ( (char *)&classno, sizeof(int) );
-		os.write ( (char *)&dimension, sizeof(int) );
-		os.write ( (char *)data, sizeof(double)*dimension );
+  if ( format != FILEFORMAT_RAW ) {
+    os << classno << " ";
+    for ( size_t k = 0 ; k < x.size() ; k++ )
+    {
+      if ( format == FILEFORMAT_INDEX )
+        os << k + 1 << ":" << x[k];
+      else if ( format == FILEFORMAT_NOINDEX )
+        os << x[k];
+      else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )  {
+        if ( x[k] != 0.0 )
+          os << k + 1 << ":" << x[k];
+      }
+
+      if ( k != x.size() )
+        os << " ";
     }
+    os << endl;
+  } else {
+    const double *data = x.getDataPointer();
+    int dimension = x.size();
+
+    os.write ( ( char * ) &classno, sizeof ( int ) );
+    os.write ( ( char * ) &dimension, sizeof ( int ) );
+    os.write ( ( char * ) data, sizeof ( double ) *dimension );
+  }
 }
 
-void LabeledSetVector::restoreRAW (istream & is)
+void LabeledSetVector::restoreRAW ( istream & is )
 {
-    while (! is.eof())
-    {
-		int classno;
-		int dimension;
-
-		is.read ( (char *)&classno, sizeof(int) );
-		if ( is.gcount() != sizeof(int) )
-			return;
-
-		is.read ( (char *)&dimension, sizeof(int) );
-		if ( is.gcount() != sizeof(int) )
-			return;
-
-		NICE::Vector vec;
-
-		try {
-			vec.resize(dimension);
-		} catch ( std::bad_alloc ) {
-			fthrow(IOException, "Unable to allocate a vector with size " << dimension << "." << endl 
-					<< "(debug: class " << classno << " ; " << "sizeof(int) = " << 8*sizeof(int) << " Bit ; " << endl
-					<< "elements read = " << count() << " )" << endl );
-		}
-		double *data = vec.getDataPointer();
-
-		is.read ( (char *)data, sizeof(double)*dimension );
-		if ( (int)is.gcount() != (int)sizeof(double)*dimension )
-			return;
-
-		for ( int k = 0 ; k < dimension ; k++ )
-			if ( isnan(data[k]) ) {
-				cerr << "WARNING: nan's found !!" << endl;
-				data[k] = 0.0;
-			}
-		
-		add( classno, vec );
+  while ( ! is.eof() )
+  {
+    int classno;
+    int dimension;
+
+    is.read ( ( char * ) &classno, sizeof ( int ) );
+    if ( is.gcount() != sizeof ( int ) )
+      return;
+
+    is.read ( ( char * ) &dimension, sizeof ( int ) );
+    if ( is.gcount() != sizeof ( int ) )
+      return;
+
+    NICE::Vector vec;
+
+    try {
+      vec.resize ( dimension );
+    } catch ( std::bad_alloc ) {
+      fthrow ( IOException, "Unable to allocate a vector with size " << dimension << "." << endl
+               << "(debug: class " << classno << " ; " << "sizeof(int) = " << 8*sizeof ( int ) << " Bit ; " << endl
+               << "elements read = " << count() << " )" << endl );
     }
+    double *data = vec.getDataPointer();
+
+    is.read ( ( char * ) data, sizeof ( double ) *dimension );
+    if ( ( int ) is.gcount() != ( int ) sizeof ( double ) *dimension )
+      return;
+
+    for ( int k = 0 ; k < dimension ; k++ )
+      if ( isnan ( data[k] ) ) {
+        cerr << "WARNING: nan's found !!" << endl;
+        data[k] = 0.0;
+      }
+
+    add ( classno, vec );
+  }
 }
 
 LabeledSetVector::ElementPointer LabeledSetVector::pickRandomSample () const
 {
-    if ( insertOrder.size() <= 0 ) {
-		fprintf (stderr, "LabeledSet::pickRandomSample: failure !\n");
-		exit(-1);
-    }
-    
-    int selection = rand() % insertOrder.size();
-    return insertOrder[selection];
+  if ( insertOrder.size() <= 0 ) {
+    fprintf ( stderr, "LabeledSet::pickRandomSample: failure !\n" );
+    exit ( -1 );
+  }
+
+  int selection = rand() % insertOrder.size();
+  return insertOrder[selection];
 }
 
 int LabeledSetVector::count ( int classno ) const
 {
-    const_iterator i = find(classno);
-    return ( i == end() ) ? 0 : i->second.size();
+  const_iterator i = find ( classno );
+  return ( i == end() ) ? 0 : i->second.size();
 }
 
 int LabeledSetVector::count () const
 {
-    int mycount = 0;
-    for ( const_iterator i = begin() ; i != end() ; i++ )
-		mycount += i->second.size();
-    return mycount;
+  int mycount = 0;
+  for ( const_iterator i = begin() ; i != end() ; i++ )
+    mycount += i->second.size();
+  return mycount;
 }
 
 int LabeledSetVector::pickRandomSample ( int classno, ElementPointer & i ) const
 {
-    const_iterator j = find(classno);
-    if ( j == end() ) return -1;
+  const_iterator j = find ( classno );
+  if ( j == end() ) return -1;
 
-    const vector<Vector *> & l = j->second;
-    int num = rand() % l.size();
+  const vector<Vector *> & l = j->second;
+  int num = rand() % l.size();
 
-    i.first = classno;
-    i.second = l[num];
+  i.first = classno;
+  i.second = l[num];
 
-    return classno;
+  return classno;
 }
 
 void LabeledSetVector::clear ()
 {
-    if ( ! selection ) {
-		for ( Permutation::const_iterator i  = insertOrder.begin(); 
-						  i != insertOrder.end();
-						  i++ )
-		{
-			const NICE::Vector *s = i->second;
-			delete s;
-		}
-		insertOrder.clear();
+  if ( ! selection ) {
+    for ( Permutation::const_iterator i  = insertOrder.begin();
+          i != insertOrder.end();
+          i++ )
+    {
+      const NICE::Vector *s = i->second;
+      delete s;
     }
+    insertOrder.clear();
+  }
 
-    std::map< int, vector<Vector *> >::clear();
+  std::map< int, vector<Vector *> >::clear();
 }
 
 void LabeledSetVector::add ( int classno, const NICE::Vector & x )
 {
-    if ( selection ) {
-		fprintf (stderr, "Add operation not available for selections !\n");
-		exit(-1);
-    }
-
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<Vector *>();
-		i = find(classno);
-    }
-    NICE::Vector *xp = new Vector(x);
-
-    i->second.push_back ( xp ); 
-    insertOrder.push_back ( ElementPointer ( classno, xp ) );
+  if ( selection ) {
+    fprintf ( stderr, "Add operation not available for selections !\n" );
+    exit ( -1 );
+  }
+
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<Vector *>();
+    i = find ( classno );
+  }
+  NICE::Vector *xp = new Vector ( x );
+
+  i->second.push_back ( xp );
+  insertOrder.push_back ( ElementPointer ( classno, xp ) );
 }
-    
+
 void LabeledSetVector::getPermutation ( Permutation & permutation ) const
 {
-    permutation = Permutation ( insertOrder );
+  permutation = Permutation ( insertOrder );
 }
 
 void LabeledSetVector::add_reference ( int classno, NICE::Vector *pointer )
 {
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<Vector *>();
-		i = find(classno);
-    }
-    i->second.push_back ( pointer ); 
-    insertOrder.push_back ( ElementPointer ( classno, pointer ) );
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<Vector *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( pointer );
+  insertOrder.push_back ( ElementPointer ( classno, pointer ) );
 }
-	
+
 void LabeledSetVector::getClasses ( std::vector<int> & classes ) const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-	classes.push_back ( i->first );
+  for ( const_iterator i = begin(); i != end(); i++ )
+    classes.push_back ( i->first );
 }
-	
+
 void LabeledSetVector::printInformation () const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-    {
-		cerr << "class " << i->first << ": " << i->second.size() << endl;
-    }
+  for ( const_iterator i = begin(); i != end(); i++ )
+  {
+    cerr << "class " << i->first << ": " << i->second.size() << endl;
+  }
 }
-	
+
 int LabeledSetVector::getMaxClassno() const
 {
-    int maxclassno = 0;
+  int maxclassno = 0;
 
-    for ( const_iterator i = begin(); i != end(); i++ )
-		if ( i->first > maxclassno ) 
-			maxclassno = i->first;
+  for ( const_iterator i = begin(); i != end(); i++ )
+    if ( i->first > maxclassno )
+      maxclassno = i->first;
 
-    return maxclassno;
+  return maxclassno;
 }
 
 void LabeledSetVector::getFlatRepresentation ( VVector & vecSet, NICE::Vector & vecSetLabels ) const
 {
-	int k = 0;
-	vecSetLabels.resize(count());
-	for ( LabeledSetVector::const_iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++)
-		for ( vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); 
-								 jLOOP_ALL != iLOOP_ALL->second.end(); 
-								 jLOOP_ALL++,k++ )
-		{
-			const NICE::Vector & (x) = *(*jLOOP_ALL);
-			vecSet.push_back ( x );
-			vecSetLabels[k] = iLOOP_ALL->first;
-		}
+  int k = 0;
+  vecSetLabels.resize ( count() );
+  for ( LabeledSetVector::const_iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++ )
+    for ( vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin();
+          jLOOP_ALL != iLOOP_ALL->second.end();
+          jLOOP_ALL++, k++ )
+    {
+      const NICE::Vector & ( x ) = * ( *jLOOP_ALL );
+      vecSet.push_back ( x );
+      vecSetLabels[k] = iLOOP_ALL->first;
+    }
 
 }
 

+ 107 - 95
cbaselib/LabeledSet.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LabeledSet.h
 * @brief Labeled set of vectors
 * @author Erik Rodner
@@ -18,143 +18,155 @@
 #include "ImageInfo.h"
 
 #define LOOP_ALL(ls) for(LabeledSetVector::const_iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH(classno,x) int (classno) = iLOOP_ALL->first; \
-			const NICE::Vector & (x) = *(*jLOOP_ALL);
-	
+  const NICE::Vector & (x) = *(*jLOOP_ALL);
+
 #define LOOP_ALL_NONCONST(ls) for(LabeledSetVector::iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH_NONCONST(classno,x) int (classno) = iLOOP_ALL->first; \
-			NICE::Vector & (x) = *(*jLOOP_ALL);
-				
+  NICE::Vector & (x) = *(*jLOOP_ALL);
+
 #define LOOP_ALL_S(ls) for(LabeledSet::const_iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<ImageInfo *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<ImageInfo *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH_S(classno,x) int (classno) = iLOOP_ALL->first; \
-			const std::string & (x) = (*jLOOP_ALL)->img();
+  const std::string & (x) = (*jLOOP_ALL)->img();
 
 #define EACH_INFO(classno,x) int (classno) = iLOOP_ALL->first; \
-			const ImageInfo & (x) = *(*jLOOP_ALL);
+  const ImageInfo & (x) = *(*jLOOP_ALL);
 
 
 namespace OBJREC {
 
-class LabeledSet : 
-	public std::map< int, std::vector<ImageInfo *> >
+class LabeledSet :
+      public std::map< int, std::vector<ImageInfo *> >
 {
-    public:
-	typedef std::vector<std::string *> ElementIterator;
-	typedef std::pair<size_t, const ImageInfo *> ElementPointer;
-	typedef std::vector< ElementPointer > Permutation;
+  public:
+    typedef std::vector<std::string *> ElementIterator;
+    typedef std::pair<size_t, const ImageInfo *> ElementPointer;
+    typedef std::vector< ElementPointer > Permutation;
+
+  private:
+    bool selection;
 
-    private:
-	bool selection;
+    Permutation insertOrder;
 
-	Permutation insertOrder;
+  public:
 
-    public:
+    void add_reference ( int classno, ImageInfo *pointer );
 
-	void add_reference ( int classno, ImageInfo *pointer );
+    LabeledSet ( bool selection = false );
+    ~LabeledSet ();
 
-	LabeledSet ( bool selection = false );
-	~LabeledSet ();
+    int numClasses () const
+    {
+      return size();
+    }
 
-	int numClasses () const
-	{   return size();   }
+    int count ( int classno ) const;
+    int count () const;
 
-	int count ( int classno ) const;
-	int count () const;
-	
-	void clear ();
+    void clear ();
 
-	void add ( int classno, ImageInfo *x );
+    void add ( int classno, ImageInfo *x );
 
-	void getPermutation ( Permutation & permutation ) const; 
-	void getClasses ( std::vector<int> & classes ) const; 
+    void getPermutation ( Permutation & permutation ) const;
+    void getClasses ( std::vector<int> & classes ) const;
 
-	void printInformation () const;
+    void printInformation () const;
 
-	friend class LabeledSetSelection<LabeledSet>;
+    friend class LabeledSetSelection<LabeledSet>;
 };
 
 
 /** simple labeled set of vectors as a specialization of std::map<> */
-class LabeledSetVector : 
-	public std::map< int, std::vector<NICE::Vector *> >, 
-	public NICE::Persistent
+class LabeledSetVector :
+      public std::map< int, std::vector<NICE::Vector *> >,
+      public NICE::Persistent
 {
-    public:
-	typedef std::vector<NICE::Vector *> ElementIterator;
-	typedef std::pair<int, const NICE::Vector *> ElementPointer;
-	typedef std::vector< ElementPointer > Permutation;	
-
-	enum {
-	    FILEFORMAT_INDEX = 0,
-	    FILEFORMAT_NOINDEX = 1,
-	    FILEFORMAT_RAW = 2,
-	    FILEFORMAT_INDEX_SPARSE_ONE = 3
-	};
-    
-    private:
-	bool selection;
+  public:
+    typedef std::vector<NICE::Vector *> ElementIterator;
+    typedef std::pair<int, const NICE::Vector *> ElementPointer;
+    typedef std::vector< ElementPointer > Permutation;
+
+    enum {
+      FILEFORMAT_INDEX = 0,
+      FILEFORMAT_NOINDEX = 1,
+      FILEFORMAT_RAW = 2,
+      FILEFORMAT_INDEX_SPARSE_ONE = 3
+    };
 
-	Permutation insertOrder;
+  private:
+    bool selection;
 
-    public:
+    Permutation insertOrder;
 
-	LabeledSetVector ( bool selection = false );
-	~LabeledSetVector ();
+  public:
 
-	void add_reference ( int classno, NICE::Vector *pointer );
+    LabeledSetVector ( bool selection = false );
+    ~LabeledSetVector ();
 
-	int dimension () const;
+    void add_reference ( int classno, NICE::Vector *pointer );
 
-	int numClasses () const
-	{   return size();   }
+    int dimension () const;
+
+    int numClasses () const
+    {
+      return size();
+    }
+
+    void restore ( std::istream & is, int format = FILEFORMAT_INDEX );
+    void restoreRAW ( std::istream & is );
+    void restoreASCII ( std::istream & is, int format = FILEFORMAT_INDEX );
+    void store ( std::ostream & os, int format = FILEFORMAT_INDEX ) const;
+    static void storeElement ( std::ostream & os, int classno, const NICE::Vector & x, int format = FILEFORMAT_INDEX );
+
+    ElementPointer pickRandomSample () const;
+
+    int count ( int classno ) const;
+    
+    /**
+     * @brief count all features
+     *
+     * @return int number of features
+     **/
+    int count () const;
 
-	void restore (std::istream & is, int format = FILEFORMAT_INDEX);
-	void restoreRAW ( std::istream & is );
-	void restoreASCII (std::istream & is, int format = FILEFORMAT_INDEX);
-	void store (std::ostream & os, int format = FILEFORMAT_INDEX) const;
-	static void storeElement ( std::ostream & os, int classno, const NICE::Vector & x, int format = FILEFORMAT_INDEX );
+    int pickRandomSample ( int classno, ElementPointer & i ) const;
 
-	ElementPointer pickRandomSample () const;
+    void clear ();
 
-	int count ( int classno ) const;
-	int count () const;
-	
-	int pickRandomSample ( int classno, ElementPointer & i ) const;
+    /** most important function: add a labeled vector */
+    void add ( int classno, const NICE::Vector & x );
 
-	void clear ();
+    void getPermutation ( Permutation & permutation ) const;
+    void getClasses ( std::vector<int> & classes ) const;
 
-	/** most important function: add a labeled vector */
-	void add ( int classno, const NICE::Vector & x );
+    void printInformation () const;
 
-	void getPermutation ( Permutation & permutation ) const; 
-	void getClasses ( std::vector<int> & classes ) const; 
-	
-	void printInformation () const;
+    void setSelection ( bool _selection = true ) {
+      selection = _selection;
+    };
 
-	void setSelection ( bool _selection = true ) { selection = _selection; };
+    /**
+     * returns the highest class number (not the number of classes!)
+     */
+    int getMaxClassno() const;
 
-	/**
-	 * returns the highest class number (not the number of classes!)
-	 */
-	int getMaxClassno() const;
+    /**
+     * converts LabeledSetVector to a NICE::VVector Set (containing data) and a Labelvector (containing labels for each Data)
+     * @param vecSet dataset (output)
+     * @param vecSetLabels labels (output)
+     */
+    void getFlatRepresentation ( NICE::VVector & vecSet, NICE::Vector & vecSetLabels ) const;
 
-	/**
-	 * converts LabeledSetVector to a NICE::VVector Set (containing data) and a Labelvector (containing labels for each Data)
-	 * @param vecSet dataset (output)
-	 * @param vecSetLabels labels (output)
-	 */
-	void getFlatRepresentation ( NICE::VVector & vecSet, NICE::Vector & vecSetLabels ) const;
-	
-	friend class LabeledSetSelection<LabeledSetVector>;
+    friend class LabeledSetSelection<LabeledSetVector>;
 };
 
 

+ 229 - 0
cbaselib/MutualInformation.cpp

@@ -0,0 +1,229 @@
+/** 
+* @file MutualInformation.cpp
+* @brief Part Selection with Mutual Information
+* @author Erik Rodner
+* @date 02/20/2008
+
+*/
+#include <iostream>
+
+#include "MutualInformation.h"
+#include "vislearning/baselib/Gnuplot.h"
+
+using namespace OBJREC;
+
+using namespace std;
+using namespace NICE;
+
+
+
+MutualInformation::MutualInformation( bool verbose )
+{
+  this->verbose = verbose;
+}
+
+MutualInformation::~MutualInformation()
+{
+}
+
+void MutualInformation::addStatistics ( const vector<Vector *> & v, size_t d, double threshold, size_t & ones ) const
+{
+  for ( vector<Vector *>::const_iterator j = v.begin() ; j != v.end(); j++ )
+	  if ( (*(*j))[d] > threshold ) ones++;
+}
+
+double MutualInformation::entropy ( size_t n1, size_t n2 ) const
+{
+  // - p_1 log p_1 - p_2 log p_2
+  // aber log im bereich [0,1] numerisch instabil
+  // daher
+  // p_1 log 1/p_1 + p_2 log 1/p_2
+  double sum = n1 + n2;
+  double log1 = n1 > 0 ? log(n1) : 0;
+  double log2 = n2 > 0 ? log(n2) : 0;
+  double logsum = (sum > 0) ? log(sum) : 0;
+
+  return - (n1/sum*log1 + n2/sum*log2) + logsum;
+}
+
+
+
+double MutualInformation::mutualInformationOverall ( const LabeledSetVector & ls, 
+					      size_t dimension,
+					      double threshold ) const
+{
+  double entropy_conditional = 0.0;
+  for ( LabeledSetVector::const_iterator i = ls.begin();
+           i != ls.end();
+           i++ )
+  {
+    size_t ones = 0;
+    addStatistics ( i->second, dimension, threshold, ones );
+    
+    double entropy_conditional_class = entropy ( ones, i->second.size() - ones );
+    entropy_conditional += entropy_conditional_class;
+  }
+  entropy_conditional /= ls.size();
+
+  double entropy_joint = 0.0;
+  size_t ones = 0;
+  size_t count = 0;
+
+  for ( LabeledSetVector::const_iterator i = ls.begin();
+           i != ls.end();
+           i++ )
+  {
+    addStatistics ( i->second, dimension, threshold, ones );
+    count += i->second.size();
+  }
+  entropy_joint = entropy ( ones, count - ones );
+  
+  return entropy_joint - entropy_conditional;
+}
+
+double MutualInformation::mutualInformationClass ( const LabeledSetVector & ls, 
+						   size_t classno,
+						  size_t dimension,
+						  double threshold ) const
+{
+  size_t ones_p  = 0;
+  LabeledSetVector::const_iterator iclassno = ls.find(classno);
+  if ( iclassno == ls.end() )
+  {
+    fprintf (stderr, "MutualInformation::mutualInformationClass: classno %u not found\n", classno );
+    exit(-1);
+  }
+  size_t count_p = iclassno->second.size();
+
+  addStatistics ( iclassno->second, dimension, threshold, ones_p );
+  
+  double entropy_conditional_p = entropy ( ones_p, count_p - ones_p );
+
+  size_t ones_n  = 0;
+  size_t count_n = 0;
+  for ( LabeledSetVector::const_iterator i = ls.begin();
+           i != ls.end();
+           i++ )
+  {
+    if ( i->first != (int)classno );
+    addStatistics ( i->second, dimension, threshold, ones_n );
+    count_n += i->second.size();
+  }
+  double entropy_conditional_n = entropy ( ones_n, count_n - ones_n );
+  double entropy_conditional = 0.5 * ( entropy_conditional_n + entropy_conditional_p );
+  double entropy_joint = entropy ( ones_p + ones_n, count_p + count_n - ones_p - ones_n );
+    
+  return entropy_joint - entropy_conditional;
+}
+
+
+
+double MutualInformation::computeThresholdClass ( const LabeledSetVector & ls, size_t classno,
+						  size_t dimension, double & opt_threshold ) const
+{
+  vector<double> thresholds;
+  LOOP_ALL(ls)
+  {
+    EACH(classno, v);
+    double val = v[dimension];
+    thresholds.push_back ( val );
+  }
+  sort ( thresholds.begin(), thresholds.end() );
+  thresholds.erase( std::unique( thresholds.begin(), thresholds.end()), thresholds.end());
+    
+  opt_threshold = 0.0;
+  double opt_mi = 0.0;
+
+  for ( vector<double>::const_iterator i  = thresholds.begin();
+               i != thresholds.end(); 
+         i++ )
+  {
+    vector<double>::const_iterator j = i + 1;
+    if ( j == thresholds.end() ) break;
+
+    double threshold = 0.5 * ((*i) + (*j));
+    double mi = mutualInformationClass ( ls, classno, dimension, threshold );
+    if ( mi > opt_mi ) {
+        opt_mi = mi;
+        opt_threshold = threshold;
+    }
+  }
+
+  return opt_mi;
+}
+
+
+double MutualInformation::computeThresholdOverall ( const LabeledSetVector & ls, size_t dimension, double & opt_threshold ) const
+{
+  vector<double> thresholds;
+  vector<int> y;
+  LOOP_ALL(ls)
+  {
+    EACH(classno, v);
+    double val = v[dimension];
+    thresholds.push_back ( val );
+    y.push_back(classno);
+  }
+  sort ( thresholds.begin(), thresholds.end() );
+  thresholds.erase( std::unique( thresholds.begin(), thresholds.end()), thresholds.end());
+  
+  opt_threshold = 0.0;
+  double opt_mi = 0.0;
+
+  uint ind = 0;
+  for ( vector<double>::const_iterator i  = thresholds.begin();
+               i != thresholds.end(); i++, ind++ )
+  {
+    vector<double>::const_iterator j = i + 1;
+    if ( j == thresholds.end() ) break;
+
+    // the optimimum can not be found at non-class borders
+    if ( y[ind] == y[ind+1] ) continue;
+
+    double threshold = 0.5 * ((*i) + (*j));
+
+    // FIXME: This call is pretty inefficient!!
+    // We can directly count the features here...might be 100times faster :)
+    double mi = mutualInformationOverall ( ls, dimension, threshold );
+    if ( mi > opt_mi ) {
+        opt_mi = mi;
+        opt_threshold = threshold;
+    }
+  }
+   
+  return opt_mi;
+}
+
+void MutualInformation::computeThresholdsClass ( const LabeledSetVector & ls, size_t classno, 
+						 NICE::Vector & thresholds, NICE::Vector & mis ) const
+{
+  size_t max_dimension = ls.dimension();
+
+  thresholds.resize(max_dimension);
+  mis.resize(max_dimension);
+
+  for ( size_t k = 0 ; k < max_dimension ; k++ )
+  {
+    double t, mi;
+    mi = computeThresholdClass ( ls, classno, k, t );
+    mis[k] = mi;
+    thresholds[k] = t;
+  }
+}
+
+void MutualInformation::computeThresholdsOverall ( const LabeledSetVector & ls, NICE::Vector & thresholds, NICE::Vector & mis ) const
+{
+  size_t max_dimension = ls.dimension();
+
+  thresholds.resize(max_dimension);
+  mis.resize(max_dimension);
+  for ( size_t k = 0 ; k < max_dimension ; k++ )
+  {
+    if ( verbose )
+      cerr << "MutualInformation: Optimizing threshold for feature " << k << " / " << max_dimension << endl;
+    double t, mi;
+    mi = computeThresholdOverall ( ls, k, t );
+    mis[k] = mi;
+    thresholds[k] = t;
+  }
+}

+ 93 - 0
cbaselib/MutualInformation.h

@@ -0,0 +1,93 @@
+/** 
+* @file MutualInformation.h
+* @brief Part selection and thresholding with Mutual Information
+* @author Erik Rodner
+* @date 02/20/2008
+
+*/
+#ifndef MUTUALINFORMATIONINCLUDE
+#define MUTUALINFORMATIONINCLUDE
+
+#include "core/vector/VVector.h"
+#include "vislearning/cbaselib/LabeledSet.h"
+
+
+namespace OBJREC {
+
+/** Part selection and thresholding with mutual information */
+class MutualInformation
+{
+  protected:
+
+    //! verbose handling
+    bool verbose;
+
+    /**
+    * @brief helper function: loop through all vectors and count how often f[d]>threshold
+    *
+    * @param v multi-dimensional features
+    * @param d feature index used
+    * @param threshold used to generate the binary feature
+    * @param ones number of times f[d] is above threshold
+    */
+	  void addStatistics ( const std::vector<NICE::Vector *> & v, size_t d, double threshold, size_t & ones ) const;
+
+    
+    /**
+    * @brief Compute the entropy of 2-bin discrete distribution
+    *
+    * @param n1 number of elements for bin 1
+    * @param n2 number of elements for bin 2
+    *
+    * @return entropy value
+    */
+	  double entropy ( size_t n1, size_t n2 ) const;
+
+  public:
+  
+    /** simple constructor */
+    MutualInformation( bool verbose = false );
+        
+    /** simple destructor */
+    virtual ~MutualInformation();
+ 
+    /**
+    * @brief Compute the mutual information between a one-dimensional thresholded feature and the class information
+    *
+    * @param ls labeled set of multi-dimensional feature vectors
+    * @param dimension feature index to use
+    * @param threshold threshold used to binarize the feature
+    *
+    * @return mutual information value
+    */
+    double mutualInformationOverall ( const LabeledSetVector & ls, size_t dimension, double threshold ) const;
+    double mutualInformationClass ( const LabeledSetVector & ls, size_t classno, size_t dimension, double threshold ) const;
+	
+    /**
+    * @brief Compute an optimal threshold for a one-dimensional feature that best retains class information, i.e.
+    * maximizes the mutual information between the feature B and the class label C
+    * @param ls labeled set of multi-dimensional feature vectors
+    * @param dimension feature index to use
+    * @param opt_threshold resulting optimal threshold
+    *
+    * @return resulting mutual information of the optimal threshold
+    */
+    double computeThresholdOverall ( const LabeledSetVector & ls, size_t dimension, double & opt_threshold ) const;
+    double computeThresholdClass ( const LabeledSetVector & ls, size_t classno, size_t dimension, double & opt_threshold ) const;
+
+    /**
+    * @brief Compute optimal thresholds for each dimension of a multi-dimensional feature trying to retain class information
+    *
+    * @param ls labeled set of multi-dimensional feature vectors
+    * @param thresholds vector of thresholds for each dimension
+    * @param mis vector of resulting mutual information values
+    */
+    void computeThresholdsOverall ( const LabeledSetVector & ls, NICE::Vector & thresholds, NICE::Vector & mis ) const;
+    void computeThresholdsClass ( const LabeledSetVector & ls, size_t classno, NICE::Vector & thresholds, NICE::Vector & mis ) const;
+    
+};
+
+
+} // namespace
+
+#endif

+ 127 - 127
classifier/fpclassifier/logisticregression/FPCSMLR.cpp

@@ -9,153 +9,153 @@ using namespace NICE;
 
 FPCSMLR::FPCSMLR ()
 {
-	inpic = false;
+  inpic = false;
 }
 
-FPCSMLR::FPCSMLR( const Config *_conf, string section ) : conf(_conf)
+FPCSMLR::FPCSMLR ( const Config *_conf, string section ) : conf ( _conf )
 {
-	confsection = section;
-	inpic = conf->gB(section, "inpic", false );
+  confsection = section;
+  inpic = conf->gB ( section, "inpic", false );
 }
 
 FPCSMLR::~FPCSMLR()
 {
-	//clean up
+  //clean up
 }
 
 ClassificationResult FPCSMLR::classify ( Example & pce )
 {
-	FullVector overall_distribution(maxClassNo+1);
-	overall_distribution[maxClassNo] = 0.0;
-
-	double maxp = -numeric_limits<double>::max();
-	int classno = 0;
-	
-	double sum  = 0.0;
-		
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		overall_distribution[i] = classifiers[i].classify(pce);
-		
-		sum += overall_distribution[i];
-		
-		if(maxp < overall_distribution[i])
-		{
-			classno = i;
-			maxp = overall_distribution[i];
-		}
-	}
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		overall_distribution[i] /= sum;
-	}
-
-	return ClassificationResult ( classno, overall_distribution );
+  FullVector overall_distribution ( maxClassNo + 1 );
+  overall_distribution[maxClassNo] = 0.0;
+
+  double maxp = -numeric_limits<double>::max();
+  int classno = 0;
+
+  double sum  = 0.0;
+
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    overall_distribution[i] = classifiers[i].classify ( pce );
+
+    sum += overall_distribution[i];
+
+    if ( maxp < overall_distribution[i] )
+    {
+      classno = i;
+      maxp = overall_distribution[i];
+    }
+  }
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    overall_distribution[i] /= sum;
+  }
+
+  return ClassificationResult ( classno, overall_distribution );
 }
 
 void FPCSMLR::train ( FeaturePool & _fp, Examples & examples )
 {
 
-	cout << "start train" << endl;
-	fp = FeaturePool(_fp);
-    
-	// Anzahl von Merkmalen
-	int fanz = examples.size();
-
-	maxClassNo = -1;
-	for(int i = 0; i < fanz; i++)
-	{
-		maxClassNo = std::max(maxClassNo, examples[i].first);
-	}
-	maxClassNo++;
-	
-	assert(fanz >= maxClassNo);
-	
-	classifiers.resize(maxClassNo);
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		cout << "classifier no " << i << " training starts" << endl;
-		classifiers[i] = SLR(conf, confsection);
-
-		if(inpic)
-		{
-	
-			vector<bool> classinpic;
-			
-			for(int j = 0; j < (int)examples.size(); j++)
-			{
-				if(examples[j].first == i)
-				{
-					if(examples[j].second.position < (int)classinpic.size())
-						classinpic[examples[j].second.position] = true;
-					else if(examples[j].second.position == (int)classinpic.size())
-						classinpic.push_back(true);
-					else
-					{
-						while(examples[j].second.position > (int)classinpic.size())
-						{
-							classinpic.push_back(false);
-						}
-						classinpic.push_back(true);
-					}
-				}
-			}
-			
-			Examples ex2;
-
-			for(int j = 0; j < (int)examples.size(); j++)
-			{
-				if(examples[j].second.position >= (int)classinpic.size())
-						continue;
-				if(classinpic[examples[j].second.position])
-				{
-					Example e;
-					e.svec = examples[j].second.svec;
-					e.vec = examples[j].second.vec;
-					ex2.push_back ( pair<int, Example> ( examples[j].first, e ) );
-				}
-			}
-			cout << "examples for class " << i << ": " << ex2.size() << endl;
-			
-			if(ex2.size() <= 2)
-				continue;
-			
-			classifiers[i].train(_fp, ex2, i);
-			
-			for(int j = 0; j < (int)ex2.size(); j++)
-			{
-				ex2[j].second.svec = NULL;
-			}
-		}
-		else
-		{
-			classifiers[i].train(_fp, examples, i);
-		}
-	}
-
-	cout << "end train" << endl;
+  cout << "start train" << endl;
+  fp = FeaturePool ( _fp );
+
+  // Anzahl von Merkmalen
+  int fanz = examples.size();
+
+  maxClassNo = -1;
+  for ( int i = 0; i < fanz; i++ )
+  {
+    maxClassNo = std::max ( maxClassNo, examples[i].first );
+  }
+  maxClassNo++;
+
+  assert ( fanz >= maxClassNo );
+
+  classifiers.resize ( maxClassNo );
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    cout << "classifier no " << i << " training starts" << endl;
+    classifiers[i] = SLR ( conf, confsection );
+
+    if ( inpic )
+    {
+
+      vector<bool> classinpic;
+
+      for ( int j = 0; j < ( int ) examples.size(); j++ )
+      {
+        if ( examples[j].first == i )
+        {
+          if ( examples[j].second.position < ( int ) classinpic.size() )
+            classinpic[examples[j].second.position] = true;
+          else if ( examples[j].second.position == ( int ) classinpic.size() )
+            classinpic.push_back ( true );
+          else
+          {
+            while ( examples[j].second.position > ( int ) classinpic.size() )
+            {
+              classinpic.push_back ( false );
+            }
+            classinpic.push_back ( true );
+          }
+        }
+      }
+
+      Examples ex2;
+
+      for ( int j = 0; j < ( int ) examples.size(); j++ )
+      {
+        if ( examples[j].second.position >= ( int ) classinpic.size() )
+          continue;
+        if ( classinpic[examples[j].second.position] )
+        {
+          Example e;
+          e.svec = examples[j].second.svec;
+          e.vec = examples[j].second.vec;
+          ex2.push_back ( pair<int, Example> ( examples[j].first, e ) );
+        }
+      }
+      cout << "examples for class " << i << ": " << ex2.size() << endl;
+
+      if ( ex2.size() <= 2 )
+        continue;
+
+      classifiers[i].train ( _fp, ex2, i );
+
+      for ( int j = 0; j < ( int ) ex2.size(); j++ )
+      {
+        ex2[j].second.svec = NULL;
+      }
+    }
+    else
+    {
+      classifiers[i].train ( _fp, examples, i );
+    }
+  }
+
+  cout << "end train" << endl;
 }
 
 
-void FPCSMLR::restore (istream & is, int format)
+void FPCSMLR::restore ( istream & is, int format )
 {
-	is >> maxClassNo;
-	classifiers.resize(maxClassNo);
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		classifiers[i].restore(is, format);
-	}
+  is >> maxClassNo;
+  classifiers.resize ( maxClassNo );
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    classifiers[i].restore ( is, format );
+  }
 }
 
-void FPCSMLR::store (ostream & os, int format) const
+void FPCSMLR::store ( ostream & os, int format ) const
 {
 
-	if(format!=-9999) os << maxClassNo;
+  if ( format != -9999 ) os << maxClassNo;
 
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		classifiers[i].store(os, format);
-	}
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    classifiers[i].store ( os, format );
+  }
 }
 
 void FPCSMLR::clear ()
@@ -165,15 +165,15 @@ void FPCSMLR::clear ()
 
 FeaturePoolClassifier *FPCSMLR::clone () const
 {
-	//TODO: wenn alle Variablen der Klasse bekannt sind, dann übergebe diese mit
-	FPCSMLR *o = new FPCSMLR ( conf, confsection );
+  //TODO: wenn alle Variablen der Klasse bekannt sind, dann übergebe diese mit
+  FPCSMLR *o = new FPCSMLR ( conf, confsection );
 
-	o->maxClassNo = maxClassNo;
+  o->maxClassNo = maxClassNo;
 
-	return o;
+  return o;
 }
 
 void FPCSMLR::setComplexity ( int size )
 {
-	cerr << "FPCSMLR: no complexity to set" << endl;
+  cerr << "FPCSMLR: no complexity to set" << endl;
 }

+ 431 - 431
classifier/fpclassifier/logisticregression/SLR.cpp

@@ -18,115 +18,115 @@ SLR::SLR ()
 {
 }
 
-SLR::SLR( const Config *_conf, string section ) : conf(_conf)
+SLR::SLR ( const Config *_conf, string section ) : conf ( _conf )
 {
-	maxiter = conf->gI(section, "maxiter", 20000 );
-	resamp_decay = conf->gD(section, "resamp_decay", 0.5 );
-	convergence_tol = conf->gD(section, "convergence_tol", 1e-7 );
-	min_resamp =  conf->gD(section, "min_resamp", 0.001 );
-	lambda = conf->gD(section, "lambda", 0.1 );
-	samplesperclass = conf->gD(section, "samplesperclass", 200.0);
-	weight.setDim(0);
-	fdim = 0;
+  maxiter = conf->gI ( section, "maxiter", 20000 );
+  resamp_decay = conf->gD ( section, "resamp_decay", 0.5 );
+  convergence_tol = conf->gD ( section, "convergence_tol", 1e-7 );
+  min_resamp =  conf->gD ( section, "min_resamp", 0.001 );
+  lambda = conf->gD ( section, "lambda", 0.1 );
+  samplesperclass = conf->gD ( section, "samplesperclass", 200.0 );
+  weight.setDim ( 0 );
+  fdim = 0;
 }
 
 SLR::~SLR()
 {
-	//clean up
+  //clean up
 }
 
 double SLR::classify ( Example & pce )
 {
-	double result;
-	SparseVector *svec;
+  double result;
+  SparseVector *svec;
 
-	if(weight.getDim() == 0)
-		return 0.0;
+  if ( weight.getDim() == 0 )
+    return 0.0;
 
-	bool newvec = false;
-	
-	if(pce.svec != NULL)
-	{
-		svec = pce.svec;
-	}
-	else
-	{
-		Vector x;
+  bool newvec = false;
 
-		x = *(pce.vec);
+  if ( pce.svec != NULL )
+  {
+    svec = pce.svec;
+  }
+  else
+  {
+    Vector x;
+
+    x = * ( pce.vec );
 
 #ifdef featnorm
-		for(int m = 0; m < (int)x.size(); m++)
-		{
-			x[m] = (x[m]-minval[m]) /(maxval[m] - minval[m]);
-		}
+    for ( int m = 0; m < ( int ) x.size(); m++ )
+    {
+      x[m] = ( x[m] - minval[m] ) / ( maxval[m] - minval[m] );
+    }
 #endif
-		svec = new SparseVector(x);
+    svec = new SparseVector ( x );
+
+    svec->setDim ( x.size() );
 
-		svec->setDim(x.size());
+    newvec = true;
 
-		newvec = true;
+  }
 
-	}
-		
-	if(weight.size() == 0)
-		result = 0.0;
-	else
-	{
-		result = 1.0/(1.0+exp(-svec->innerProduct(weight)));
-	}
+  if ( weight.size() == 0 )
+    result = 0.0;
+  else
+  {
+    result = 1.0 / ( 1.0 + exp ( -svec->innerProduct ( weight ) ) );
+  }
 
-	if(newvec)
-		delete svec;
+  if ( newvec )
+    delete svec;
 
-	return result;
+  return result;
 }
 
 void SLR::train ( FeaturePool & _fp, Examples & examples, int classno )
 {
 
-	cout << "start train" << endl;
-	fp = FeaturePool(_fp);
-    
-	// Anzahl von Merkmalen
-	int fanz = examples.size();
-	assert(fanz >= 2);
-
-	// Merkmalsdimension bestimmen
-	Vector x;
-	fp.calcFeatureVector(examples[0].second, x);
-	fdim = x.size();
-	assert(fdim > 0);
-
-	stepwise_regression(examples, classno);	
-	cout << "end train" << endl;
+  cout << "start train" << endl;
+  fp = FeaturePool ( _fp );
+
+  // Anzahl von Merkmalen
+  int fanz = examples.size();
+  assert ( fanz >= 2 );
+
+  // Merkmalsdimension bestimmen
+  Vector x;
+  fp.calcFeatureVector ( examples[0].second, x );
+  fdim = x.size();
+  assert ( fdim > 0 );
+
+  stepwise_regression ( examples, classno );
+  cout << "end train" << endl;
 }
 
-void SLR::restore (istream & is, int format)
+void SLR::restore ( istream & is, int format )
 {
-	weight.restore(is, format);
-	fdim = (int) weight.getDim();
-	maxval.resize(fdim);
-	minval.resize(fdim);
-	for(int i = 0; i < fdim; i++)
-	{
-		is >> maxval[i];
-		is >> minval[i];
-	}
+  weight.restore ( is, format );
+  fdim = ( int ) weight.getDim();
+  maxval.resize ( fdim );
+  minval.resize ( fdim );
+  for ( int i = 0; i < fdim; i++ )
+  {
+    is >> maxval[i];
+    is >> minval[i];
+  }
 }
 
-void SLR::store (ostream & os, int format) const
+void SLR::store ( ostream & os, int format ) const
 
 {
-	if(format!=-9999){
-		weight.store(os, format);
-		for(int i = 0; i < fdim; i++)
-		{
-			os << maxval[i] << " " << minval[i] << endl;
-		}
-	}else{
-		weight.store(os, format);
-	}
+  if ( format != -9999 ) {
+    weight.store ( os, format );
+    for ( int i = 0; i < fdim; i++ )
+    {
+      os << maxval[i] << " " << minval[i] << endl;
+    }
+  } else {
+    weight.store ( os, format );
+  }
 }
 
 void SLR::clear ()
@@ -134,385 +134,385 @@ void SLR::clear ()
 //TODO: einbauen
 }
 
-int SLR::stepwise_regression(Examples &x, int classno)
+int SLR::stepwise_regression ( Examples &x, int classno )
 {
-	// initialize randomization
-	srand (time(NULL));
-	//srand (1);
-	
-	cout << "start regression" << endl;
-	
-	// get the number of features
-	int fnum = x.size();
-	
-	// create Datamatrix
-	GMSparseVectorMatrix X;
-	
-	GMSparseVectorMatrix Y;
-	
-	vector<int> count(2, 0);
-
-	maxval.resize(fdim);
-	minval.resize(fdim);
-
-	if(x[0].second.svec == NULL) //input normal vectors
-	{
-		Vector feat;
-
-		for(int i = 0; i < fdim; i++)
-		{
-			maxval[i] = numeric_limits<double>::min();
-			minval[i] = numeric_limits<double>::max();
-		}
-		
-		for(int i = 0; i < fnum; i++)
-		{
-			int pos = 0;
-			if(x[i].first != classno)
-				pos = 1;
-			
-			++count[pos];
-
-			fp.calcFeatureVector(x[i].second, feat);
+  // initialize randomization
+  srand ( time ( NULL ) );
+  //srand (1);
+
+  cout << "start regression" << endl;
+
+  // get the number of features
+  int fnum = x.size();
+
+  // create Datamatrix
+  GMSparseVectorMatrix X;
+
+  GMSparseVectorMatrix Y;
+
+  vector<int> count ( 2, 0 );
+
+  maxval.resize ( fdim );
+  minval.resize ( fdim );
+
+  if ( x[0].second.svec == NULL ) //input normal vectors
+  {
+    Vector feat;
+
+    for ( int i = 0; i < fdim; i++ )
+    {
+      maxval[i] = numeric_limits<double>::min();
+      minval[i] = numeric_limits<double>::max();
+    }
+
+    for ( int i = 0; i < fnum; i++ )
+    {
+      int pos = 0;
+      if ( x[i].first != classno )
+        pos = 1;
+
+      ++count[pos];
+
+      fp.calcFeatureVector ( x[i].second, feat );
 #ifdef featnorm
-			for(int m = 0; m < (int)feat.size(); m++)
-			{
-				minval[m] = std::min(minval[m], feat[m]);
-				maxval[m] = std::max(maxval[m], feat[m]);
-			}
+      for ( int m = 0; m < ( int ) feat.size(); m++ )
+      {
+        minval[m] = std::min ( minval[m], feat[m] );
+        maxval[m] = std::max ( maxval[m], feat[m] );
+      }
 #endif
-			fdim = feat.size();
-		}
-	}
-	else //input Sparse Vectors
-	{
-		for(int i = 0; i < fnum; i++)
-		{
-			int pos = 0;
-			if(x[i].first != classno)
-				pos = 1;
-			
-			++count[pos];
-		}
-		fdim = x[0].second.svec->getDim();
-	}
-	
-	if(count[0] == 0 || count[1] == 0)
-	{
-		cerr << "not enought samples " << count[0] << " : " << count[1] << endl;
-		weight.setDim(0);
-		return -1;
-	}
-
-	double samples = std::min(count[0], count[1]);
-	samples = std::min(samples, samplesperclass);
-	//samples = std::max(samples, 200);
-	//samples = samplesperclass;
-	
-	vector<double> rands(2,0.0);
-	vector<double> allsizes(2,0.0);
-	for(int i = 0; i < 2; i++)
-	{
-		rands[i] = 1.0;								//use all samples (default if samples>count[i])
-		if(samples>0 && samples<1) rands[i] = samples;				//use relative number of samples wrt. class size
-		if(samples>1 && samples<=count[i]) rands[i] = samples/(double)count[i]; //use (approximately) fixed absolute number of samples for each class
-		allsizes[i]=count[i];
-		count[i] = 0;
-	}
-
-	for(int i = 0; i < fnum; i++)
-	{
-		int pos = 0;
-		if(x[i].first != classno)
-			pos = 1;
-			
-			
-		double r = (double)rand()/(double)RAND_MAX;	
-			
-		if( r > rands[pos])
-			continue;
-		++count[pos];
-
-		if(x[0].second.svec == NULL) 
-		{
-			Vector feat;
-			fp.calcFeatureVector(x[i].second, feat);
+      fdim = feat.size();
+    }
+  }
+  else //input Sparse Vectors
+  {
+    for ( int i = 0; i < fnum; i++ )
+    {
+      int pos = 0;
+      if ( x[i].first != classno )
+        pos = 1;
+
+      ++count[pos];
+    }
+    fdim = x[0].second.svec->getDim();
+  }
+
+  if ( count[0] == 0 || count[1] == 0 )
+  {
+    cerr << "not enought samples " << count[0] << " : " << count[1] << endl;
+    weight.setDim ( 0 );
+    return -1;
+  }
+
+  double samples = std::min ( count[0], count[1] );
+  samples = std::min ( samples, samplesperclass );
+  //samples = std::max(samples, 200);
+  //samples = samplesperclass;
+
+  vector<double> rands ( 2, 0.0 );
+  vector<double> allsizes ( 2, 0.0 );
+  for ( int i = 0; i < 2; i++ )
+  {
+    rands[i] = 1.0;        //use all samples (default if samples>count[i])
+    if ( samples > 0 && samples < 1 ) rands[i] = samples;    //use relative number of samples wrt. class size
+    if ( samples > 1 && samples <= count[i] ) rands[i] = samples / ( double ) count[i]; //use (approximately) fixed absolute number of samples for each class
+    allsizes[i] = count[i];
+    count[i] = 0;
+  }
+
+  for ( int i = 0; i < fnum; i++ )
+  {
+    int pos = 0;
+    if ( x[i].first != classno )
+      pos = 1;
+
+
+    double r = ( double ) rand() / ( double ) RAND_MAX;
+
+    if ( r > rands[pos] )
+      continue;
+    ++count[pos];
+
+    if ( x[0].second.svec == NULL )
+    {
+      Vector feat;
+      fp.calcFeatureVector ( x[i].second, feat );
 #ifdef featnorm
-			for(int m = 0; m < (int)feat.size(); m++)
-			{
-				feat[m] = (feat[m]-minval[m]) /(maxval[m] - minval[m]);
-			}
+      for ( int m = 0; m < ( int ) feat.size(); m++ )
+      {
+        feat[m] = ( feat[m] - minval[m] ) / ( maxval[m] - minval[m] );
+      }
 #endif
 
-			X.addRow(feat);
-		}
-		else
-		{
-			X.addRow(x[i].second.svec);
-		}
-		SparseVector *v = new SparseVector(2);
-		(*v)[pos] = 1.0;
-		Y.addRow(v);
-	}
-	Y.setDel();
-
-	if(x[0].second.svec == NULL)
-		X.setDel();
-		
-	for(int i = 0; i < 2; i++)
-	{
-		cerr << "Examples for class " << i << ": " << count[i] << " out of " << allsizes[i] << " with p = " << rands[i] << endl;
-	}	
-	
+      X.addRow ( feat );
+    }
+    else
+    {
+      X.addRow ( x[i].second.svec );
+    }
+    SparseVector *v = new SparseVector ( 2 );
+    ( *v ) [pos] = 1.0;
+    Y.addRow ( v );
+  }
+  Y.setDel();
+
+  if ( x[0].second.svec == NULL )
+    X.setDel();
+
+  for ( int i = 0; i < 2; i++ )
+  {
+    cerr << "Examples for class " << i << ": " << count[i] << " out of " << allsizes[i] << " with p = " << rands[i] << endl;
+  }
+
 #undef NORMALIZATION
 #ifdef NORMALIZATION
-	GMSparseVectorMatrix Xred;
-	Xred.resize(X.rows(), X.cols());
-
-	for(int r = 0; r < (int)Xred.rows(); r++)
-	{
-		for(int c = 0; c < (int)Xred.cols(); c++)
-		{
-			double tmp = X[r].get(c);
-			
-			if(Y[r].get(0) == 1)
-				tmp *= count[0]/fnum;
-			else
-				tmp *= count[1]/fnum;
-			
-			if(fabs(tmp) > 10e-7)
-				Xred[r][c] = tmp;
-		}
-	}
+  GMSparseVectorMatrix Xred;
+  Xred.resize ( X.rows(), X.cols() );
+
+  for ( int r = 0; r < ( int ) Xred.rows(); r++ )
+  {
+    for ( int c = 0; c < ( int ) Xred.cols(); c++ )
+    {
+      double tmp = X[r].get ( c );
+
+      if ( Y[r].get ( 0 ) == 1 )
+        tmp *= count[0] / fnum;
+      else
+        tmp *= count[1] / fnum;
+
+      if ( fabs ( tmp ) > 10e-7 )
+        Xred[r][c] = tmp;
+    }
+  }
 #endif
 
-	fnum = X.rows();
-	
-	GMSparseVectorMatrix xY;
+  fnum = X.rows();
+
+  GMSparseVectorMatrix xY;
 #ifdef NORMALIZATION
-	Xred.mult(Y, xY, true);
+  Xred.mult ( Y, xY, true );
 #else
-	X.mult(Y, xY, true);
+  X.mult ( Y, xY, true );
 #endif
 
-	weight.setDim(fdim);
-
-	// for faster Computing Xw = X*w	
-	GMSparseVectorMatrix Xw;
-	X.mult(weight, Xw, false, true);
-	SparseVector S(fnum);
-
-	for(int r = 0; r < fnum; r++)
-	{
-		S[r] = 0.0;
-		for(int c = 0; c < 2; c++)
-		{
-			S[r] += exp(Xw[r].get(c));
-		}
-	}
-
-	// for faster computing ac[i] = (maxClassNo-1)/(2*maxClassNo) * Sum_j (x_i (j))^2
-	
-	Vector ac(fdim);
-	Vector lm_2_ac(fdim);
-	
-	for(int f = 0; f < fdim; f++)
-	{
-		ac[f] = 0.0;
-		for(int a = 0; a < fnum; a++)
-		{
-			ac[f] += X[a].get(f)*X[a].get(f);
-		}
-		ac[f] *= 0.25;
-		lm_2_ac[f] = (lambda/2.0)/ac[f];
-	}
-	
-	// initialize the iterative optimization
-	double incr = numeric_limits<double>::max();
-	long non_zero = 0;
-	long wasted_basis = 0;
-	long needed_basis = 0;
-	
-	// prob of resample each weight
-	vector<double> p_resamp;
-	p_resamp.resize(fdim);
-
-	// loop over cycles
-	long cycle = 0;
-	
-	for (cycle = 0; cycle < maxiter; cycle++)
-	{
+  weight.setDim ( fdim );
+
+  // for faster Computing Xw = X*w
+  GMSparseVectorMatrix Xw;
+  X.mult ( weight, Xw, false, true );
+  SparseVector S ( fnum );
+
+  for ( int r = 0; r < fnum; r++ )
+  {
+    S[r] = 0.0;
+    for ( int c = 0; c < 2; c++ )
+    {
+      S[r] += exp ( Xw[r].get ( c ) );
+    }
+  }
+
+  // for faster computing ac[i] = (maxClassNo-1)/(2*maxClassNo) * Sum_j (x_i (j))^2
+
+  Vector ac ( fdim );
+  Vector lm_2_ac ( fdim );
+
+  for ( int f = 0; f < fdim; f++ )
+  {
+    ac[f] = 0.0;
+    for ( int a = 0; a < fnum; a++ )
+    {
+      ac[f] += X[a].get ( f ) * X[a].get ( f );
+    }
+    ac[f] *= 0.25;
+    lm_2_ac[f] = ( lambda / 2.0 ) / ac[f];
+  }
+
+  // initialize the iterative optimization
+  double incr = numeric_limits<double>::max();
+  long non_zero = 0;
+  long wasted_basis = 0;
+  long needed_basis = 0;
+
+  // prob of resample each weight
+  vector<double> p_resamp;
+  p_resamp.resize ( fdim );
+
+  // loop over cycles
+  long cycle = 0;
+
+  for ( cycle = 0; cycle < maxiter; cycle++ )
+  {
 #ifdef SLRDEBUG
-		cerr << "iteration: " << cycle << " of " << maxiter << endl;
+    cerr << "iteration: " << cycle << " of " << maxiter << endl;
 #endif
-    	// zero out the diffs for assessing change
-		double sum2_w_diff = 0.0;
-		double sum2_w_old = 0.0;
-		wasted_basis = 0;
-		if (cycle==1)
-			needed_basis = 0;		
-		
-    	// update each weight
+    // zero out the diffs for assessing change
+    double sum2_w_diff = 0.0;
+    double sum2_w_old = 0.0;
+    wasted_basis = 0;
+    if ( cycle == 1 )
+      needed_basis = 0;
+
+    // update each weight
 //#pragma omp parallel for
-		for (int basis = 0; basis < fdim; basis++) // über alle Dimensionen
-		{
-			int changed = 0;
-			// get the starting weight
-			double w_old = weight.get(basis);
-
-			// set the p_resamp if it's the first cycle
-			if (cycle == 0)
-			{
-				p_resamp[basis] = 1.0;
-			}
-
-			// see if we're gonna update
-			double rval = (double)rand()/(double)RAND_MAX;			
-			
-			if ((w_old != 0) || (rval < p_resamp[basis]))
-			{
-	  			// calc the probability
-				double XdotP = 0.0;
-				for (int i = 0; i < fnum; i++)
-				{
+    for ( int basis = 0; basis < fdim; basis++ ) // über alle Dimensionen
+    {
+      int changed = 0;
+      // get the starting weight
+      double w_old = weight.get ( basis );
+
+      // set the p_resamp if it's the first cycle
+      if ( cycle == 0 )
+      {
+        p_resamp[basis] = 1.0;
+      }
+
+      // see if we're gonna update
+      double rval = ( double ) rand() / ( double ) RAND_MAX;
+
+      if ( ( w_old != 0 ) || ( rval < p_resamp[basis] ) )
+      {
+        // calc the probability
+        double XdotP = 0.0;
+        for ( int i = 0; i < fnum; i++ )
+        {
 #ifdef NORMALIZATION
-					double e = Xred[i].get(basis) * exp(Xw[i].get(0))/S[i];
+          double e = Xred[i].get ( basis ) * exp ( Xw[i].get ( 0 ) ) / S[i];
 #else
-					double e = X[i].get(basis) * exp(Xw[i].get(0))/S[i];
+          double e = X[i].get ( basis ) * exp ( Xw[i].get ( 0 ) ) / S[i];
 #endif
-					if(finite(e))
-						XdotP += e;
+          if ( finite ( e ) )
+            XdotP += e;
 #ifdef SLRDEBUG
-					else
-						throw "numerical problems";
+          else
+            throw "numerical problems";
 #endif
-				}
-					
-				// get the gradient
-				double grad = xY[basis].get(0) - XdotP;
-	  			// set the new weight
-				double w_new = w_old + grad/ac[basis];
-
-				// test that we're within bounds
-				if (w_new > lm_2_ac[basis])
-				{
-	    			// more towards bounds, but keep it
-					w_new -= lm_2_ac[basis];
-					changed = 1;
-
-	    			// umark from being zero if necessary
-					if (w_old == 0.0)
-					{
-						non_zero += 1;
-
-	      				// reset the p_resample
-						p_resamp[basis] = 1.0;
-
-	      				// we needed the basis
-						needed_basis += 1;
-					}
-				}
-				else if (w_new < -lm_2_ac[basis])
-				{
-	    			// more towards bounds, but keep it
-					w_new += lm_2_ac[basis];
-					changed = 1;
-
-	    			// umark from being zero if necessary
-					if (w_old == 0.0)
-					{
-						non_zero += 1;
-
-	      				// reset the p_resample
-						p_resamp[basis] = 1.0;
-
-	      				// we needed the basis
-						needed_basis += 1;
-					}
-				}
-				else
-				{
-	    			// gonna zero it out
-					w_new = 0.0;
-
-	    			// decrease the p_resamp
-					p_resamp[basis] -= (p_resamp[basis] - min_resamp) * resamp_decay;
-
-	    			// set the number of non-zero
-					if (w_old == 0.0)
-					{
-	     				// we didn't change
-						changed = 0;
-
-	      				// and wasted a basis
-						wasted_basis += 1;
-					}
-					else
-					{
-	      				// we changed
-						changed = 1;
-
-	      				// must update num non_zero
-						non_zero -= 1;
-					}
-				}
-	  			// process changes if necessary
-				if (changed == 1)
-				{
-	   				// update the expected values
-					double w_diff = w_new - w_old;
-					for (int i = 0; i < fnum; i++)
-					{
-						double E_old = exp(Xw[i].get(0));
-						double val = X[i].get(basis)*w_diff;
-						if(Xw[i].get(0) == 0.0)
-						{
-							if(fabs(val) > 10e-7)
-								Xw[i][0] = val;
-						}
-						else
-							Xw[i][0] += X[i].get(basis)*w_diff;
-						double E_new_m = exp(Xw[i].get(0));			
-						
-						S[i] += E_new_m - E_old;
-					}
-
-	    			// update the weight
-					if( w_new == 0.0)
-					{
-						if(weight.get(basis) != 0.0)
-						{
-							weight.erase(basis);
-						}
-					}
-					else
-						weight[basis] = w_new;
-	    			// keep track of the sqrt sum squared diffs
+        }
+
+        // get the gradient
+        double grad = xY[basis].get ( 0 ) - XdotP;
+        // set the new weight
+        double w_new = w_old + grad / ac[basis];
+
+        // test that we're within bounds
+        if ( w_new > lm_2_ac[basis] )
+        {
+          // more towards bounds, but keep it
+          w_new -= lm_2_ac[basis];
+          changed = 1;
+
+          // umark from being zero if necessary
+          if ( w_old == 0.0 )
+          {
+            non_zero += 1;
+
+            // reset the p_resample
+            p_resamp[basis] = 1.0;
+
+            // we needed the basis
+            needed_basis += 1;
+          }
+        }
+        else if ( w_new < -lm_2_ac[basis] )
+        {
+          // more towards bounds, but keep it
+          w_new += lm_2_ac[basis];
+          changed = 1;
+
+          // umark from being zero if necessary
+          if ( w_old == 0.0 )
+          {
+            non_zero += 1;
+
+            // reset the p_resample
+            p_resamp[basis] = 1.0;
+
+            // we needed the basis
+            needed_basis += 1;
+          }
+        }
+        else
+        {
+          // gonna zero it out
+          w_new = 0.0;
+
+          // decrease the p_resamp
+          p_resamp[basis] -= ( p_resamp[basis] - min_resamp ) * resamp_decay;
+
+          // set the number of non-zero
+          if ( w_old == 0.0 )
+          {
+            // we didn't change
+            changed = 0;
+
+            // and wasted a basis
+            wasted_basis += 1;
+          }
+          else
+          {
+            // we changed
+            changed = 1;
+
+            // must update num non_zero
+            non_zero -= 1;
+          }
+        }
+        // process changes if necessary
+        if ( changed == 1 )
+        {
+          // update the expected values
+          double w_diff = w_new - w_old;
+          for ( int i = 0; i < fnum; i++ )
+          {
+            double E_old = exp ( Xw[i].get ( 0 ) );
+            double val = X[i].get ( basis ) * w_diff;
+            if ( Xw[i].get ( 0 ) == 0.0 )
+            {
+              if ( fabs ( val ) > 10e-7 )
+                Xw[i][0] = val;
+            }
+            else
+              Xw[i][0] += X[i].get ( basis ) * w_diff;
+            double E_new_m = exp ( Xw[i].get ( 0 ) );
+
+            S[i] += E_new_m - E_old;
+          }
+
+          // update the weight
+          if ( w_new == 0.0 )
+          {
+            if ( weight.get ( basis ) != 0.0 )
+            {
+              weight.erase ( basis );
+            }
+          }
+          else
+            weight[basis] = w_new;
+          // keep track of the sqrt sum squared diffs
 //#pragma omp critical
-					sum2_w_diff += w_diff*w_diff;
-				}
-	  			// no matter what we keep track of the old
+          sum2_w_diff += w_diff * w_diff;
+        }
+        // no matter what we keep track of the old
 //#pragma omp critical
-				sum2_w_old += w_old*w_old;
-			}
-		}
+        sum2_w_old += w_old * w_old;
+      }
+    }
 
-    	// finished a cycle, assess convergence
-		incr = sqrt(sum2_w_diff) / (sqrt(sum2_w_old)+numeric_limits<double>::epsilon());
+    // finished a cycle, assess convergence
+    incr = sqrt ( sum2_w_diff ) / ( sqrt ( sum2_w_old ) + numeric_limits<double>::epsilon() );
 #ifdef SLRDEBUG
-		cout << "sum2_w_diff: " << sum2_w_diff << " sum2_w_old " << sum2_w_old << endl;
-		cout << "convcrit: " << incr << " tol: " << convergence_tol << endl;
-		//cout << "sum2_w_wold = " << sum2_w_old << " sum2_w_diff = " << sum2_w_diff << endl;
+    cout << "sum2_w_diff: " << sum2_w_diff << " sum2_w_old " << sum2_w_old << endl;
+    cout << "convcrit: " << incr << " tol: " << convergence_tol << endl;
+    //cout << "sum2_w_wold = " << sum2_w_old << " sum2_w_diff = " << sum2_w_diff << endl;
 #endif
-		if (incr < convergence_tol)
-		{
-      		// we converged!!!
-			break;
-		}
-	}
-
-  	// finished updating weights
-  	// assess convergence
-	cerr << "end regression after " << cycle << " steps"  << endl;
-	return cycle;
+    if ( incr < convergence_tol )
+    {
+      // we converged!!!
+      break;
+    }
+  }
+
+  // finished updating weights
+  // assess convergence
+  cerr << "end regression after " << cycle << " steps"  << endl;
+  return cycle;
 }

+ 93 - 93
classifier/fpclassifier/logisticregression/SLR.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file SLR.h
  * @brief implementation of Sparse Logistic Regression (SMLR) Classififier (one vs. all)
  * @author Björn Fröhlich
@@ -20,98 +20,98 @@ namespace OBJREC {
 
 class SLR : public NICE::Persistent
 {
-  //protected:
-	public:
-	//! the configuration file
-	const NICE::Config *conf;
-
-	//! section in the configfile
-	std::string confsection;
-	
-	//! weight vectors
-	SparseVector weight;
-	
-	//! the featurepool
-	FeaturePool fp;
-	
-	//! maximum number of iterations
-	int maxiter;
-	
-	//! Decay rate in the probability of resampling a zero weight.1.0 will immediately decrease to the min_resamp from 1.0, 0.0 will never decrease from 1.0.
-	double resamp_decay;
-	
-	//! convergence criterium for stepwise regression
-	double convergence_tol;
-	
-	//! Minimum resampling probability for zeroed weights"
-	double min_resamp;
-	
-	//! Feature Dimension
-	int fdim;
-	
-	//! The penalty term lambda. Larger values will give rise to	more sparsification
-	double lambda;
-	
-	//! how many samples per class should be used
-	double samplesperclass;
-	
-	//! for normalization
-	std::vector<double> minval, maxval;
-	
-    public:
-  
-	
-	/**
-	 * standard constructor
-	 * @param conf configfile
-	 * @param section section name in configfile for classifier
-	 */
-	SLR( const NICE::Config *conf, std::string section="SMLR");
-      
-	
-	/**
-	 * simple constructor -> does nothing
-	 */
-	SLR ();
-
-	/**
-	 * simple destructor
-	 */
-	~SLR();
-
-	/**
-	 * main classification function
-	 * @param pce input feature
-	 * @return a classification result
-	 */
-	double classify ( Example & pce );
-
-	/**
-	 * start training
-	 * @param fp a featurepool (how to handle which features...)
-	 * @param classno which class should be learned
-	 * @param examples input features
-	 */
-	void train ( FeaturePool & _fp, Examples & examples, int classno = 1 );
-
-	/**
-	 * clone this object
-	 * @return a copy of this object
-	 */
-	FeaturePoolClassifier *clone () const;
-
-	/**
-	 * perform the stepwise regression
-	 * @param x input features
-	 * @param classno which class should be learned
-	 * @return number of iterations
-	 */
-	int stepwise_regression(Examples &x, int classno = 1);
-	
-	/** IO functions */
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
+    //protected:
+  public:
+    //! the configuration file
+    const NICE::Config *conf;
+
+    //! section in the configfile
+    std::string confsection;
+
+    //! weight vectors
+    SparseVector weight;
+
+    //! the featurepool
+    FeaturePool fp;
+
+    //! maximum number of iterations
+    int maxiter;
+
+    //! Decay rate in the probability of resampling a zero weight.1.0 will immediately decrease to the min_resamp from 1.0, 0.0 will never decrease from 1.0.
+    double resamp_decay;
+
+    //! convergence criterium for stepwise regression
+    double convergence_tol;
+
+    //! Minimum resampling probability for zeroed weights"
+    double min_resamp;
+
+    //! Feature Dimension
+    int fdim;
+
+    //! The penalty term lambda. Larger values will give rise to more sparsification
+    double lambda;
+
+    //! how many samples per class should be used
+    double samplesperclass;
+
+    //! for normalization
+    std::vector<double> minval, maxval;
+
+  public:
+
+
+    /**
+     * standard constructor
+     * @param conf configfile
+     * @param section section name in configfile for classifier
+     */
+    SLR ( const NICE::Config *conf, std::string section = "SMLR" );
+
+
+    /**
+     * simple constructor -> does nothing
+     */
+    SLR ();
+
+    /**
+     * simple destructor
+     */
+    ~SLR();
+
+    /**
+     * main classification function
+     * @param pce input feature
+     * @return a classification result
+     */
+    double classify ( Example & pce );
+
+    /**
+     * start training
+     * @param fp a featurepool (how to handle which features...)
+     * @param classno which class should be learned
+     * @param examples input features
+     */
+    void train ( FeaturePool & _fp, Examples & examples, int classno = 1 );
+
+    /**
+     * clone this object
+     * @return a copy of this object
+     */
+    FeaturePoolClassifier *clone () const;
+
+    /**
+     * perform the stepwise regression
+     * @param x input features
+     * @param classno which class should be learned
+     * @return number of iterations
+     */
+    int stepwise_regression ( Examples &x, int classno = 1 );
+
+    /** IO functions */
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
 };
 
 } // namespace

+ 71 - 72
classifier/genericClassifierSelection.h

@@ -52,16 +52,15 @@ namespace OBJREC {
 
 class GenericClassifierSelection
 {
-    public:
+  public:
 
-		static VecClassifier *selectVecClassifier ( const NICE::Config *conf, std::string classifier_type )
-		{
-			 std::vector<std::string> submatches;
-			 VecClassifier *classifier = NULL;
-
-			 if ( classifier_type == "amit" ) {
-				  classifier = new VCAmitSVM ( conf );
+    static VecClassifier *selectVecClassifier ( const NICE::Config *conf, std::string classifier_type )
+    {
+      std::vector<std::string> submatches;
+      VecClassifier *classifier = NULL;
 
+      if ( classifier_type == "amit" ) {
+        classifier = new VCAmitSVM ( conf );
 			 } else if ( classifier_type == "nn" ) {
 				  classifier = new VCNearestNeighbour( conf, new NICE::EuclidianDistance<double>() );
 #ifdef NICE_USELIB_ICE 
@@ -71,76 +70,76 @@ class GenericClassifierSelection
                          } else if ( classifier_type == "nearest_classmean2" ) {
                                   classifier = new VCNearestClassMean( conf, new NICE::EuclidianDistance<double>() );
 #endif
-			 } else if ( classifier_type == "random_forest" ) {
-				  FeaturePoolClassifier *fpc = new FPCRandomForests ( conf, "RandomForest" );
-				  classifier = new VCFeaturePool ( conf, fpc );
-				
-			 } else if ( classifier_type == "sparse_logistic_regression" ) {
-				 FeaturePoolClassifier *fpc = new FPCSMLR ( conf, "SparseLogisticRegression" );
-				 classifier = new VCFeaturePool ( conf, fpc );
-				  
-			 } else if ( classifier_type == "boost" ) {
-				  FeaturePoolClassifier *fpc = new FPCBoosting ( conf, "Boost" );
-				  classifier = new VCFeaturePool ( conf, fpc );
-			 
-				 } else if ( classifier_type == "decision_tree" ) {
-				  FeaturePoolClassifier *fpc = new FPCDecisionTree ( conf, "DecisionTree" );
-				  classifier = new VCFeaturePool ( conf, fpc );
+      } else if ( classifier_type == "random_forest" ) {
+        FeaturePoolClassifier *fpc = new FPCRandomForests ( conf, "RandomForest" );
+        classifier = new VCFeaturePool ( conf, fpc );
+
+      } else if ( classifier_type == "sparse_logistic_regression" ) {
+        FeaturePoolClassifier *fpc = new FPCSMLR ( conf, "SparseLogisticRegression" );
+        classifier = new VCFeaturePool ( conf, fpc );
+
+      } else if ( classifier_type == "boost" ) {
+        FeaturePoolClassifier *fpc = new FPCBoosting ( conf, "Boost" );
+        classifier = new VCFeaturePool ( conf, fpc );
+
+      } else if ( classifier_type == "decision_tree" ) {
+        FeaturePoolClassifier *fpc = new FPCDecisionTree ( conf, "DecisionTree" );
+        classifier = new VCFeaturePool ( conf, fpc );
 #ifdef NICE_USELIB_ICE
-			 } else if ( (classifier_type == "cross_generalization") || (classifier_type == "bart") ) {
-				  classifier = new VCCrossGeneralization ( conf );
+      } else if ( ( classifier_type == "cross_generalization" ) || ( classifier_type == "bart" ) ) {
+        classifier = new VCCrossGeneralization ( conf );
 #endif
 #ifdef NICE_USELIB_SVMLIGHT
-			 } else if ( (classifier_type == "svmlight") || (classifier_type == "svm") ) {
-				  classifier = new VCSVMLight ( conf );
-			 } else if ( (classifier_type == "svm_onevsone") ) {
-				  classifier = new VCOneVsOne ( conf, new VCSVMLight(conf) );
-			 } else if ( (classifier_type == "svm_onevsall") ) {
-				  classifier = new VCOneVsAll ( conf, new VCSVMLight(conf) );
-			 } else if ( (classifier_type == "svmlight_kernel")) {
-				  classifier = new KCSVMLight ( conf, new KernelStd() );
-			 } else if ( (classifier_type == "svm_one_class")) {
-				  classifier = new VCSVMOneClass( conf, "VCSVMLight" );
+      } else if ( ( classifier_type == "svmlight" ) || ( classifier_type == "svm" ) ) {
+        classifier = new VCSVMLight ( conf );
+      } else if ( ( classifier_type == "svm_onevsone" ) ) {
+        classifier = new VCOneVsOne ( conf, new VCSVMLight ( conf ) );
+      } else if ( ( classifier_type == "svm_onevsall" ) ) {
+        classifier = new VCOneVsAll ( conf, new VCSVMLight ( conf ) );
+      } else if ( ( classifier_type == "svmlight_kernel" ) ) {
+        classifier = new KCSVMLight ( conf, new KernelStd() );
+      } else if ( ( classifier_type == "svm_one_class" ) ) {
+        classifier = new VCSVMOneClass ( conf, "VCSVMLight" );
 #endif
 #ifdef NICE_USELIB_NICEDTSVM
-			 // this classifier requires nice-dtsvm, which is an optional
-			 // nice sub-library
-			 } else if ( classifier_type == "treebased" ) {
-				 classifier = new VCTreeBasedClassifier ( conf );
+        // this classifier requires nice-dtsvm, which is an optional
+        // nice sub-library
+      } else if ( classifier_type == "treebased" ) {
+        classifier = new VCTreeBasedClassifier ( conf );
 #endif
-			 } else if ( (classifier_type == "dtgp") ) {
-				  classifier = new VCDTSVM ( conf );
-			 } else if ( (classifier_type == "minimum_enclosing_ball")) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCMinimumEnclosingBall ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( (classifier_type == "gp_one_class")) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCGPOneClass ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( (classifier_type == "gp_regression_rbf")) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCGPRegression ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( (classifier_type == "gp_laplace_rbf")) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCGPLaplace ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( (classifier_type == "gp_regression_rbf_onevsall" ) ) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCGPRegOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( (classifier_type == "gp_laplace_rbf_onevsall" ) ) {
-				  string kernel_type = conf->gS("Kernel", "kernel_function", "rbf" );
-				  classifier = new KCGPLaplaceOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-			 } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_one\\(([^\\)]+)\\)$", submatches ) && (submatches.size() == 2)) {
-				  classifier = new VCOneVsOne ( conf, selectVecClassifier( conf, submatches[1] ) );
-			 } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_all\\(([^\\)]+)\\)$", submatches ) && (submatches.size() == 2)) {
-				  classifier = new VCOneVsAll ( conf, selectVecClassifier( conf, submatches[1] ) );
-			 } else if ( StringTools::regexMatch ( classifier_type, "^random_forest\\(([^\\)]+)\\)$", submatches ) && (submatches.size() == 2)) {
-				  classifier = new VCPreRandomForest ( conf, "VCPreRandomForest", selectVecClassifier(conf, submatches[1] ) );
-			 } else {
-				  fthrow ( Exception, "Classifier type " << classifier_type << " not (yet) supported." << endl <<
-				  			"(genericClassifierSelection.h contains a list of classifiers to choose from)");
-			 }
-
-			 return classifier;
-		}
+      } else if ( ( classifier_type == "dtgp" ) ) {
+        classifier = new VCDTSVM ( conf );
+      } else if ( ( classifier_type == "minimum_enclosing_ball" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCMinimumEnclosingBall ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( ( classifier_type == "gp_one_class" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCGPOneClass ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( ( classifier_type == "gp_regression_rbf" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCGPRegression ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( ( classifier_type == "gp_laplace_rbf" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCGPLaplace ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( ( classifier_type == "gp_regression_rbf_onevsall" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCGPRegOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( ( classifier_type == "gp_laplace_rbf_onevsall" ) ) {
+        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        classifier = new KCGPLaplaceOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
+      } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_one\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+        classifier = new VCOneVsOne ( conf, selectVecClassifier ( conf, submatches[1] ) );
+      } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_all\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+        classifier = new VCOneVsAll ( conf, selectVecClassifier ( conf, submatches[1] ) );
+      } else if ( StringTools::regexMatch ( classifier_type, "^random_forest\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+        classifier = new VCPreRandomForest ( conf, "VCPreRandomForest", selectVecClassifier ( conf, submatches[1] ) );
+      } else {
+        fthrow ( Exception, "Classifier type " << classifier_type << " not (yet) supported." << endl <<
+                 "(genericClassifierSelection.h contains a list of classifiers to choose from)" );
+      }
+
+      return classifier;
+    }
 
 };
 

+ 0 - 1
classifier/kernelclassifier/progs/laplaceTests.cpp

@@ -75,7 +75,6 @@ int main (int argc, char **argv)
 
 	ColorImage img;
 	ICETools::convertToRGB ( predictions, img );
-	uint k = 0;
 	LOOP_ALL(train)
 	{
 		EACH(classno,vec);

+ 0 - 1
classifier/progs/toyExampleUnsupervisedGP.cpp

@@ -90,7 +90,6 @@ int main (int argc, char **argv)
  
     int xsize = conf.gI("main", "xsize", 300 );
     int ysize = conf.gI("main", "ysize", 300 );
-    int numClasses = 3;
     
     NICE::Image img (xsize, ysize);
     img.set(255);

+ 157 - 157
classifier/vclassifier/VCDTSVM.cpp

@@ -4,85 +4,85 @@
 
 #include "core/basics/StringTools.h"
 
-#define WRITE
+#undef WRITE
 
 using namespace OBJREC;
 
 using namespace std;
 using namespace NICE;
 
-VCDTSVM::VCDTSVM ( const Config *_conf, const string & section ) 
+VCDTSVM::VCDTSVM ( const Config *_conf, const string & section )
     : VecClassifier ( _conf )
 {
-    binary = _conf->gS(section, "binary", "./tdsvm");
-    configtrain = _conf->gS(section, "configtrain", "configtrain.txt");
-    configtest = _conf->gS(section, "configtest", "configtest.txt");
-    trainfile  = _conf->gS(section, "traindst", "train.txt");
-    testfile  = _conf->gS(section, "testdst", "test.txt");
+  binary = _conf->gS ( section, "binary", "./tdsvm" );
+  configtrain = _conf->gS ( section, "configtrain", "configtrain.txt" );
+  configtest = _conf->gS ( section, "configtest", "configtest.txt" );
+  trainfile  = _conf->gS ( section, "traindst", "train.txt" );
+  testfile  = _conf->gS ( section, "testdst", "test.txt" );
 
 #ifndef WRITE
-    counter = new vector<int>(1,0);
-    if(results.size() == 0)
+  counter = new vector<int> ( 1, 0 );
+  if ( results.size() == 0 )
+  {
+
+    ifstream fin ( "results.txt" );
+
+
+    const int bufsize = 1024 * 1024;
+    char *buf = new char[bufsize];
+    std::string buf_s;
+    while ( !fin.eof() )
     {
+      int bc;
+      vector<string> elements;
+      fin >> bc;
+      fin.get ( buf, bufsize );
+      buf_s = buf;
+
+      if ( buf_s.size() <= 0 )
+        break;
+
+      StringTools::split ( buf_s, ' ', elements );
 
-	    ifstream fin("results.txt");
-		
-
-	    const int bufsize = 1024*1024;
-	    char *buf = new char[bufsize];
-	    std::string buf_s;	
-	    while(!fin.eof())
-	    {
-		    int bc;
-		    vector<string> elements;
-		    fin >> bc;
-		    fin.get ( buf, bufsize );
-		    buf_s = buf;
-	
-		    if ( buf_s.size() <= 0 ) 
-			    break;
-	
-		    StringTools::split ( buf_s, ' ', elements );
-	
-		    if ( elements.size() <= 1 )
-			    break;
-	
-		    vector<double> tmp;
-	
-		    size_t l = 0;
-			
-			// skip first element because of white space
-		    for ( vector<string>::const_iterator i  = elements.begin()+1; i != elements.end(); i++, l++ )
-		    {
-			    double val = atof ( i->c_str() );
-			    tmp.push_back(val);
-		    }
-		    results.push_back(tmp);
-		    labels.push_back(bc);
-	    }
-
-	    fin.close();
-
-	    (*counter)[0] = 0;
-	    //counter = 0;
+      if ( elements.size() <= 1 )
+        break;
+
+      vector<double> tmp;
+
+      size_t l = 0;
+
+      // skip first element because of white space
+      for ( vector<string>::const_iterator i  = elements.begin() + 1; i != elements.end(); i++, l++ )
+      {
+        double val = atof ( i->c_str() );
+        tmp.push_back ( val );
+      }
+      results.push_back ( tmp );
+      labels.push_back ( bc );
     }
+
+    fin.close();
+
+    ( *counter ) [0] = 0;
+    //counter = 0;
+  }
 #endif
 }
 
-VCDTSVM::VCDTSVM ( const VCDTSVM & classifier ) : VecClassifier() 
+VCDTSVM::VCDTSVM ( const VCDTSVM & classifier ) : VecClassifier()
 {
-	binary = classifier.binary;
-	configtrain = classifier.configtrain;
-	configtest = classifier.configtest;
-	trainfile = classifier.trainfile;
-	testfile = classifier.testfile;
+  binary = classifier.binary;
+  configtrain = classifier.configtrain;
+  configtest = classifier.configtest;
+  trainfile = classifier.trainfile;
+  testfile = classifier.testfile;
 }
 
 
 VCDTSVM::~VCDTSVM()
 {
-	int c2 = (*counter)[0];
-	cout << "c2: " << c2 << " matsize " << results.size() << endl;
+  int c2 = ( *counter ) [0];
+  cout << "c2: " << c2 << " matsize " << results.size() << endl;
 }
 
 ClassificationResult VCDTSVM::classify ( const NICE::Vector & x ) const
@@ -90,105 +90,105 @@ ClassificationResult VCDTSVM::classify ( const NICE::Vector & x ) const
 
 
 #ifdef WRITE
-	ofstream fout( testfile.c_str(), ios::app );
-	fout << 0 << " ";
-	int i;
-	for(i = 0; i < x.size()-1; i++)
-	{
-		fout << i+1 << ":" << x[i] << " ";
-	}
-	i++;
-	fout << i+1 << ":" << x[i] << endl;
-	fout.close();
-	
-	
-	FullVector scores(10);
-
-	//scores.read("scores");
-	double bval = scores[0];
-
-	int bclass = 0;
-	for(i = 1; i < scores.size(); i++)
-	{
-		if(bval < scores[i])
-		{
-			bval = scores[i];
-			bclass = i;
-		}
-	}
-	return ClassificationResult (bclass, scores);
+  ofstream fout ( testfile.c_str(), ios::app );
+  fout << 0 << " ";
+  int i;
+  for ( i = 0; i < x.size() - 1; i++ )
+  {
+    fout << i + 1 << ":" << x[i] << " ";
+  }
+  i++;
+  fout << i + 1 << ":" << x[i] << endl;
+  fout.close();
+
+
+  FullVector scores ( 10 );
+
+  //scores.read("scores");
+  double bval = scores[0];
+
+  int bclass = 0;
+  for ( i = 1; i < scores.size(); i++ )
+  {
+    if ( bval < scores[i] )
+    {
+      bval = scores[i];
+      bclass = i;
+    }
+  }
+  return ClassificationResult ( bclass, scores );
 #endif
-	
+
 #ifndef WRITE
-	int c2 = (*counter)[0];
-	(*counter)[0]++;
-	FullVector tmp(results[c2].size());
-	for(int i = 0; i < results[c2].size(); i++)
-	{
-		tmp[i] = results[c2][i];
-	}
-	return ClassificationResult (labels[c2], tmp);	
+  int c2 = ( *counter ) [0];
+  ( *counter ) [0]++;
+  FullVector tmp ( results[c2].size() );
+  for ( int i = 0; i < results[c2].size(); i++ )
+  {
+    tmp[i] = results[c2][i];
+  }
+  return ClassificationResult ( labels[c2], tmp );
 #endif
 
-#if 0	
-	const int buffersize = 65536;
-	char *buffer = new char [buffersize];
-	
-	string call = binary +" "+configtest;
-	
-	FILE *f = popen ( call.c_str(), "r" );
-	
-	if ( f == NULL )
-	{
-		fprintf (stderr, "VCDTSVM::classify: FATAL ERROR, unable to run the implementation of DTSVM\n");
-		exit(-1);
-	}
-	
-	while ( ! feof(f) ) 
-	{
-		if ( fgets ( buffer, buffersize, f ) <= 0 )
-		{
-			break;
-		} else 
-		{
-			//fprintf (stderr, "VCDTSVM::classify: [INFO] %s", buffer );
-		}
-	}
-	pclose(f);
+#if 0
+  const int buffersize = 65536;
+  char *buffer = new char [buffersize];
+
+  string call = binary + " " + configtest;
+
+  FILE *f = popen ( call.c_str(), "r" );
+
+  if ( f == NULL )
+  {
+    fprintf ( stderr, "VCDTSVM::classify: FATAL ERROR, unable to run the implementation of DTSVM\n" );
+    exit ( -1 );
+  }
+
+  while ( ! feof ( f ) )
+  {
+    if ( fgets ( buffer, buffersize, f ) <= 0 )
+    {
+      break;
+    } else
+    {
+      //fprintf (stderr, "VCDTSVM::classify: [INFO] %s", buffer );
+    }
+  }
+  pclose ( f );
 #endif
 }
 
 void VCDTSVM::teach ( const LabeledSetVector & _teachSet )
 {
-    	maxClassNo = _teachSet.getMaxClassno();
-    	//TODO: LabeledSet rausschreiben und classifier anwerfen
+  maxClassNo = _teachSet.getMaxClassno();
+  //TODO: LabeledSet rausschreiben und classifier anwerfen
 #ifdef WRITE
-    	_teachSet.write(trainfile, LabeledSetVector::FILEFORMAT_INDEX);
-    /*
-    	string call = binary +" "+configtrain;
-    
-    	const int buffersize = 65536;
-	char *buffer = new char [buffersize];
-	
-	FILE *f = popen ( call.c_str(), "r" );
-	
-	if ( f == NULL )
-	{
-		fprintf (stderr, "VCDTSVM::teach: FATAL ERROR, unable to run the implementation of DTSVM\n");
-		exit(-1);
-	}
-	
-	while ( ! feof(f) ) 
-	{
-		if ( fgets ( buffer, buffersize, f ) <= 0 )
-		{
-			break;
-		} else 
-		{
-			fprintf (stderr, "VCDTSVM::teach: [INFO] %s", buffer );
-		}
-	}
-	pclose(f);*/
+  _teachSet.write ( trainfile, LabeledSetVector::FILEFORMAT_INDEX );
+  /*
+   string call = binary +" "+configtrain;
+
+   const int buffersize = 65536;
+  char *buffer = new char [buffersize];
+
+  FILE *f = popen ( call.c_str(), "r" );
+
+  if ( f == NULL )
+  {
+  fprintf (stderr, "VCDTSVM::teach: FATAL ERROR, unable to run the implementation of DTSVM\n");
+  exit(-1);
+  }
+
+  while ( ! feof(f) )
+  {
+  if ( fgets ( buffer, buffersize, f ) <= 0 )
+  {
+  break;
+  } else
+  {
+  fprintf (stderr, "VCDTSVM::teach: [INFO] %s", buffer );
+  }
+  }
+  pclose(f);*/
 #endif
 }
 
@@ -197,35 +197,35 @@ void VCDTSVM::finishTeaching()
 }
 
 /** clone this object */
-VCDTSVM *VCDTSVM::clone(void) const
+VCDTSVM *VCDTSVM::clone ( void ) const
 {
-	VCDTSVM *classifier = new VCDTSVM( *this );
-	return classifier;
+  VCDTSVM *classifier = new VCDTSVM ( *this );
+  return classifier;
 }
 
 void VCDTSVM::clear ()
 {
-    //TODO wieder freigeben
+  //TODO wieder freigeben
 }
 
-void VCDTSVM::read (const string& s, int format)
+void VCDTSVM::read ( const string& s, int format )
 {
-    //TODO: Zielverzeichnis eventuell
+  //TODO: Zielverzeichnis eventuell
 }
 
-void VCDTSVM::save (const string& s, int format) const
+void VCDTSVM::save ( const string& s, int format ) const
 {
-    //TODO: Zielverzeichnis eventuell
+  //TODO: Zielverzeichnis eventuell
 }
 
 
 void VCDTSVM::store ( std::ostream & os, int format ) const
 {
-    fprintf (stderr, "VCDTSVM: unable to write to stream! please use read()\n");
+  fprintf ( stderr, "VCDTSVM: unable to write to stream! please use read()\n" );
 }
 
 void VCDTSVM::restore ( std::istream & is, int format )
 {
-    fprintf (stderr, "VCDTSVM: unable to read from stream! please use save()\n");
-    exit (-1);
+  fprintf ( stderr, "VCDTSVM: unable to read from stream! please use save()\n" );
+  exit ( -1 );
 }

+ 50 - 50
classifier/vclassifier/VCDTSVM.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file VCDTSVM.h
 * @brief Interface to DTSVM
 * @author Björn Fröhlich
@@ -20,55 +20,55 @@ namespace OBJREC {
 class VCDTSVM : public VecClassifier
 {
 
-	protected:
-		NICE::Vector max;
-		NICE::Vector min;
-
-		int normalization_type;
-		
-		/** where to find the binary file */
-		std::string binary;
-		
-		/** where to find the DT-SVM config files */
-		std::string configtrain;
-		std::string configtest;
-		std::string trainfile;
-		std::string testfile;
-		
-	private:
-		std::vector<std::vector<double> > results;
-		std::vector<int> *counter;
-		//int counter;
-		std::vector<int> labels;		
-
-	public:
-		/** using a config file to read some settings */
-		VCDTSVM( const NICE::Config *conf, const std::string & section = "VCDTSVM" );
-
-		/** simple copy constructor */
-		VCDTSVM ( const VCDTSVM & src );
-	  
-		/** simple destructor */
-		virtual ~VCDTSVM();
-		 
-		/** classify using simple vector */
-		ClassificationResult classify ( const NICE::Vector & x ) const;
-
-		/** classify using a simple vector */
-		void teach ( const LabeledSetVector & teachSet );
-		
-		void finishTeaching();
-
-		/** clone this object */
-		virtual VCDTSVM *clone(void) const;
-
-		void clear ();
-
-		void read (const std::string& s, int format = 0);
-		void save (const std::string& s, int format = 0) const;
-
-		void store ( std::ostream & os, int format = 0 ) const;
-		void restore ( std::istream & is, int format = 0 );
+  protected:
+    NICE::Vector max;
+    NICE::Vector min;
+
+    int normalization_type;
+
+    /** where to find the binary file */
+    std::string binary;
+
+    /** where to find the DT-SVM config files */
+    std::string configtrain;
+    std::string configtest;
+    std::string trainfile;
+    std::string testfile;
+
+  private:
+    std::vector<std::vector<double> > results;
+    std::vector<int> *counter;
+    //int counter;
+    std::vector<int> labels;
+
+  public:
+    /** using a config file to read some settings */
+    VCDTSVM ( const NICE::Config *conf, const std::string & section = "VCDTSVM" );
+
+    /** simple copy constructor */
+    VCDTSVM ( const VCDTSVM & src );
+
+    /** simple destructor */
+    virtual ~VCDTSVM();
+
+    /** classify using simple vector */
+    ClassificationResult classify ( const NICE::Vector & x ) const;
+
+    /** classify using a simple vector */
+    void teach ( const LabeledSetVector & teachSet );
+
+    void finishTeaching();
+
+    /** clone this object */
+    virtual VCDTSVM *clone ( void ) const;
+
+    void clear ();
+
+    void read ( const std::string& s, int format = 0 );
+    void save ( const std::string& s, int format = 0 ) const;
+
+    void store ( std::ostream & os, int format = 0 ) const;
+    void restore ( std::istream & is, int format = 0 );
 };
 
 

+ 171 - 174
features/fpfeatures/HaarFeature.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file HaarFeature.cpp
 * @brief simple haar like feature
 * @author Erik Rodner
@@ -12,212 +12,209 @@
 #include "vislearning/cbaselib/FeaturePool.h"
 
 using namespace OBJREC;
-
 using namespace std;
-// refactor-nice.pl: check this substitution
-// old: using namespace ice;
 using namespace NICE;
 
 
 void HaarFeature::explode ( FeaturePool & featurePool, bool variableWindow ) const
 {
-    HaarFeature *hf = new HaarFeature ( *this );
-
-    hf->pos1 = 0;
-    hf->pos2 = 0;
-    hf->type = HAARTYPE_HORIZONTAL;  
-    for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_y - 1 ; hf->pos1 += hf->step_y )
-	featurePool.addFeature ( hf->clone(), hf->step_y / (double)( HAARTYPE_NUMTYPES * hf->window_size_y ) );
-
-    hf->pos1 = 0;
-    hf->pos2 = 0;
-    hf->type = HAARTYPE_VERTICAL;
-    for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 1; hf->pos1 += hf->step_x )
-	featurePool.addFeature ( hf->clone(), hf->step_x / (double)( HAARTYPE_NUMTYPES * hf->window_size_x ) );
-
-    hf->type = HAARTYPE_DIAGONAL;
-    hf->pos1 = 0;
-    hf->pos2 = 0;
-    for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 1; hf->pos1 += hf->step_x )
-	for ( hf->pos2 = 0 ; hf->pos2 < hf->window_size_y - 1 ; hf->pos2 += hf->step_y )
-	    featurePool.addFeature ( hf->clone(), 
-		hf->step_x * hf->step_y / (double)( HAARTYPE_NUMTYPES * hf->window_size_x * hf->window_size_y ) );
-
-    hf->pos1 = 0;
-    hf->pos2 = 0;
-    hf->type = HAARTYPE_3BLOCKS;
-    for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 2*hf->step_x ; hf->pos1 += hf->step_x )
-	for ( hf->pos2 = hf->pos1 + hf->step_x; hf->pos2 < hf->window_size_x - hf->step_x ; hf->pos2 += hf->step_x )
-	    featurePool.addFeature ( hf->clone(), 
-		(2.0 * hf->step_x) / ( HAARTYPE_NUMTYPES * (hf->window_size_x - hf->step_x) ) 	);
-
-    delete hf;
+  HaarFeature *hf = new HaarFeature ( *this );
+
+  hf->pos1 = 0;
+  hf->pos2 = 0;
+  hf->type = HAARTYPE_HORIZONTAL;
+  for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_y - 1 ; hf->pos1 += hf->step_y )
+    featurePool.addFeature ( hf->clone(), hf->step_y / ( double ) ( HAARTYPE_NUMTYPES * hf->window_size_y ) );
+
+  hf->pos1 = 0;
+  hf->pos2 = 0;
+  hf->type = HAARTYPE_VERTICAL;
+  for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 1; hf->pos1 += hf->step_x )
+    featurePool.addFeature ( hf->clone(), hf->step_x / ( double ) ( HAARTYPE_NUMTYPES * hf->window_size_x ) );
+
+  hf->type = HAARTYPE_DIAGONAL;
+  hf->pos1 = 0;
+  hf->pos2 = 0;
+  for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 1; hf->pos1 += hf->step_x )
+    for ( hf->pos2 = 0 ; hf->pos2 < hf->window_size_y - 1 ; hf->pos2 += hf->step_y )
+      featurePool.addFeature ( hf->clone(),
+                               hf->step_x * hf->step_y / ( double ) ( HAARTYPE_NUMTYPES * hf->window_size_x * hf->window_size_y ) );
+
+  hf->pos1 = 0;
+  hf->pos2 = 0;
+  hf->type = HAARTYPE_3BLOCKS;
+  for ( hf->pos1 = 0 ; hf->pos1 < hf->window_size_x - 2*hf->step_x ; hf->pos1 += hf->step_x )
+    for ( hf->pos2 = hf->pos1 + hf->step_x; hf->pos2 < hf->window_size_x - hf->step_x ; hf->pos2 += hf->step_x )
+      featurePool.addFeature ( hf->clone(),
+                               ( 2.0 * hf->step_x ) / ( HAARTYPE_NUMTYPES * ( hf->window_size_x - hf->step_x ) ) );
+
+  delete hf;
 }
 
 Feature *HaarFeature::clone() const
 {
-    HaarFeature *fp =  new HaarFeature(*this);
-    return fp;
+  HaarFeature *fp =  new HaarFeature ( *this );
+  return fp;
 }
 
 
 /************* HaarFeature **************/
-HaarFeature::HaarFeature( const Config *conf )
+HaarFeature::HaarFeature ( const Config *conf )
 {
-    window_size_x = conf->gI("HaarFeature", "window_size_x", 24 );
-    window_size_y = conf->gI("HaarFeature", "window_size_y", 24 );
-    step_x = conf->gI("HaarFeature", "step_x", 1 );
-    step_y = conf->gI("HaarFeature", "step_y", 1 );
+  window_size_x = conf->gI ( "HaarFeature", "window_size_x", 24 );
+  window_size_y = conf->gI ( "HaarFeature", "window_size_y", 24 );
+  step_x = conf->gI ( "HaarFeature", "step_x", 1 );
+  step_y = conf->gI ( "HaarFeature", "step_y", 1 );
 }
 
-HaarFeature::HaarFeature ( int _window_size_x,	
-			   int _window_size_y,
-			   int _step_x,
-			   int _step_y )
+HaarFeature::HaarFeature ( int _window_size_x,
+                           int _window_size_y,
+                           int _step_x,
+                           int _step_y )
 {
-    window_size_x = _window_size_x;
-    window_size_y = _window_size_y;
-    pos1 = 1;
-    pos2 = 0;
-    step_x = _step_x;
-    step_y = _step_y;
-    type = HaarFeature::HAARTYPE_HORIZONTAL;
+  window_size_x = _window_size_x;
+  window_size_y = _window_size_y;
+  pos1 = 1;
+  pos2 = 0;
+  step_x = _step_x;
+  step_y = _step_y;
+  type = HaarFeature::HAARTYPE_HORIZONTAL;
 }
 
 HaarFeature::~HaarFeature()
 {
 }
 
-double HaarFeature::val( const Example *example ) const
+double HaarFeature::val ( const Example *example ) const
 {
-    const NICE::MultiChannelImageT<long> & img = example->ce->getLChannel ( CachedExample::L_INTEGRALIMAGE ); 
-
-    const long *integralImage = img.data[0];
-    int xsize = img.xsize;
-    int ysize = img.ysize;
-
-    int x = example->x;
-    int y = example->y;
-    long tl, tr, bl, br;
-
-    int exwidth = example->width;
-    if ( exwidth != 0 ) 
-    {
-	int exheight = example->height;
-	tl = (x - exwidth/2) + (y - exheight/2)*xsize;
-	tr = tl + exwidth - 1;
-	bl = tl + (exheight - 1)*xsize;
-	br = bl + exwidth - 1;
-    } else {
-	tl = (x - window_size_x/2) + (y - window_size_y/2)*xsize;
-	tr = tl + window_size_x - 1;
-	bl = tl + (window_size_y - 1)*xsize;
-	br = bl + (window_size_x - 1);
-    }
-
-    assert ( tl < xsize*ysize );
-    assert ( tr < xsize*ysize );
-    if ( br >= xsize*ysize ) 
-    {
-	fprintf (stderr, "xsize=%d, ysize=%d, x=%d, y=%d, wsy=%d, wsx=%d\n",
-		xsize, ysize, x, y, window_size_x, window_size_y );
-	fprintf (stderr, "example: %d x %d\n",
-		example->width, example->height );
-
-    }
-    assert ( bl < xsize*ysize );
-    assert ( br < xsize*ysize );
-    assert ( pos1 >= 0 );
-    assert ( pos2 >= 0 );
-
-    double value;
-    if ( type == HaarFeature::HAARTYPE_HORIZONTAL )
-    {
-	long ml = tl + xsize*pos1;
-	long mr = tr + xsize*pos1;
-	assert ( (ml >= 0) && (ml < xsize*ysize) );
-	assert ( (mr >= 0) && (mr < xsize*ysize) );
-	value = 2*integralImage[mr];
-	value -= 2*integralImage[ml];
-	value +=   integralImage[tl];
-	value +=   integralImage[tr];
-	value -=   integralImage[bl];
-	value -=   integralImage[br];
-    } else if ( type == HaarFeature::HAARTYPE_VERTICAL ) {
-	long mt = tl + pos1;
-	long mb = bl + pos1;
-	assert ( (mt >= 0) && (mt < xsize*ysize) );
-	assert ( (mb >= 0) && (mb < xsize*ysize) );
-
-	value = 2*integralImage[mb];
-	value -= 2*integralImage[mt];
-	value +=   integralImage[tl];
-	value +=   integralImage[tr];
-	value -=   integralImage[bl];
-	value -=   integralImage[br];
-    } else if ( type == HaarFeature::HAARTYPE_DIAGONAL ) {
-	int p2o = pos2*xsize;
-	assert ( (p2o >= 0) && (p2o < xsize*ysize) );
-	assert ( (tl+pos1 >= 0) && (tl+pos1 < xsize*ysize) );
-	assert ( (tl+p2o >= 0) && (tl+p2o < xsize*ysize) );
-	assert ( (bl+pos1 >= 0) && (bl+pos1 < xsize*ysize) );
-	assert ( (tr+p2o >= 0) && (tr+p2o < xsize*ysize) );
-	assert ( (tl+pos1+p2o >= 0) && (tl+pos1+p2o < xsize*ysize) );
-
-	value = integralImage[tl];
-	value += integralImage[bl];
-	value += integralImage[br];
-	value += integralImage[tr];
-	value -= 2 * ( 
-		  integralImage[tl+pos1]
-		+ integralImage[tl+p2o]
-		+ integralImage[bl+pos1]
-		+ integralImage[tr+p2o]
-	     );
-	value += 4 * integralImage[tl + pos1 + p2o];
-
-    } else if ( type == HaarFeature::HAARTYPE_3BLOCKS ) {
-	assert ( (tl+pos1 >= 0) && (tl+pos1 < xsize*ysize) );
-	assert ( (bl+pos2 >= 0) && (bl+pos2 < xsize*ysize) );
-	assert ( (tl+pos2 >= 0) && (tl+pos2 < xsize*ysize) );
-	assert ( (bl+pos1 >= 0) && (bl+pos1 < xsize*ysize) );
-	value = integralImage[tl];
-	value +=  integralImage[br];
-	value -=  integralImage[bl];
-	value -=  integralImage[tr];
-	value += 2 * (
-		- integralImage[tl+pos1]
-		- integralImage[bl+pos2]
-		+ integralImage[tl+pos2]
-		+ integralImage[bl+pos1]
-	    );
-    } else {
-	return -1;
-    }
-
-    assert ( finite(value) );
-
-    return value;
+  const NICE::MultiChannelImageT<long> & img = example->ce->getLChannel ( CachedExample::L_INTEGRALIMAGE );
+
+  const long *integralImage = img.data[0];
+  int xsize = img.xsize;
+  int ysize = img.ysize;
+
+  int x = example->x;
+  int y = example->y;
+  long tl, tr, bl, br;
+
+  int exwidth = example->width;
+  if ( exwidth != 0 )
+  {
+    int exheight = example->height;
+    tl = ( x - exwidth / 2 ) + ( y - exheight / 2 ) * xsize;
+    tr = tl + exwidth - 1;
+    bl = tl + ( exheight - 1 ) * xsize;
+    br = bl + exwidth - 1;
+  } else {
+    tl = ( x - window_size_x / 2 ) + ( y - window_size_y / 2 ) * xsize;
+    tr = tl + window_size_x - 1;
+    bl = tl + ( window_size_y - 1 ) * xsize;
+    br = bl + ( window_size_x - 1 );
+  }
+
+  assert ( tl < xsize*ysize );
+  assert ( tr < xsize*ysize );
+  if ( br >= xsize*ysize )
+  {
+    fprintf ( stderr, "xsize=%d, ysize=%d, x=%d, y=%d, wsy=%d, wsx=%d\n",
+              xsize, ysize, x, y, window_size_x, window_size_y );
+    fprintf ( stderr, "example: %d x %d\n",
+              example->width, example->height );
+
+  }
+  assert ( bl < xsize*ysize );
+  assert ( br < xsize*ysize );
+  assert ( pos1 >= 0 );
+  assert ( pos2 >= 0 );
+
+  double value;
+  if ( type == HaarFeature::HAARTYPE_HORIZONTAL )
+  {
+    long ml = tl + xsize * pos1;
+    long mr = tr + xsize * pos1;
+    assert ( ( ml >= 0 ) && ( ml < xsize*ysize ) );
+    assert ( ( mr >= 0 ) && ( mr < xsize*ysize ) );
+    value = 2 * integralImage[mr];
+    value -= 2 * integralImage[ml];
+    value +=   integralImage[tl];
+    value +=   integralImage[tr];
+    value -=   integralImage[bl];
+    value -=   integralImage[br];
+  } else if ( type == HaarFeature::HAARTYPE_VERTICAL ) {
+    long mt = tl + pos1;
+    long mb = bl + pos1;
+    assert ( ( mt >= 0 ) && ( mt < xsize*ysize ) );
+    assert ( ( mb >= 0 ) && ( mb < xsize*ysize ) );
+
+    value = 2 * integralImage[mb];
+    value -= 2 * integralImage[mt];
+    value +=   integralImage[tl];
+    value +=   integralImage[tr];
+    value -=   integralImage[bl];
+    value -=   integralImage[br];
+  } else if ( type == HaarFeature::HAARTYPE_DIAGONAL ) {
+    int p2o = pos2 * xsize;
+    assert ( ( p2o >= 0 ) && ( p2o < xsize*ysize ) );
+    assert ( ( tl + pos1 >= 0 ) && ( tl + pos1 < xsize*ysize ) );
+    assert ( ( tl + p2o >= 0 ) && ( tl + p2o < xsize*ysize ) );
+    assert ( ( bl + pos1 >= 0 ) && ( bl + pos1 < xsize*ysize ) );
+    assert ( ( tr + p2o >= 0 ) && ( tr + p2o < xsize*ysize ) );
+    assert ( ( tl + pos1 + p2o >= 0 ) && ( tl + pos1 + p2o < xsize*ysize ) );
+
+    value = integralImage[tl];
+    value += integralImage[bl];
+    value += integralImage[br];
+    value += integralImage[tr];
+    value -= 2 * (
+               integralImage[tl+pos1]
+               + integralImage[tl+p2o]
+               + integralImage[bl+pos1]
+               + integralImage[tr+p2o]
+             );
+    value += 4 * integralImage[tl + pos1 + p2o];
+
+  } else if ( type == HaarFeature::HAARTYPE_3BLOCKS ) {
+    assert ( ( tl + pos1 >= 0 ) && ( tl + pos1 < xsize*ysize ) );
+    assert ( ( bl + pos2 >= 0 ) && ( bl + pos2 < xsize*ysize ) );
+    assert ( ( tl + pos2 >= 0 ) && ( tl + pos2 < xsize*ysize ) );
+    assert ( ( bl + pos1 >= 0 ) && ( bl + pos1 < xsize*ysize ) );
+    value = integralImage[tl];
+    value +=  integralImage[br];
+    value -=  integralImage[bl];
+    value -=  integralImage[tr];
+    value += 2 * (
+               - integralImage[tl+pos1]
+               - integralImage[bl+pos2]
+               + integralImage[tl+pos2]
+               + integralImage[bl+pos1]
+             );
+  } else {
+    return -1;
+  }
+
+  assert ( finite ( value ) );
+
+  return value;
 }
 
-void HaarFeature::restore (istream & is, int format)
+void HaarFeature::restore ( istream & is, int format )
 {
-    is >> type;
-    is >> window_size_x;
-    is >> window_size_y;
-    is >> pos1;
-    is >> pos2;
+  is >> type;
+  is >> window_size_x;
+  is >> window_size_y;
+  is >> pos1;
+  is >> pos2;
 }
 
-void HaarFeature::store (ostream & os, int format) const
+void HaarFeature::store ( ostream & os, int format ) const
 {
-    os << "HAARFEATURE" << " " << type << " " 
-       << window_size_x << " " << window_size_y 
-       << " " << pos1 << " " << pos2;
+  os << "HAARFEATURE" << " " << type << " "
+  << window_size_x << " " << window_size_y
+  << " " << pos1 << " " << pos2;
 }
 
-void HaarFeature::clear ()
+void HaarFeature::clear()
 {
-    // nothing to do in my opinion
+  // nothing to do in my opinion
 }
 

+ 40 - 40
features/fpfeatures/HaarFeature.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file HaarFeature.h
 * @brief simple haar like feature
 * @author Erik Rodner
@@ -22,45 +22,45 @@ namespace OBJREC {
 class HaarFeature : public Feature
 {
 
-    protected:
-	enum {
-	    HAARTYPE_HORIZONTAL = 0,
-	    HAARTYPE_VERTICAL,
-	    HAARTYPE_DIAGONAL,
-	    HAARTYPE_3BLOCKS,
-	    HAARTYPE_NUMTYPES
-	};
-
-	int type;
-	int pos1;
-	int pos2;
-	int step_x;
-	int step_y;
-	int window_size_x;
-	int window_size_y;
-
-    public:
-  
-	/** simple constructor */
-	HaarFeature( const NICE::Config *conf );
-      
-	/** without memory wasting config */
-	HaarFeature ( int window_size_x,	
-		      int window_size_y,
-		      int step_x,
-		      int step_y );
-
-	/** simple destructor */
-	virtual ~HaarFeature();
-     
-	virtual double val( const Example *example ) const;
-
-	void explode ( FeaturePool & featurePool, bool variableWindow ) const;
-	Feature *clone() const;
-	
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
+  protected:
+    enum {
+      HAARTYPE_HORIZONTAL = 0,
+      HAARTYPE_VERTICAL,
+      HAARTYPE_DIAGONAL,
+      HAARTYPE_3BLOCKS,
+      HAARTYPE_NUMTYPES
+    };
+
+    int type;
+    int pos1;
+    int pos2;
+    int step_x;
+    int step_y;
+    int window_size_x;
+    int window_size_y;
+
+  public:
+
+    /** simple constructor */
+    HaarFeature ( const NICE::Config *conf );
+
+    /** without memory wasting config */
+    HaarFeature ( int window_size_x,
+                  int window_size_y,
+                  int step_x,
+                  int step_y );
+
+    /** simple destructor */
+    virtual ~HaarFeature();
+
+    virtual double val ( const Example *example ) const;
+
+    void explode ( FeaturePool & featurePool, bool variableWindow ) const;
+    Feature *clone() const;
+
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
 
 };
 

+ 0 - 278
features/localfeatures/Centrist.cpp~

@@ -1,278 +0,0 @@
-/** 
- * @file Centrist.cpp
- * @brief Implementation of the Centrist feature published in  "CENTRIST: A Visual Descriptor for Scene Categorization" (PAMI 2011)
- * @author Alexander Lütz
- * @date 12/06/2011
-*/
-#include <iostream>
-
-#include "vislearning/features/localfeatures/Centrist.h"
-#include "core/image/ImageT.h"
-#include "core/vector/VVector.h"
-
-using namespace OBJREC;
-using namespace std;
-using namespace NICE;
-
-/* protected methods*/
-
-/**
- * @brief: perform centrist transformation for a single pixel 
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-//TODO maybe inline?
-int CensusTransform(const NICE::Image & img, const int & x, const int & y)
-{
-	int index(0);
-	if (! img.isWithinImage(x,y)) return index;
-	
-	if( (img.isWithinImage(x-1,y-1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x-1,y-1)) ) index |= 0x80;
-	if( (img.isWithinImage(x-1,y)) && (img.getPixelInt(x,y)<=img.getPixelInt(x-1,y)) ) index |= 0x40;
-	if( (img.isWithinImage(x-1,y+1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x-1,y+1)) ) index |= 0x20;
-	if( (img.isWithinImage(x,y-1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x,y-1)) ) index |= 0x10;
-	if( (img.isWithinImage(x,y+1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x,y+1)) ) index |= 0x08;
-	if( (img.isWithinImage(x+1,y-1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x+1,y-1)) ) index |= 0x04;
-	if( (img.isWithinImage(x+1,y)) && (img.getPixelInt(x,y)<=img.getPixelInt(x+1,y)) ) index |= 0x02;
-	if( (img.isWithinImage(x+1,y+1)) && (img.getPixelInt(x,y)<=img.getPixelInt(x+1,y+1)) ) index |= 0x01;
-	return index;
-}
-
-/**
- * @brief: perform centrist transformation for a single pixel 
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-//TODO maybe inline?
-int CensusTransform(const NICE::ColorImage & img, const int & x, const int & y, const int & channel)
-{
-	int index(0);
-	if (! img.isWithinImage(x,y)) return index;
-	
-	if( (img.isWithinImage(x-1,y-1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x-1,y-1, channel)) ) index |= 0x80;
-	if( (img.isWithinImage(x-1,y)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x-1,y, channel)) ) index |= 0x40;
-	if( (img.isWithinImage(x-1,y+1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x-1,y+1, channel)) ) index |= 0x20;
-	if( (img.isWithinImage(x,y-1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x,y-1, channel)) ) index |= 0x10;
-	if( (img.isWithinImage(x,y+1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x,y+1, channel)) ) index |= 0x08;
-	if( (img.isWithinImage(x+1,y-1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x+1,y-1, channel)) ) index |= 0x04;
-	if( (img.isWithinImage(x+1,y)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x+1,y, channel)) ) index |= 0x02;
-	if( (img.isWithinImage(x+1,y+1)) && (img.getPixelInt(x,y, channel)<=img.getPixelInt(x+1,y+1, channel)) ) index |= 0x01;
-	return index;
-}
-
-/**
- * @brief: generate CT histogram for a given rectangle: pixels in [xi yi]-(xa,ya) -- including (xi,yi) but excluding (xa,ya)
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-void Centrist::GenerateHistForOneRect(const NICE::Image & img, const int & xi, const int & xa, const int & yi, const int & ya, NICE::Vector & feature)
-{
-// 	double pixelSum(0.0);
-// 	double pixelSquare(0.0);
-	feature.resize(256);
-	feature.set(0.0);
-	
-	for (int j = yi; j < ya; j++)
-	{
-		for (int i = xi; i < xa; i++)
-		{
-// 			pixelSum += img.getPixelInt(i,j);
-// 			pixelSquare += img.getPixelInt(i,j)*img.getPixelInt(i,j);
-			feature[CensusTransform(img,i,j)]++;
-		}
-	}
-	
-// 	const double size ( (xa-xi)*(ya-yi));
-
-	// normalize histogram to have 0 mean, remove the first and last entry, and normalize to have unit norm
-	double sum(feature.Sum()/256.0);//shift more efficient?
-	
-	// normalize histogram to have 0 mean
-	//but why?
-	feature -= sum;
-	
-	//remove the first and last entry
-	feature[0] = 0.0;
-	feature[255] = 0.0;
-
-	//normalization - here done using unit L2-norm
-	feature.normalizeL2();
-}
-
-/**
- * @brief: generate CT histogram for a given rectangle: pixels in [xi yi]-(xa,ya) -- including (xi,yi) but excluding (xa,ya)
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-void Centrist::GenerateHistForOneRect(const NICE::ColorImage & img, const int & xi, const int & xa, const int & yi, const int & ya, NICE::Vector & feature)
-{
-// 	double pixelSum(0.0);
-// 	double pixelSquare(0.0);
-	int nrChannel (img.channels());
-	feature.resize(256*nrChannel);
-	feature.set(0.0);
-	
-	for (int channel = 0; channel < nrChannel; channel++)
-	{
-		for (int j = yi; j < ya; j++)
-		{
-			for (int i = xi; i < xa; i++)
-			{
-// 				pixelSum += img.getPixelInt(i,j, channel);
-// 				pixelSquare += img.getPixelInt(i,j, channel)*img.getPixelInt(i,j, channel);
-				feature[256*channel+CensusTransform(img,i,j,channel)]++;
-			}
-		}
-	}
-	
-// 	const double size ( (xa-xi)*(ya-yi))
-
-	// normalize histogram to have 0 mean, remove the first and last entry, and normalize to have unit norm
-	double sum(feature.Sum()/256.0);//shift more efficient?
-	
-	// normalize histogram to have 0 mean
-	//but why?
-	feature -= sum;
-	
-	//remove the first and last entry
-	feature[0] = 0.0;
-	feature[255] = 0.0;
-
-	//normalization - here done using unit L2-norm
-	feature.normalizeL2();
-}
-
-/**
- * @brief Computes several CENTRIST descriptors for each of the given positions om a local neighborhood
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-void Centrist::computeDesc( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors )
-{
-	descriptors.clear();
-	for (NICE::VVector::const_iterator it = positions.begin(); it != positions.end(); it++)
-	{
-		NICE::Vector descriptor;
-		GenerateHistForOneRect(img, (*it)[0]-sizeNeighborhood/2, (*it)[0]+sizeNeighborhood/2, (*it)[1]-sizeNeighborhood/2, (*it)[1]+sizeNeighborhood/2, descriptor);
-		descriptors.push_back(descriptor);
-	}
-}
-
-/**
- * @brief Computes several CENTRIST descriptors for each of the given positions om a local neighborhood
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-void Centrist::computeDesc( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & descriptors )
-{
-	descriptors.clear();
-	for (NICE::VVector::const_iterator it = positions.begin(); it != positions.end(); it++)
-	{
-		NICE::Vector descriptor;
-		GenerateHistForOneRect(img, (*it)[0]-sizeNeighborhood/2, (*it)[0]+sizeNeighborhood/2, (*it)[1]-sizeNeighborhood/2, (*it)[1]+sizeNeighborhood/2, descriptor);
-		descriptors.push_back(descriptor);
-	}
-}
-
-/* public methods*/
-
-/**
- * @brief Default constructor
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-Centrist::Centrist()
-{
-	sizeNeighborhood = 16;
-}
-
-/**
- * @brief Recommended constructor
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-Centrist::Centrist( const Config *conf, const std::string & section )
-{
-	sizeNeighborhood = conf->gI(section, "sizeNeighborhood", 16);
-}
-
-/**
- * @brief Default destructor
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-Centrist::~Centrist()
-{
-}
-
-
-/**
- * @brief Computes several CENTRIST descriptors for each of the given positions on a local neighborhood
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-int Centrist::getDescriptors ( const NICE::Image & img, VVector & positions, VVector & descriptors )
-{
-	computeDesc(img, positions, descriptors);
-	return 0;
-}
-
-/**
- * @brief Computes several CENTRIST descriptors for each of the given positions on a local neighborhood
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-int Centrist::getDescriptors ( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & descriptors)
-{
-	computeDesc(img, positions, descriptors);
-	return 0;
-}
-
-/**
- * @brief Visualizes CENTRIST descriptors, not implemented yet!
- * @author Alexander Lütz
- * @date 12/06/2011
- */
-void Centrist::visualizeFeatures ( NICE::Image & mark,
-				 const VVector & positions,
-				 size_t color ) const
-{
-//     ice::Image mark_ice = ice::NewImg ( mark.width(), 
-// 	mark.height(), 255 );
-//     for ( size_t k = 0 ; k < positions.size() ; k++ )
-//     {
-// 		const NICE::Vector & pos = positions[k];
-// 		ice::Matrix points ( 0, 2 );
-// 		const int size = 6;
-// 		points.Append ( ice::Vector(-size, -size) );
-// 		points.Append ( ice::Vector(-size, size) );
-// 		points.Append ( ice::Vector(size, size) );
-// 		points.Append ( ice::Vector(size, -size) );
-// 
-// 		ice::Trafo tr;
-// 
-// 		tr.Scale ( 0, 0, pos[2] );
-// 		tr.Rotate ( 0, 0, pos[3] );
-// 		tr.Shift ( pos[0], pos[1] );
-// 
-// 		ice::TransformList(tr, points);
-// 
-// 		for ( int j = 0 ; j < points.rows(); j++ )
-// 		{
-// 			if (points[j][0] < 0 ) 
-// 			points[j][0] = 0;
-// 			if (points[j][0] >= mark_ice->xsize) 
-// 			points[j][0] = mark_ice->xsize - 1;
-// 			if (points[j][1] < 0 ) 
-// 			points[j][1] = 0;
-// 			if (points[j][1] >= mark_ice->ysize) 
-// 			points[j][1] = mark_ice->ysize - 1;
-// 		}
-// 		ice::DrawPolygon ( points, color, mark_ice );
-//     }
-// 
-//     for ( unsigned int y = 0 ; y < mark.height(); y++ )
-// 		for ( unsigned int x = 0 ; x < mark.width(); x++ )
-// 			mark.setPixel(x,y, GetVal(mark_ice,x,y));
-}
-

+ 0 - 64
features/localfeatures/Centrist.h~

@@ -1,64 +0,0 @@
-/** 
-* @file Centrist.h
-* @brief Implementation of the Centrist feature published in  "CENTRIST: A Visual Descriptor for Scene Categorization" (PAMI 2011)
-* @author Alexander Lütz
-* @date 12/06/2011
-*/
-#ifndef CENTRISTINCLUDE
-#define CENTRISTINCLUDE
-
-#ifdef NOVISUAL
-#include <vislearning/nice_nonvis.h>
-#else
-#include <vislearning/nice.h>
-#endif
-
-#include "core/vector/VVector.h"
-#include "LocalFeature.h"
-#include "core/basics/Config.h"
-  
-
-namespace OBJREC {
-
-/** interface to CENTRIST implementation*/
-class Centrist : public LocalFeature
-{
-
-    protected:
-		 int sizeNeighborhood;
-		 
-		 int CensusTransform(const NICE::Image & img, const int & x, const int & y);
-		 int CensusTransform(const NICE::ColorImage & img, const int & x, const int & y, const int & channel);
-		 void GenerateHistForOneRect(const NICE::Image & img, const int & xi, const int & xa, const int & yi, const int & ya, NICE::Vector & feature);
-		 void GenerateHistForOneRect(const NICE::ColorImage & img, const int & xi, const int & xa, const int & yi, const int & ya, NICE::Vector & feature);
-		 void computeDesc( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors );
-		 void computeDesc( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & descriptors );
-
-    public:
-  
-	/** simple constructor */
-	Centrist();
-	/** default constructor */
-	Centrist(const NICE::Config *conf, const std::string & section="CENTRIST");
-      
-	/** simple destructor */
-	virtual ~Centrist();
-
-	// we have 8 neighbors, so the size is always 256 with the given implementation (without spatial levels, ...)
-	/** Beware: multiply this number by the number of channels you use in your color image*/
-	int getDescSize(){return 256;};
-
-	int getDescriptors ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors);
-	
-	int getDescriptors ( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & descriptors);
-	
-	void visualizeFeatures ( NICE::Image & mark,
-				 const NICE::VVector & positions,
-				 size_t color ) const;
-    
-};
-
-
-} // namespace
-
-#endif

+ 413 - 416
features/localfeatures/LFColorWeijer.cpp

@@ -1,5 +1,5 @@
 #include "vislearning/features/localfeatures/LFColorWeijer.h"
-  
+
 #include <fstream>
 #include <iostream>
 #include "vislearning/baselib/ColorSpace.h"
@@ -11,485 +11,482 @@ using namespace std;
 using namespace NICE;
 
 //! color representation for visualization
-const int colors[11][3] = 
+const int colors[11][3] =
 {
-	{0,     0,   0}, // black
-	{0,     0, 255}, // blue
-	{165,  42,  42}, // brown
-	{190, 190, 190}, // grey
-	{  0, 255,   0}, // green
-	{255, 165,   0}, // orange
-	{255, 192, 203}, // pink
-	{160,  32, 240}, // purple
-	{255,   0,   0}, // red
-	{255, 255, 255}, // white
-	{255, 255,   0}, // yellow
+  {0,     0,   0}, // black
+  {0,     0, 255}, // blue
+  {165,  42,  42}, // brown
+  {190, 190, 190}, // grey
+  {  0, 255,   0}, // green
+  {255, 165,   0}, // orange
+  {255, 192, 203}, // pink
+  {160,  32, 240}, // purple
+  {255,   0,   0}, // red
+  {255, 255, 255}, // white
+  {255, 255,   0}, // yellow
 };
 
 
-LFColorWeijer::LFColorWeijer(const Config *c)
+LFColorWeijer::LFColorWeijer( const Config *c )
 {
-	conf = c;
-	
-	bin[0] = conf->gI("LFColorWeijer", "binL", 10);
-	bin[1] = conf->gI("LFColorWeijer", "bina", 20);
-	bin[2] = conf->gI("LFColorWeijer", "binb", 20);
-
-	maxv[0] =  100.0;
-	maxv[1] =   80.0;
-	maxv[2] =   50.0;
-
-	minv[0] =    0.0;
-	minv[1] = -105.0;
-	minv[2] = -200.0;
-
-	tfile = conf->gS("LFColorWeijer", "table", "/home/dbv/bilder/colorWeijer/color.txt");
-
-	for (int i = 0; i < 3; i++)
-	{
-		interval[i] = (maxv[i] - minv[i]) / (double)bin[i];
-	}
-
-	ifstream test(tfile.c_str());
-
-	if (test)
-	{
-		restore();
-	}
-	else
-	{
-		train();
-	}
+  conf = c;
+
+  bin[0] = conf->gI( "LFColorWeijer", "binL", 10 );
+  bin[1] = conf->gI( "LFColorWeijer", "bina", 20 );
+  bin[2] = conf->gI( "LFColorWeijer", "binb", 20 );
+
+  maxv[0] =  100.0;
+  maxv[1] =   80.0;
+  maxv[2] =   50.0;
+
+  minv[0] =    0.0;
+  minv[1] = -105.0;
+  minv[2] = -200.0;
+
+  tfile = conf->gS( "LFColorWeijer", "table", "/home/dbv/bilder/colorWeijer/color.txt" );
+
+  for ( int i = 0; i < 3; i++ )
+  {
+    interval[i] = ( maxv[i] - minv[i] ) / ( double )bin[i];
+  }
+
+  ifstream test( tfile.c_str() );
+
+  if ( test )
+  {
+    restore();
+  }
+  else
+  {
+    train();
+  }
 }
 
 LFColorWeijer::~LFColorWeijer()
 {
-	for(uint i = 0; i < hist.size(); i++)
-	{
-		for(uint j = 0; j < hist[i].size(); j++)
-		{
-			hist[i][j].clear();
-		}
-		hist[i].clear();
-	}
-	hist.clear();
+  for ( uint i = 0; i < hist.size(); i++ )
+  {
+    for ( uint j = 0; j < hist[i].size(); j++ )
+    {
+      hist[i][j].clear();
+    }
+    hist[i].clear();
+  }
+  hist.clear();
 }
 
 int LFColorWeijer::getDescSize() const
 {
-	return LASTCOLOR;
+  return LASTCOLOR;
 }
 
 void LFColorWeijer::store()
 {
-	ofstream fout(tfile.c_str(), ios_base::app);
-
-	fout << hist.size() << " " << hist[0].size() << " " << hist[0][0].size() << " " << hist[0][0][0].size() << endl;
-
-	for (uint i = 0; i < hist.size(); i++)
-	{
-		for (uint i0 = 0; i0 < hist[i].size(); i0++)
-		{
-			for (uint i1 = 0; i1 < hist[i][i0].size(); i1++)
-			{
-				for (uint i2 = 0; i2 < hist[i][i0][i1].size(); i2++)
-				{
-					fout << hist[i][i0][i1][i2] << " ";
-				}
-			}
-		}
-	}
+  ofstream fout( tfile.c_str(), ios_base::app );
+
+  fout << hist.size() << " " << hist[0].size() << " " << hist[0][0].size() << " " << hist[0][0][0].size() << endl;
+
+  for ( uint i = 0; i < hist.size(); i++ )
+  {
+    for ( uint i0 = 0; i0 < hist[i].size(); i0++ )
+    {
+      for ( uint i1 = 0; i1 < hist[i][i0].size(); i1++ )
+      {
+        for ( uint i2 = 0; i2 < hist[i][i0][i1].size(); i2++ )
+        {
+          fout << hist[i][i0][i1][i2] << " ";
+        }
+      }
+    }
+  }
 }
 
 void LFColorWeijer::smooth()
 {
-	int size0 = (int)hist.size();
-	int size1 = (int)hist[0].size();
-	int size2 = (int)hist[0][0].size();
-	int size3 = (int)hist[0][0][0].size();
-	for(int i0 = 0; i0 < size1; i0++)
-	{
-		for(int i1 = 0; i1 < size2; i1++)
-		{
-			for(int i2 = 0; i2 < size3; i2++)
-			{
-				double maxval = 0.0;
-				for(int i = 0; i < size0; i++)
-				{
-					maxval = std::max(maxval, hist[i][i0][i1][i2]);
-				}
-				if(maxval == 0.0)
-				{
-					for(int i = 0; i < size0; i++)
-					{
-						int anz = 0;
-						for(int a0 = std::max(i0-1,0); a0 <= std::min(i0+1,size1-1); a0++)
-						{
-							for(int a1 = std::max(i1-1,0); a1 <= std::min(i1+1,size2-1); a1++)
-							{
-								for(int a2 = std::max(i2-1,0); a2 <= std::min(i2+1,size3-1); a2++)
-								{
-									anz++;
-									hist[i][i0][i1][i2] += hist[i][a0][a1][a2];
-								}
-							}
-						}
-						hist[i][i0][i1][i2] /= anz;
-					}
-				}
-			}
-		}
-	}
+  int size0 = ( int )hist.size();
+  int size1 = ( int )hist[0].size();
+  int size2 = ( int )hist[0][0].size();
+  int size3 = ( int )hist[0][0][0].size();
+  for ( int i0 = 0; i0 < size1; i0++ )
+  {
+    for ( int i1 = 0; i1 < size2; i1++ )
+    {
+      for ( int i2 = 0; i2 < size3; i2++ )
+      {
+        double maxval = 0.0;
+        for ( int i = 0; i < size0; i++ )
+        {
+          maxval = std::max( maxval, hist[i][i0][i1][i2] );
+        }
+        if ( maxval == 0.0 )
+        {
+          for ( int i = 0; i < size0; i++ )
+          {
+            int anz = 0;
+            for ( int a0 = std::max( i0 - 1, 0 ); a0 <= std::min( i0 + 1, size1 - 1 ); a0++ )
+            {
+              for ( int a1 = std::max( i1 - 1, 0 ); a1 <= std::min( i1 + 1, size2 - 1 ); a1++ )
+              {
+                for ( int a2 = std::max( i2 - 1, 0 ); a2 <= std::min( i2 + 1, size3 - 1 ); a2++ )
+                {
+                  anz++;
+                  hist[i][i0][i1][i2] += hist[i][a0][a1][a2];
+                }
+              }
+            }
+            hist[i][i0][i1][i2] /= anz;
+          }
+        }
+      }
+    }
+  }
 }
 
 void LFColorWeijer::restore()
 {
-	int size0, size1, size2, size3;
-	ifstream fin(tfile.c_str());
-	fin >> size0;
-	fin >> size1;
-	fin >> size2;
-	fin >> size3;
-	hist.clear();
-
-	for (int i = 0; i < size0; i++)
-	{
-		vector<vector<vector<double> > > v2;
-
-		for (int i0 = 0; i0 < size1; i0++)
-		{
-			vector<vector<double> > v1;
-
-			for (int i1 = 0; i1 < size2; i1++)
-			{
-				vector<double> v0;
-
-				for (int i2 = 0; i2 < size3; i2++)
-				{
-					double val;
-					fin >> val;
-					v0.push_back(val);
-				}
-
-				v1.push_back(v0);
-			}
-
-			v2.push_back(v1);
-		}
-
-		hist.push_back(v2);
-	}
+  int size0, size1, size2, size3;
+  ifstream fin( tfile.c_str() );
+  fin >> size0;
+  fin >> size1;
+  fin >> size2;
+  fin >> size3;
+  hist.clear();
+
+  for ( int i = 0; i < size0; i++ )
+  {
+    vector<vector<vector<double> > > v2;
+
+    for ( int i0 = 0; i0 < size1; i0++ )
+    {
+      vector<vector<double> > v1;
+
+      for ( int i1 = 0; i1 < size2; i1++ )
+      {
+        vector<double> v0;
+
+        for ( int i2 = 0; i2 < size3; i2++ )
+        {
+          double val;
+          fin >> val;
+          v0.push_back( val );
+        }
+
+        v1.push_back( v0 );
+      }
+
+      v2.push_back( v1 );
+    }
+
+    hist.push_back( v2 );
+  }
 }
 
-int LFColorWeijer::getDescriptors ( const NICE::Image & img, VVector & positions, VVector & features ) const
+int LFColorWeijer::getDescriptors( const NICE::Image & img, VVector & positions, VVector & features ) const
 {
-	cerr << "this are COLOR Features, they won't work on gray value images" << endl;
-	exit(-1);
+  cerr << "this are COLOR Features, they won't work on gray value images" << endl;
+  exit( -1 );
 }
 
-int LFColorWeijer::getDescriptors(const NICE::ColorImage & img, VVector & positions, VVector & features) const
+int LFColorWeijer::getDescriptors( const NICE::ColorImage & img, VVector & positions, VVector & features ) const
 {
-	// in Lab umwandeln
-	for (int i = 0; i < (int)positions.size(); i++)
-	{
-			vector<double> vals;
-			vector<int> b;
-			int x = positions[i][0];
-			int y = positions[i][1];
-			
-			double R,G,B,X,Y,Z;
-			vector<double> lab(3,0.0);
-			
-			R=(double)img.getPixel(x,y,0)/255.0;
-			G=(double)img.getPixel(x,y,1)/255.0;
-			B=(double)img.getPixel(x,y,2)/255.0;
-			
-			ColorConversion::ccRGBtoXYZ(R,G,B,&X,&Y,&Z,0);
-			ColorConversion::ccXYZtoCIE_Lab(X,Y,Z,&lab[0],&lab[1],&lab[2],0);
-			
-			for (int i = 0; i < 3; i++)
-			{
-				int val = (int)((lab[i] - minv[i]) / interval[i]);
-				val = std::min(val, bin[i] - 1);
-				val = std::max(val, 0);
-				b.push_back(val);
-			}
-
-			Vector feat(hist.size());
-			
-			for (uint i = 0; i < hist.size(); i++)
-			{
-				feat[i] = hist[i][b[0]][b[1]][b[2]];
-			}
-			features.push_back(feat);
-	}
-	
-	return 1;
+  // in Lab umwandeln
+  for ( int i = 0; i < ( int )positions.size(); i++ )
+  {
+    vector<double> vals;
+    vector<int> b;
+    int x = positions[i][0];
+    int y = positions[i][1];
+
+    double R, G, B, X, Y, Z;
+    vector<double> lab( 3, 0.0 );
+
+    R = ( double )img.getPixel( x, y, 0 ) / 255.0;
+    G = ( double )img.getPixel( x, y, 1 ) / 255.0;
+    B = ( double )img.getPixel( x, y, 2 ) / 255.0;
+
+    ColorConversion::ccRGBtoXYZ( R, G, B, &X, &Y, &Z, 0 );
+    ColorConversion::ccXYZtoCIE_Lab( X, Y, Z, &lab[0], &lab[1], &lab[2], 0 );
+
+    for ( int i = 0; i < 3; i++ )
+    {
+      int val = ( int )(( lab[i] - minv[i] ) / interval[i] );
+      val = std::min( val, bin[i] - 1 );
+      val = std::max( val, 0 );
+      b.push_back( val );
+    }
+
+    Vector feat( hist.size() );
+
+    for ( uint i = 0; i < hist.size(); i++ )
+    {
+      feat[i] = hist[i][b[0]][b[1]][b[2]];
+    }
+    features.push_back( feat );
+  }
+
+  return 1;
 }
 
-void LFColorWeijer::visualizeFeatures ( NICE::Image & mark, const VVector & positions,	size_t color ) const
+void LFColorWeijer::visualizeFeatures( NICE::Image & mark, const VVector & positions, size_t color ) const
 {
-	
+
 }
 
-void LFColorWeijer::add(vector<vector<vector<double> > > &dest, vector<vector<vector<double> > > &src)
+void LFColorWeijer::add( vector<vector<vector<double> > > &dest, vector<vector<vector<double> > > &src )
 {
-	for(uint i0 = 0; i0 < src.size(); i0++)
-	{
-		for(uint i1 = 0; i1 < src[i0].size(); i1++)
-		{
-			for(uint i2 = 0; i2 < src[i0][i1].size(); i2++)
-			{
-				dest[i0][i1][i2] += src[i0][i1][i2];
-			}
-		}
-	}
+  for ( uint i0 = 0; i0 < src.size(); i0++ )
+  {
+    for ( uint i1 = 0; i1 < src[i0].size(); i1++ )
+    {
+      for ( uint i2 = 0; i2 < src[i0][i1].size(); i2++ )
+      {
+        dest[i0][i1][i2] += src[i0][i1][i2];
+      }
+    }
+  }
 }
 
-int LFColorWeijer::findColor(string &fn)
+int LFColorWeijer::findColor( string &fn )
 {
-	if(fn.find("black") != string::npos)
-		return BLACK;
-	if(fn.find("blue") != string::npos)
-		return BLUE;
-	if(fn.find("brown") != string::npos)
-		return BROWN;
-	if(fn.find("grey") != string::npos)
-		return GREY;
-	if(fn.find("green") != string::npos)
-		return GREEN;
-	if(fn.find("orange") != string::npos)
-		return ORANGE;
-	if(fn.find("pink") != string::npos)
-		return PINK;
-	if(fn.find("purple") != string::npos)
-		return PURPLE;
-	if(fn.find("red") != string::npos)
-		return RED;
-	if(fn.find("white") != string::npos)
-		return WHITE;
-	if(fn.find("yellow") != string::npos)
-		return YELLOW;
-	
-	return -1;
+  if ( fn.find( "black" ) != string::npos )
+    return BLACK;
+  if ( fn.find( "blue" ) != string::npos )
+    return BLUE;
+  if ( fn.find( "brown" ) != string::npos )
+    return BROWN;
+  if ( fn.find( "grey" ) != string::npos )
+    return GREY;
+  if ( fn.find( "green" ) != string::npos )
+    return GREEN;
+  if ( fn.find( "orange" ) != string::npos )
+    return ORANGE;
+  if ( fn.find( "pink" ) != string::npos )
+    return PINK;
+  if ( fn.find( "purple" ) != string::npos )
+    return PURPLE;
+  if ( fn.find( "red" ) != string::npos )
+    return RED;
+  if ( fn.find( "white" ) != string::npos )
+    return WHITE;
+  if ( fn.find( "yellow" ) != string::npos )
+    return YELLOW;
+
+  return -1;
 }
 
 vector<vector<vector<double > > > LFColorWeijer::createTable()
 {
-	vector<vector<vector<double> > > h;
-	for(int i0 = 0; i0 < bin[0]; i0++)
-	{
-		vector<vector< double > > vec;
-		for(int i1 = 0; i1 < bin[1]; i1++)
-		{
-			vector<double> v;
-			for(int i2 = 0; i2 < bin[2]; i2++)
-			{
-				v.push_back(0.0);
-			}
-			vec.push_back(v);
-		}
-		h.push_back(vec);
-	}
-	return h;
+  vector<vector<vector<double> > > h;
+  for ( int i0 = 0; i0 < bin[0]; i0++ )
+  {
+    vector<vector< double > > vec;
+    for ( int i1 = 0; i1 < bin[1]; i1++ )
+    {
+      vector<double> v;
+      for ( int i2 = 0; i2 < bin[2]; i2++ )
+      {
+        v.push_back( 0.0 );
+      }
+      vec.push_back( v );
+    }
+    h.push_back( vec );
+  }
+  return h;
 }
 
-void LFColorWeijer::normalize(vector<vector<vector<double> > > &tab)
+void LFColorWeijer::normalize( vector<vector<vector<double> > > &tab )
 {
-	double sum = 0.0;
-	
-	for(uint i0 = 0; i0 < tab.size(); i0++)
-	{
-		for(uint i1 = 0; i1 < tab[i0].size(); i1++)
-		{
-			for(uint i2 = 0; i2 < tab[i0][i1].size(); i2++)
-			{
-				sum += tab[i0][i1][i2];
-			}
-		}
-	}
-	
-	for(uint i0 = 0; i0 < tab.size(); i0++)
-	{
-		for(uint i1 = 0; i1 < tab[i0].size(); i1++)
-		{
-			for(uint i2 = 0; i2 < tab[i0][i1].size(); i2++)
-			{
-				tab[i0][i1][i2] /= sum;
-			}
-		}
-	}
-	
-	return;
+  double sum = 0.0;
+
+  for ( uint i0 = 0; i0 < tab.size(); i0++ )
+  {
+    for ( uint i1 = 0; i1 < tab[i0].size(); i1++ )
+    {
+      for ( uint i2 = 0; i2 < tab[i0][i1].size(); i2++ )
+      {
+        sum += tab[i0][i1][i2];
+      }
+    }
+  }
+
+  for ( uint i0 = 0; i0 < tab.size(); i0++ )
+  {
+    for ( uint i1 = 0; i1 < tab[i0].size(); i1++ )
+    {
+      for ( uint i2 = 0; i2 < tab[i0][i1].size(); i2++ )
+      {
+        tab[i0][i1][i2] /= sum;
+      }
+    }
+  }
+
+  return;
 }
 
-void LFColorWeijer::createHist(const ColorImage &cimg, vector<vector<vector<double> > > &hist, Image &mask)
+void LFColorWeijer::createHist( const ColorImage &cimg, vector<vector<vector<double> > > &hist, Image &mask )
 {
-	// in Lab umwandeln
-	NICE::MultiChannelImageT<double> genimg, imglab;
-
-	ColorSpace::ColorImagetoMultiChannelImage(cimg, genimg);
-	ColorSpace::convert(imglab, genimg, ColorSpace::COLORSPACE_LAB, ColorSpace::COLORSPACE_RGB);
-	
-	for(int y = 0; y < cimg.height(); y++)
-	{
-		for(int x = 0; x < cimg.width(); x++)
-		{
-			if(mask.getPixel(x,y) == 0)
-				continue;
-			vector<int> b;
-			for(int i = 0; i < 3; i++)
-			{
-				int val =(int)((imglab.get(x,y,i)-minv[i])/interval[i]);
-				val = std::min(val, bin[i]-1);
-				b.push_back(val);
-			}
-			hist[b[0]][b[1]][b[2]]++;
-		}
-	}
+  // in Lab umwandeln
+  NICE::MultiChannelImageT<double> genimg, imglab;
+
+  ColorSpace::ColorImagetoMultiChannelImage( cimg, genimg );
+  ColorSpace::convert( imglab, genimg, ColorSpace::COLORSPACE_LAB, ColorSpace::COLORSPACE_RGB );
+
+  for ( int y = 0; y < cimg.height(); y++ )
+  {
+    for ( int x = 0; x < cimg.width(); x++ )
+    {
+      if ( mask.getPixel( x, y ) == 0 )
+        continue;
+      vector<int> b;
+      for ( int i = 0; i < 3; i++ )
+      {
+        int val = ( int )(( imglab.get( x, y, i ) - minv[i] ) / interval[i] );
+        val = std::min( val, bin[i] - 1 );
+        b.push_back( val );
+      }
+      hist[b[0]][b[1]][b[2]]++;
+    }
+  }
 }
 
 void LFColorWeijer::train()
 {
-	cout << "train Starts" << endl;
-	for(int i = 0; i < LASTCOLOR; i++)
-	{
-		vector<vector<vector<double> > > h = createTable();
-		hist.push_back(h);
-	}
-	
-	string dir = conf->gS("LFColorWeijer", "table", "/home/dbv/bilder/colorWeijer/ebay/");
-	string images = conf->gS("LFColorWeijer", "table", "test_images.txt");
-	string mask = conf->gS("LFColorWeijer", "table", "mask_images.txt");
-		
-	string imagesfn;
-	string maskfn;
-	
-	ifstream finimg( (dir+images).c_str());
-	ifstream finmask( (dir+mask).c_str());
-	cout << dir+images << endl;
-	cout << dir+mask << endl;
-	// lese bilder und masken ein
-	while( finimg >> imagesfn && finmask >> maskfn)
-	{
-		Image mimg(dir+maskfn);
-		cout << dir+maskfn << endl;
-		ColorImage cimg(dir+imagesfn);
-			
-		int col = findColor(imagesfn);
-		vector<vector<vector<double> > > tab = createTable();
-			
-		createHist(cimg, tab, mimg); // erzeuge Lab Histogramm des Bildes
-			
-		normalize(tab);
-			
-		add(hist[col], tab);
-	}
-	finimg.close();
-	finmask.close();
-		
-		// normalisiere alle lookuptables
-	for(uint i = 0; i < hist.size(); i++)
-	{
-		normalize(hist[i]);
-	}
-		
-	smooth();
-	store();
+  cout << "train Starts" << endl;
+  for ( int i = 0; i < LASTCOLOR; i++ )
+  {
+    vector<vector<vector<double> > > h = createTable();
+    hist.push_back( h );
+  }
+
+  string dir = conf->gS( "LFColorWeijer", "table", "/home/dbv/bilder/colorWeijer/ebay/" );
+  string images = conf->gS( "LFColorWeijer", "table", "test_images.txt" );
+  string mask = conf->gS( "LFColorWeijer", "table", "mask_images.txt" );
+
+  string imagesfn;
+  string maskfn;
+
+  ifstream finimg(( dir + images ).c_str() );
+  ifstream finmask(( dir + mask ).c_str() );
+  cout << dir + images << endl;
+  cout << dir + mask << endl;
+  // lese bilder und masken ein
+  while ( finimg >> imagesfn && finmask >> maskfn )
+  {
+    Image mimg( dir + maskfn );
+    cout << dir + maskfn << endl;
+    ColorImage cimg( dir + imagesfn );
+
+    int col = findColor( imagesfn );
+    vector<vector<vector<double> > > tab = createTable();
+
+    createHist( cimg, tab, mimg ); // erzeuge Lab Histogramm des Bildes
+
+    normalize( tab );
+
+    add( hist[col], tab );
+  }
+  finimg.close();
+  finmask.close();
+
+  // normalisiere alle lookuptables
+  for ( uint i = 0; i < hist.size(); i++ )
+  {
+    normalize( hist[i] );
+  }
+
+  smooth();
+  store();
 }
 
-void LFColorWeijer::visualizeFeatures ( NICE::ColorImage & out, const VVector & features, const VVector & position ) const
+void LFColorWeijer::visualizeFeatures( NICE::ColorImage & out, const VVector & features, const VVector & position ) const
 {
-	for(int i = 0; i < (int)position.size(); i++)
-	{
-		int maxpos = 0;
-		double maxval = 0.0;
-		for(int j = 0; j < (int)features[i].size(); j++)
-		{
-			if(maxval < features[i][j])
-			{
-				maxval = features[i][j];
-				maxpos = j;
-			}
-		}
-		
-		out.setPixel(position[i][0],position[i][1],colors[maxpos][0],colors[maxpos][1],colors[maxpos][2]);
-	}
+  for ( int i = 0; i < ( int )position.size(); i++ )
+  {
+    int maxpos = 0;
+    double maxval = 0.0;
+    for ( int j = 0; j < ( int )features[i].size(); j++ )
+    {
+      if ( maxval < features[i][j] )
+      {
+        maxval = features[i][j];
+        maxpos = j;
+      }
+    }
+
+    out.setPixel( position[i][0], position[i][1], colors[maxpos][0], colors[maxpos][1], colors[maxpos][2] );
+  }
 }
 
-void LFColorWeijer::visualizeFeatures ( const NICE::ColorImage & cimg) const
+void LFColorWeijer::visualizeFeatures( const NICE::ColorImage & cimg ) const
 {
-	ColorImage out;
-	visualizeFeatures(cimg, out);
+  ColorImage out;
+  visualizeFeatures( cimg, out );
 }
 
-void LFColorWeijer::visualizeFeatures ( const NICE::ColorImage & cimg, NICE::ColorImage &out) const
+void LFColorWeijer::visualizeFeatures( const NICE::ColorImage & cimg, NICE::ColorImage &out ) const
 {
-	VVector pos, feats;
-	for(int y = 0; y < cimg.height(); y++)
-	{
-		for(int x = 0; x < cimg.width(); x++)
-		{
-			Vector vec(2);
-			vec[0] = x;
-			vec[1] = y;
-			pos.push_back(vec);
-		}
-	}
-	
-	getDescriptors(cimg, pos, feats);
-	
-	out.resize(cimg.width(), cimg.height());
-	out.set(0,0,0);
-	visualizeFeatures ( out, feats, pos);
-	ColorImage combinedout(cimg.width()*2, cimg.height());
-	
-	int width = (int)cimg.width();
-	
-	for(int y = 0; y < (int)cimg.height(); y++)
-	{
-		for(int x = 0; x < width; x++)
-		{
-			combinedout.setPixel(x,y,cimg.getPixel(x,y,0), cimg.getPixel(x,y,1),cimg.getPixel(x,y,2));
-			combinedout.setPixel(x+width,y,out.getPixel(x,y,0), out.getPixel(x,y,1),out.getPixel(x,y,2));
-		}
-	}
-	
-	showImage(combinedout, "Ergebnis");
+  VVector pos, feats;
+  for ( int y = 0; y < cimg.height(); y++ )
+  {
+    for ( int x = 0; x < cimg.width(); x++ )
+    {
+      Vector vec( 2 );
+      vec[0] = x;
+      vec[1] = y;
+      pos.push_back( vec );
+    }
+  }
+
+  getDescriptors( cimg, pos, feats );
+
+  out.resize( cimg.width(), cimg.height() );
+  out.set( 0, 0, 0 );
+  visualizeFeatures( out, feats, pos );
+  ColorImage combinedout( cimg.width()*2, cimg.height() );
+
+  int width = ( int )cimg.width();
+
+  for ( int y = 0; y < ( int )cimg.height(); y++ )
+  {
+    for ( int x = 0; x < width; x++ )
+    {
+      combinedout.setPixel( x, y, cimg.getPixel( x, y, 0 ), cimg.getPixel( x, y, 1 ), cimg.getPixel( x, y, 2 ) );
+      combinedout.setPixel( x + width, y, out.getPixel( x, y, 0 ), out.getPixel( x, y, 1 ), out.getPixel( x, y, 2 ) );
+    }
+  }
+
+  showImage( combinedout, "result" );
 }
 
-void LFColorWeijer::getFeats(const ColorImage &img, vector<vector<vector<double> > > &feats)
+void LFColorWeijer::getFeats( const ColorImage &img, MultiChannelImageT<double> &feats )
 {
-	int width = (int)img.width();
-	int height = (int)img.height();
-	
-	feats = vector<vector<vector<double> > >(width,vector<vector<double> >(height,vector<double>(hist.size(),0.0)));
-	
-	NICE::MultiChannelImageT<double> genimg, imglab;
-	
-	ColorSpace::ColorImagetoMultiChannelImage (img, genimg);
-	ColorSpace::convert(imglab, genimg, ColorSpace::COLORSPACE_LAB, ColorSpace::COLORSPACE_RGB);
-	
-	for(int y = 0; y < height; y++)
-	{
-		for(int x = 0; x < width; x++)
-		{
-			for (uint i = 0; i < hist.size(); i++)
-			{
-				vector<double> b(3,0.0);
-				for (int j = 0; j < 3; j++)
-				{
-					int val = (int)((imglab.get(x,y,j) - minv[j]) / interval[j]);
-					val = std::min(val, bin[j] - 1);
-					val = std::max(val, 0);
-					b[j] = val;
-				}
-				feats[x][y][i] = hist[i][b[0]][b[1]][b[2]];
-			}
-		}
-	}
-	
-	return;
+  int width = ( int )img.width();
+  int height = ( int )img.height();
+  feats.reInit( width, height, hist.size(), true );
+
+  NICE::MultiChannelImageT<double> genimg, imglab;
+
+  ColorSpace::ColorImagetoMultiChannelImage( img, genimg );
+  ColorSpace::convert( imglab, genimg, ColorSpace::COLORSPACE_LAB, ColorSpace::COLORSPACE_RGB );
+
+  for ( int y = 0; y < height; y++ )
+  {
+    for ( int x = 0; x < width; x++ )
+    {
+      for ( uint i = 0; i < hist.size(); i++ )
+      {
+        vector<double> b( 3, 0.0 );
+        for ( int j = 0; j < 3; j++ )
+        {
+          int val = ( int )(( imglab.get( x, y, j ) - minv[j] ) / interval[j] );
+          val = std::min( val, bin[j] - 1 );
+          val = std::max( val, 0 );
+          b[j] = val;
+        }
+        feats.set( x, y, hist[i][b[0]][b[1]][b[2]], i );
+      }
+    }
+  }
+
+  return;
 }
-
-

+ 2 - 1
features/localfeatures/LFColorWeijer.h

@@ -11,6 +11,7 @@
 #include "core/vector/MatrixT.h"
 #include "core/image/ImageT.h"
 #include "core/imagedisplay/ImageDisplay.h"
+#include "core/image/MultiChannelImageT.h"
 
 #include "LocalFeature.h"
 #include "core/basics/Config.h"
@@ -183,7 +184,7 @@ class LFColorWeijer : public LocalFeature
 		 * @param img input image
 		 * @param feats feature vector for each pixel
 		 */
-		void getFeats(const NICE::ColorImage &img, std::vector<std::vector<std::vector<double> > > &feats);
+		void getFeats(const NICE::ColorImage &img, NICE::MultiChannelImageT<double> &feats);
 };
 
 

+ 0 - 191
features/localfeatures/LFColorWeijer.h~

@@ -1,191 +0,0 @@
-/** 
- * @file LFColorWeijer.cpp
- * @brief implementation of the color features mentioned in van de Weijer, J. & Schmid, C. Applying Color Names to Image Description (2007)
- * @author Björn Fröhlich
- * @date 01/28/2010
- */
-#ifndef LFColorWeijerINCLUDE
-#define LFColorWeijerINCLUDE
-
-#include "core/vector/VectorT.h"
-#include "core/vector/MatrixT.h"
-#include "core/image/ImageT.h"
-
-#include "LocalFeature.h"
-#include "core/basics/Config.h"
-
-
-namespace OBJREC {
-
-/** interface to ColorSande implementation */
-class LFColorWeijer : public LocalFeature
-{
-
-    protected:
-		//! enum for 11 main colors
-		enum 
-		{
-			BLACK = 0,
-			BLUE,
-			BROWN,
-			GREY,
-			GREEN,
-			ORANGE,
-			PINK,
-			PURPLE,
-			RED,
-			WHITE,
-			YELLOW,
-			LASTCOLOR
-		};
-		
-		//! bins for L*, a* and b* chanel of L*a*b*
-		int bin[3];
-
-		//! upper limits for L*, a* and b* chanel of L*a*b*
-		double maxv[3];
-		
-		//! lower limits for L*, a* and b* chanel of L*a*b*
-		double minv[3];
-		
-		//! quantization interval for L*, a* and b* chanel of L*a*b* depending on bin, maxv and minv
-		double interval[3];
-		
-		//! destination of the computed lookuptable
-		std::string tfile;
-		
-		//! lookuptable for the probabilities (4d: colors, L-channel, a-channel, b-channel)
-		std::vector<std::vector<std::vector<std::vector<double> > > > hist;
-		
-		//! configuration file
-		const NICE::Config *conf;
-		
-    public:
-  
-		/** simple constructor */
-		LFColorWeijer( const NICE::Config *c);
-		  
-		/** simple destructor */
-		virtual ~LFColorWeijer();
-		
-		/**
-		 * get the size of the descriptor
-		 * @return size of descriptor
-		 */
-		int getDescSize () const;
-		
-		/**
-		 * get the colorWeijer features
-		 * @param img grayvalue input image
-		 * @param features features (output)
-		 * @param positions position of the features
-		 * @return 
-		 */
-		int getDescriptors ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & features ) const;
-		
-		/**
-		 * get the colorWeijer features
-		 * @param img color input image
-		 * @param features features (output)
-		 * @param positions given positions of the features
-		 * @return 
-		 */
-		int getDescriptors ( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & features ) const;
-		
-		/**
-		 * visualize the features
-		 * @param mark 
-		 * @param positions 
-		 * @param color 
-		 */
-		void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions,	size_t color ) const;
-		
-		/**
-		 * visualize the features
-		 * @param mark 
-		 * @param positions 
-		 * @param color 
-		 */
-		void visualizeFeatures ( NICE::ColorImage & mark, const NICE::VVector & features, const NICE::VVector & position ) const;
-		
-		/**
-		 * visualize the features
-		 * @param cimg 
-		 */
-		void visualizeFeatures ( const NICE::ColorImage & cimg) const;
-		
-		/**
-		 * visualize the features
-		 * @param cimg 
-		 * @param out
-		 */
-		void visualizeFeatures ( const NICE::ColorImage & cimg, NICE::ColorImage & out) const;
-		
-		/**
-		 * save parameters
-		 */
-		void store();
-		
-		
-		/**
-		 * load parameters
-		 */
-		void restore();
-		
-		/**
-		 * smooths the look up table
-		 */
-		void smooth();
-		
-		/**
-		 * normalizes the sum of a 3d histogram to 1
-		 * @param tab 3d histogram
-		 */
-		void normalize(std::vector<std::vector<std::vector<double> > > &tab);
-		
-		/**
-		 * creates a new and empty table
-		 * @return table of the size bin[0]xbin[1]xbin[2]
-		 */
-		std::vector<std::vector<std::vector<double > > > createTable();
-		
-		/**
-		 * finds a colorname in a given string
-		 * @param fn input string
-		 * @return number of the color
-		 */
-		int findColor(std::string &fn);
-		
-		/**
-		 * creates a new Histogram for input image depending on the image mask
-		 * @param cimg input image
-		 * @param hist histogram
-		 * @param mask which pixel should be consider
-		 */
-		void createHist(const NICE::ColorImage &cimg, std::vector<std::vector<std::vector<double> > > &hist, NICE::Image &mask);
-		
-		/**
-		 * train the lookuptable
-		 */
-		void train();
-		
-		
-		/**
-		 * add a 3d table to a 3d table elementwise
-		 * @param dest destination table
-		 * @param src source table
-		 */
-		void add(std::vector<std::vector<std::vector<double> > > &dest, std::vector<std::vector<std::vector<double> > > &src);
-		
-		/**
-		 * transform each pixel of an image
-		 * @param img input image
-		 * @param feats feature vector for each pixel
-		 */
-		void getFeats(const NICE::ColorImage &img, std::vector<std::vector<std::vector<double> > > &feats);
-};
-
-
-} // namespace
-
-#endif

+ 1 - 1
features/localfeatures/LFSiftPP.h

@@ -1,6 +1,6 @@
 /** 
 * @file LFSiftPP.h
-* @brief Sift++ interface
+* @brief Sift++ interface (with detector!)
 * @author Erik Rodner
 * @date 11/19/2007
 

+ 1 - 1
features/localfeatures/LFonHSG.h

@@ -83,7 +83,7 @@ namespace OBJREC
 			int extractFeatures ( const NICE::Image & img, NICE::VVector & features, NICE::VVector & positions ) const;
 
 			//! Extract the descriptor-Values from a given color-Image.
-		        int extractFeatures ( const NICE::ColorImage & cimg, NICE::VVector & features, NICE::VVector & positions ) const;
+      int extractFeatures ( const NICE::ColorImage & cimg, NICE::VVector & features, NICE::VVector & positions ) const;
 			
 			//! Visualisierung
 			void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;

+ 1 - 1
features/localfeatures/LocalFeatureSift.h

@@ -1,6 +1,6 @@
 /** 
 * @file LocalFeatureSift.h
-* @brief local feature with sift
+* @brief local feature with sift (without detector)
 * @author Erik Rodner
 * @date 02/05/2008
 

+ 1 - 1
features/localfeatures/progs/sift-driver.cpp

@@ -385,7 +385,7 @@ main(int argc, char** argv)
 
     // check for argument consistency
     if(argc == 0) VL_THROW("No input image specfied.") ;
-    if(outputFilename.size() != 0 && (argc > 1 | binary)) {
+    if(outputFilename.size() != 0 && ((argc > 1) | binary)) {
       VL_THROW("--output cannot be used with multiple images or --binary.") ;
     }
 

+ 71 - 30
features/simplefeatures/FCCodebookHistBin.h

@@ -1,6 +1,6 @@
 /** 
 * @file FCCodebookHistBin.h
-* @brief create features with codebook
+* @brief create features with a predefined codebook
 * @author Erik Rodner
 * @date 02/05/2008
 
@@ -24,45 +24,86 @@ namespace OBJREC {
 class FCCodebookHistBin : public FeatureFactory
 {
 
-    protected:
-	int n_method;
+  protected:
+    //! normalization method used (enum type)
+    int n_method;
 
-	const LocalFeatureRepresentation *lfrep;
-	const Codebook *codebook;
+    //! local feature method
+  	const LocalFeatureRepresentation *lfrep;
 
-	void calcHistogram ( const NICE::VVector & features,
-			     NICE::Vector & histogram );
+    //! pointer to our codebook
+	  const Codebook *codebook;
 
-	void calcHistogram ( const NICE::VVector & features,
-			     NICE::Vector & histogram,
-			     NICE::Matrix & assignments);
+    void calcHistogram ( const NICE::VVector & features,
+             NICE::Vector & histogram );
 
-	void normalizeHistogram ( NICE::Vector & histogram );
+    void calcHistogram ( const NICE::VVector & features,
+             NICE::Vector & histogram,
+             NICE::Matrix & assignments);
 
-    public:
+  	void normalizeHistogram ( NICE::Vector & histogram );
+
+  public:
+    //! enum type used for normalization method
   	enum {
 	    NORMALIZE_RAW = 0,
 	    NORMALIZE_BINZERO,
 	    NORMALIZE_SUM,
 	    NORMALIZE_THRESH
-	};
-
-
-	/** simple constructor */
-	FCCodebookHistBin( const NICE::Config *conf,
-	    const LocalFeatureRepresentation *lfrep,
-	    const std::string & normalizationMethod,
-	    const Codebook *codebook );
-      
-	/** simple destructor */
-	virtual ~FCCodebookHistBin();
-	
-	int convert ( const NICE::Image & img, NICE::Vector & vec );
-	
-	int calcAssignments ( const NICE::VVector & features, NICE::Vector & vec, NICE::Matrix & assignments );
-
-	void setNormalizationMethod ( int normalizationMethod );
-	int getNormalizationMethod () const;
+	  };
+
+
+    /**
+    * @brief standard constructor 
+    *
+    * @param conf pointer to a Config object with some parameter settings (currently not used)
+    * @param lfrep local feature extraction method (keep the pointer!)
+    * @param normalizationMethod name of the normalization method (sum, binzero, raw, thresh)
+    * @param codebook pointer to the codebook (keep the pointer!)
+    */
+    FCCodebookHistBin( const NICE::Config *conf,
+        const LocalFeatureRepresentation *lfrep,
+        const std::string & normalizationMethod,
+        const Codebook *codebook );
+        
+    /** simple destructor */
+    virtual ~FCCodebookHistBin();
+    
+    /**
+    * @brief calculate a BoV histogram vector (no local information, only global)
+    *
+    * @param img input image
+    * @param vec resulting feature vector
+    *
+    * @return -1 if something fails (no local features found for example) and zero if everything was okay 
+    */
+    int convert ( const NICE::Image & img, NICE::Vector & vec );
+    
+    /**
+    * @brief calculate a BoV histogram vector and also store the assignments of each local feature to a BoV cluster (codebook element)
+    *
+    * @param features input local features (size is N)
+    * @param vec resulting BoV feature vector
+    * @param assignments assignments of local features to BoV clusters given as a 3xN matrix, with assignments(0,*) representing the distance
+    * of a local feature to the nearest BoV cluster, assignments(1,*) storing the BoV cluster index, and assignments(2,*) being the index of the local feature
+    *
+    * @return 
+    */
+    int calcAssignments ( const NICE::VVector & features, NICE::Vector & vec, NICE::Matrix & assignments );
+
+    /**
+    * @brief set the type of the normalization method (see the enum of the class)
+    *
+    * @param normalizationMethod see enum type
+    */
+    void setNormalizationMethod ( int normalizationMethod );
+
+    /**
+    * @brief get the currently used normalization method
+    *
+    * @return see enum type
+    */
+    int getNormalizationMethod () const;
      
 };
 

+ 669 - 669
math/cluster/GMM.cpp

@@ -17,760 +17,760 @@ using namespace std;
 
 GMM::GMM()
 {
-	gaussians = 3;
-	maxiter = 200;
-	featsperclass = 0;
-	tau = 10.0;
-	srand ( time (NULL) );
-	comp = false;
+  gaussians = 3;
+  maxiter = 200;
+  featsperclass = 0;
+  tau = 10.0;
+  srand ( time ( NULL ) );
+  comp = false;
 }
 
-GMM::GMM(int _gaussians):gaussians(_gaussians)
+GMM::GMM ( int _gaussians ) : gaussians ( _gaussians )
 {
-	maxiter = 200;
-	featsperclass = 0;
-	tau = 0.0;
-	srand ( time (NULL) );
-	pyramid = false;
-	comp = false;
+  maxiter = 200;
+  featsperclass = 0;
+  tau = 0.0;
+  srand ( time ( NULL ) );
+  pyramid = false;
+  comp = false;
 }
 
-GMM::GMM(const Config *conf, int _gaussians):gaussians(_gaussians)
+GMM::GMM ( const Config *conf, int _gaussians ) : gaussians ( _gaussians )
 {
-	this->conf = conf;
-	
-	if(gaussians < 2)
-		gaussians = conf->gI("GMM", "gaussians", 2 );
-		
-	maxiter = conf->gI("GMM", "maxiter", 200 );
-		
-	featsperclass = conf->gI("GMM", "featsperclass", 0 );
-	
-	tau = conf->gD("GMM", "tau", 100.0);
-	
-	pyramid = conf->gB("GMM", "pyramid", false);
-	
-	comp = false;
-	
-	srand ( time (NULL) );
+  this->conf = conf;
+
+  if ( gaussians < 2 )
+    gaussians = conf->gI ( "GMM", "gaussians", 2 );
+
+  maxiter = conf->gI ( "GMM", "maxiter", 200 );
+
+  featsperclass = conf->gI ( "GMM", "featsperclass", 0 );
+
+  tau = conf->gD ( "GMM", "tau", 100.0 );
+
+  pyramid = conf->gB ( "GMM", "pyramid", false );
+
+  comp = false;
+
+  srand ( time ( NULL ) );
 }
 
-void GMM::computeMixture(Examples examples)
+void GMM::computeMixture ( Examples examples )
 {
-	int fsize = (int)examples.size();
-	assert(fsize >= gaussians);
-	
-	dim = examples[0].second.vec->size();
-	
-	int samples = fsize;
-	if(featsperclass > 0)
-	{
-		samples = featsperclass*gaussians;
-		samples = std::min(samples, fsize);
-	}
-		
-	// Copy data in Matrix
-	VVector dataset;
-
-	cout << "reduced training data for GMM from " << fsize << " features to " << samples << " features.";
-	for(int i = 0; i < samples; i++)
-	{
-		int k = rand() % fsize;
-		NICE::Vector *vec = examples[k].second.vec;
-		dataset.push_back(*vec);
-	}
-	
-	computeMixture(dataset);
+  int fsize = ( int ) examples.size();
+  assert ( fsize >= gaussians );
+
+  dim = examples[0].second.vec->size();
+
+  int samples = fsize;
+  if ( featsperclass > 0 )
+  {
+    samples = featsperclass * gaussians;
+    samples = std::min ( samples, fsize );
+  }
+
+  // Copy data in Matrix
+  VVector dataset;
+
+  cout << "reduced training data for GMM from " << fsize << " features to " << samples << " features.";
+  for ( int i = 0; i < samples; i++ )
+  {
+    int k = rand() % fsize;
+    NICE::Vector *vec = examples[k].second.vec;
+    dataset.push_back ( *vec );
+  }
+
+  computeMixture ( dataset );
 }
 
-void GMM::computeMixture(const VVector &DataSet)
+void GMM::computeMixture ( const VVector &DataSet )
 {
-	// Learn the GMM model
-	assert(DataSet.size() >= (uint)gaussians);
-	//initEMkMeans(DataSet); // initialize the model
-	srand ( time (NULL) );
-	
-	bool poweroftwo = false;
-	int power = 1;
-	while(power <= gaussians)
-	{
-		if(gaussians == power)
-			poweroftwo = true;
-		power *= 2;
-	}
-	
-	if(poweroftwo && pyramid)
-	{
-		initEM(DataSet); // initialize the model
-		int g = 1;
-		
-		while(g <= gaussians)
-		{
-			cout << "g = " << g << endl;
-			doEM(DataSet, g);
-			
-			if(2*g <= gaussians)
-			{
-				for(int i = g; i < g*2; i++)
-				{
-					mu[i] = mu[i-g];
-					sparse_sigma[i] = sparse_sigma[i-g];
-					sparse_inv_sigma[i] = sparse_inv_sigma[i-g];
-					log_det_sigma[i] = log_det_sigma[i-g];
-					priors[i] = priors[i-g];
-					
-					double interval = 1.0;
-					for(int k = 0; k < (int)mu[i].size(); k++)
-					{
-						interval = mu[i][k];
-						interval = std::max(interval, 0.1);
-						double r = (interval*((double)rand()/(double)RAND_MAX))-interval/2.0;
-						mu[i][k] += r;
-					}
-				}
-			}
-			g *= 2;
-		}
-	}
-	else
-	{
-		initEMkMeans(DataSet); // initialize the model
-		doEM(DataSet, gaussians);
-	}
-	// performs EM
+  // Learn the GMM model
+  assert ( DataSet.size() >= ( uint ) gaussians );
+  //initEMkMeans(DataSet); // initialize the model
+  srand ( time ( NULL ) );
+
+  bool poweroftwo = false;
+  int power = 1;
+  while ( power <= gaussians )
+  {
+    if ( gaussians == power )
+      poweroftwo = true;
+    power *= 2;
+  }
+
+  if ( poweroftwo && pyramid )
+  {
+    initEM ( DataSet ); // initialize the model
+    int g = 1;
+
+    while ( g <= gaussians )
+    {
+      cout << "g = " << g << endl;
+      doEM ( DataSet, g );
+
+      if ( 2*g <= gaussians )
+      {
+        for ( int i = g; i < g*2; i++ )
+        {
+          mu[i] = mu[i-g];
+          sparse_sigma[i] = sparse_sigma[i-g];
+          sparse_inv_sigma[i] = sparse_inv_sigma[i-g];
+          log_det_sigma[i] = log_det_sigma[i-g];
+          priors[i] = priors[i-g];
+
+          double interval = 1.0;
+          for ( int k = 0; k < ( int ) mu[i].size(); k++ )
+          {
+            interval = mu[i][k];
+            interval = std::max ( interval, 0.1 );
+            double r = ( interval * ( ( double ) rand() / ( double ) RAND_MAX ) ) - interval / 2.0;
+            mu[i][k] += r;
+          }
+        }
+      }
+      g *= 2;
+    }
+  }
+  else
+  {
+    initEMkMeans ( DataSet ); // initialize the model
+    doEM ( DataSet, gaussians );
+  }
+  // performs EM
 }
 
-inline double diagDeterminant(const NICE::Vector &sparse_mat)
+inline double diagDeterminant ( const NICE::Vector &sparse_mat )
 {
-	double det = 1.0;
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		det *= sparse_mat[i];
-	}
-	
-	return det;
+  double det = 1.0;
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    det *= sparse_mat[i];
+  }
+
+  return det;
 }
 
-inline double logdiagDeterminant(const NICE::Vector &sparse_mat)
+inline double logdiagDeterminant ( const NICE::Vector &sparse_mat )
 {
-	double det = 0.0;
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		det += log(sparse_mat[i]);
-	}
+  double det = 0.0;
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    det += log ( sparse_mat[i] );
+  }
 
-	return det;
+  return det;
 }
 
-inline NICE::Vector diagInverse(const NICE::Vector &sparse_mat)
+inline NICE::Vector diagInverse ( const NICE::Vector &sparse_mat )
 {
-	NICE::Vector inv(sparse_mat.size());
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		inv[i] = 1.0/sparse_mat[i];
-	}
-	return inv;
+  NICE::Vector inv ( sparse_mat.size() );
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    inv[i] = 1.0 / sparse_mat[i];
+  }
+  return inv;
 }
 
-void GMM::initEMkMeans(const VVector &DataSet)
+void GMM::initEMkMeans ( const VVector &DataSet )
 {
-	/*init GMM with k-Means*/
-	KMeans k( gaussians );
-	VVector means;
-	vector<double> weights;
-	vector<int> assignment;
-	k.cluster ( DataSet, means, weights, assignment );
-	
-	int nData = DataSet.size();
-	this->dim = DataSet[0].size();
-	cdimval = dim*log(2*3.14159);
-	vector<int> pop(gaussians, 0);
-	priors.resize(gaussians);
-	mu = VVector(gaussians, dim);
-	log_det_sigma.clear();
-	vector<int> allk;
-	
-	NICE::Vector globmean(dim);
-	globmean.set(0.0);
-	
-	for(int n = 0; n < (int)DataSet.size(); n++) /* getting the max value for time */
-	{
-		globmean = globmean + DataSet[n];
-	}
-
-	globmean *= (1.0/nData);
-	
-	NICE::Vector sparse_globsigma;
-
-	sparse_globsigma.resize(dim);
-	sparse_globsigma.set(0.0);
-	
-	for(int i = 0; i < (int)DataSet.size(); i++) // Covariances updates
-	{
-		// nur diagonal Elemente berechnen
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = (DataSet[i][d] - globmean[d]);
-			sparse_globsigma[d] += diff*diff;
-		}
-	}
-	
-	sparse_globsigma *= (1.0/DataSet.size());
-	
-	for(int i = 0; i < gaussians; i++)
-	{
-		NICE::Vector _inv_sigma = diagInverse(sparse_globsigma);
-
-		sparse_sigma.push_back(sparse_globsigma);
-		sparse_inv_sigma.push_back(_inv_sigma);
-		log_det_sigma.push_back(logdiagDeterminant(sparse_globsigma));
-		mu[i] = means[i];
-		//priors[i]=1.0/(double)gaussians; // set equi-probables states 
-		priors[i]=weights[i]; // set kMeans weights 
-	}
+  /*init GMM with k-Means*/
+  KMeans k ( gaussians );
+  VVector means;
+  vector<double> weights;
+  vector<int> assignment;
+  k.cluster ( DataSet, means, weights, assignment );
+
+  int nData = DataSet.size();
+  this->dim = DataSet[0].size();
+  cdimval = dim * log ( 2 * 3.14159 );
+  vector<int> pop ( gaussians, 0 );
+  priors.resize ( gaussians );
+  mu = VVector ( gaussians, dim );
+  log_det_sigma.clear();
+  vector<int> allk;
+
+  NICE::Vector globmean ( dim );
+  globmean.set ( 0.0 );
+
+  for ( int n = 0; n < ( int ) DataSet.size(); n++ ) /* getting the max value for time */
+  {
+    globmean = globmean + DataSet[n];
+  }
+
+  globmean *= ( 1.0 / nData );
+
+  NICE::Vector sparse_globsigma;
+
+  sparse_globsigma.resize ( dim );
+  sparse_globsigma.set ( 0.0 );
+
+  for ( int i = 0; i < ( int ) DataSet.size(); i++ ) // Covariances updates
+  {
+    // nur diagonal Elemente berechnen
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = ( DataSet[i][d] - globmean[d] );
+      sparse_globsigma[d] += diff * diff;
+    }
+  }
+
+  sparse_globsigma *= ( 1.0 / DataSet.size() );
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    NICE::Vector _inv_sigma = diagInverse ( sparse_globsigma );
+
+    sparse_sigma.push_back ( sparse_globsigma );
+    sparse_inv_sigma.push_back ( _inv_sigma );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_globsigma ) );
+    mu[i] = means[i];
+    //priors[i]=1.0/(double)gaussians; // set equi-probables states
+    priors[i] = weights[i]; // set kMeans weights
+  }
 }
 
-void GMM::initEM(const VVector &DataSet)
+void GMM::initEM ( const VVector &DataSet )
 {
 
-	/* init the GaussianMixture by using randomized meanvectors */
-	int nData = DataSet.size();
-	this->dim = DataSet[0].size();
-	cdimval = dim*log(2*3.14159);
-	vector<int> pop(gaussians, 0);
-	priors.resize(gaussians);
-	mu = VVector(gaussians, dim);
-	log_det_sigma.clear();
-	vector<int> allk;
-	
-	NICE::Vector globmean(dim);
-	globmean.set(0.0);
-	
-	for(int n = 0; n < (int)DataSet.size(); n++) /* getting the max value for time */
-	{
-		globmean = globmean + DataSet[n];
-	}
-
-	globmean *= (1.0/nData);
-	
-	NICE::Vector sparse_globsigma;
-
-	sparse_globsigma.resize(dim);
-	sparse_globsigma.set(0.0);
-	
-	for(int i = 0; i < (int)DataSet.size(); i++) // Covariances updates
-	{
-		// nur diagonal Elemente berechnen
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = (DataSet[i][d] - globmean[d]);
-			sparse_globsigma[d] += diff*diff;
-		}
-	}
-	
-	sparse_globsigma *= (1.0/DataSet.size());
-	
-	for(int i = 0; i < gaussians; i++)
-	{
-		priors[i]=1.0/(double)gaussians; // set equi-probables states 
-		NICE::Vector _inv_sigma = diagInverse(sparse_globsigma);
-
-		sparse_sigma.push_back(sparse_globsigma);
-		sparse_inv_sigma.push_back(_inv_sigma);
-		log_det_sigma.push_back(logdiagDeterminant(sparse_globsigma));
-		bool newv = false;
-		int k;
-		while(!newv)
-		{
-			newv = true;
-			k = rand() % nData;
-		
-			for(int nk = 0; nk < (int)allk.size(); nk++)
-				if(allk[nk] == k)
-				{
-					newv = false;
-				}
-			if(newv)
-				allk.push_back(k);
-		}
-		mu[i] = DataSet[k];
-	}
+  /* init the GaussianMixture by using randomized meanvectors */
+  int nData = DataSet.size();
+  this->dim = DataSet[0].size();
+  cdimval = dim * log ( 2 * 3.14159 );
+  vector<int> pop ( gaussians, 0 );
+  priors.resize ( gaussians );
+  mu = VVector ( gaussians, dim );
+  log_det_sigma.clear();
+  vector<int> allk;
+
+  NICE::Vector globmean ( dim );
+  globmean.set ( 0.0 );
+
+  for ( int n = 0; n < ( int ) DataSet.size(); n++ ) /* getting the max value for time */
+  {
+    globmean = globmean + DataSet[n];
+  }
+
+  globmean *= ( 1.0 / nData );
+
+  NICE::Vector sparse_globsigma;
+
+  sparse_globsigma.resize ( dim );
+  sparse_globsigma.set ( 0.0 );
+
+  for ( int i = 0; i < ( int ) DataSet.size(); i++ ) // Covariances updates
+  {
+    // nur diagonal Elemente berechnen
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = ( DataSet[i][d] - globmean[d] );
+      sparse_globsigma[d] += diff * diff;
+    }
+  }
+
+  sparse_globsigma *= ( 1.0 / DataSet.size() );
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    priors[i] = 1.0 / ( double ) gaussians; // set equi-probables states
+    NICE::Vector _inv_sigma = diagInverse ( sparse_globsigma );
+
+    sparse_sigma.push_back ( sparse_globsigma );
+    sparse_inv_sigma.push_back ( _inv_sigma );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_globsigma ) );
+    bool newv = false;
+    int k;
+    while ( !newv )
+    {
+      newv = true;
+      k = rand() % nData;
+
+      for ( int nk = 0; nk < ( int ) allk.size(); nk++ )
+        if ( allk[nk] == k )
+        {
+          newv = false;
+        }
+      if ( newv )
+        allk.push_back ( k );
+    }
+    mu[i] = DataSet[k];
+  }
 }
 
-inline void sumRow(NICE::Matrix mat, NICE::Vector &res)
+inline void sumRow ( NICE::Matrix mat, NICE::Vector &res )
 {
-	int row = mat.rows();
-	int column = mat.cols();
-	res =NICE::Vector(column);
-	res.set(1e-5f);
+  int row = mat.rows();
+  int column = mat.cols();
+  res = NICE::Vector ( column );
+  res.set ( 1e-5f );
 //#pragma omp parallel for
-	for(int i = 0; i < column; i++){
-		for(int j = 0; j < row; j++){
-			res[i] += mat(j, i);
-		}
-	}
+  for ( int i = 0; i < column; i++ ) {
+    for ( int j = 0; j < row; j++ ) {
+      res[i] += mat ( j, i );
+    }
+  }
 }
 
-double GMM::logpdfState(const NICE::Vector &Vin,int state)
+double GMM::logpdfState ( const NICE::Vector &Vin, int state )
 {
-	/* get the probability density for a given state and a given vector */
-	double p;
-	NICE::Vector dif;
-		
-	dif = Vin;
-	dif -= mu[state];
-		
-	p = 0.0;
-	for(int i = 0; i < (int)dif.size(); i++)
-	{
-		p += dif[i] * dif[i] * sparse_inv_sigma[state][i];
-	}
-	
-	p = -0.5*(p + cdimval + log_det_sigma[state]);
-	return p;
+  /* get the probability density for a given state and a given vector */
+  double p;
+  NICE::Vector dif;
+
+  dif = Vin;
+  dif -= mu[state];
+
+  p = 0.0;
+  for ( int i = 0; i < ( int ) dif.size(); i++ )
+  {
+    p += dif[i] * dif[i] * sparse_inv_sigma[state][i];
+  }
+
+  p = -0.5 * ( p + cdimval + log_det_sigma[state] );
+  return p;
 }
 
-int GMM::doEM(const VVector &DataSet, int nbgaussians)
+int GMM::doEM ( const VVector &DataSet, int nbgaussians )
 {
   /* perform Expectation/Maximization on the given Dataset :
-	Matrix DataSet(nSamples,Dimensions).
-	The GaussianMixture Object must be initialised before 
-	(see initEM or initEMkMeans methods ) */
-	
+  Matrix DataSet(nSamples,Dimensions).
+  The GaussianMixture Object must be initialised before
+  (see initEM or initEMkMeans methods ) */
+
 #ifdef DEBUG
-	cerr << "GMM::start EM" << endl;
-#endif	
-	
-	int nData = DataSet.size();
-	int iter = 0;
-	double log_lik;
-	double log_lik_threshold = 1e-6f;
-	double log_lik_old = -1e10f;
-
-	NICE::Matrix unity(dim,dim,0.0);
-	for(int k = 0; k < dim; k++) 
-		unity(k, k)=1.0;
-	
-	//EM loop
-	while(true)
-	{
+  cerr << "GMM::start EM" << endl;
+#endif
+
+  int nData = DataSet.size();
+  int iter = 0;
+  double log_lik;
+  double log_lik_threshold = 1e-6f;
+  double log_lik_old = -1e10f;
+
+  NICE::Matrix unity ( dim, dim, 0.0 );
+  for ( int k = 0; k < dim; k++ )
+    unity ( k, k ) = 1.0;
+
+  //EM loop
+  while ( true )
+  {
 #ifdef DEBUGGMM
-		cerr << "GMM::EM: iteration: " << iter << endl;
+    cerr << "GMM::EM: iteration: " << iter << endl;
 #endif
-		
-		vector<double> sum_p;
-		sum_p.resize(nData);
-
-		for(int i = 0; i < nData; i++)
-		{
-			sum_p[i] = 0.0;
-		}
-	
-		NICE::Matrix pxi(nData,gaussians);
-		pxi.set(0.0);
-		NICE::Matrix pix(nData,gaussians);
-		pix.set(0.0);
-		NICE::Vector E;
-		
-		iter++;
-		if (iter>maxiter){
-			cerr << "EM stops here. Max number of iterations (" << maxiter << ") has been reached." << endl;
-			return iter;
-		}
-
-		double sum_log = 0.0; 
-		
-    	// computing expectation
-		double maxp = -numeric_limits<double>::max();
-		vector<double> maxptmp(nData,-numeric_limits<double>::max());
+
+    vector<double> sum_p;
+    sum_p.resize ( nData );
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_p[i] = 0.0;
+    }
+
+    NICE::Matrix pxi ( nData, gaussians );
+    pxi.set ( 0.0 );
+    NICE::Matrix pix ( nData, gaussians );
+    pix.set ( 0.0 );
+    NICE::Vector E;
+
+    iter++;
+    if ( iter > maxiter ) {
+      cerr << "EM stops here. Max number of iterations (" << maxiter << ") has been reached." << endl;
+      return iter;
+    }
+
+    double sum_log = 0.0;
+
+    // computing expectation
+    double maxp = -numeric_limits<double>::max();
+    vector<double> maxptmp ( nData, -numeric_limits<double>::max() );
 #pragma omp parallel for
-		for(int i = 0; i < nData; i++)
-		{
-			for(int j = 0; j < nbgaussians; j++)
-			{
-				double p = logpdfState(DataSet[i],j); // log(P(x|i))
-				maxptmp[i] = std::max(maxptmp[i], p);
-				pxi(i, j) = p;
-			}
-		}
-		
-		for(int i = 0; i < nData; i++)
-		{
-			maxp = std::max(maxp, maxptmp[i]);
-		}
+    for ( int i = 0; i < nData; i++ )
+    {
+      for ( int j = 0; j < nbgaussians; j++ )
+      {
+        double p = logpdfState ( DataSet[i], j ); // log(P(x|i))
+        maxptmp[i] = std::max ( maxptmp[i], p );
+        pxi ( i, j ) = p;
+      }
+    }
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      maxp = std::max ( maxp, maxptmp[i] );
+    }
 
 #pragma omp parallel for
-		for(int i = 0; i < nData; i++)
-		{
-			sum_p[i] = 0.0;
-			for(int j = 0; j < nbgaussians; j++)
-			{
-				double p = pxi(i, j) - maxp; // log(P(x|i))
-				p = exp(p); // P(x|i)
-				
-				if(p < 1e-40)
-					p = 1e-40;
-
-				pxi(i, j) = p;
-				sum_p[i] += p*priors[j];
-			} 
-		}
-			
-		for(int i = 0; i < nData; i++)
-		{
-			sum_log += log(sum_p[i]);
-		}
-		
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_p[i] = 0.0;
+      for ( int j = 0; j < nbgaussians; j++ )
+      {
+        double p = pxi ( i, j ) - maxp; // log(P(x|i))
+        p = exp ( p ); // P(x|i)
+
+        if ( p < 1e-40 )
+          p = 1e-40;
+
+        pxi ( i, j ) = p;
+        sum_p[i] += p * priors[j];
+      }
+    }
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_log += log ( sum_p[i] );
+    }
+
 #pragma omp parallel for
-		for(int j = 0; j < nbgaussians; j++)
-		{
-			for(int i = 0; i < nData; i++)
-			{
-				pix(i, j) = (pxi(i, j)*priors[j])/sum_p[i]; // then P(i|x)			
-			}   
-		}
-
-		// here we compute the log likehood 
-		log_lik = sum_log/nData; 
-#ifdef DEBUGGMM	
-		cout << "diff: " << fabs((log_lik/log_lik_old)-1) << " thresh: " << log_lik_threshold << " sum: " << sum_log <<  endl;
-		//cout << "logold: " << log_lik_old << " lognew: " << log_lik << endl;
+    for ( int j = 0; j < nbgaussians; j++ )
+    {
+      for ( int i = 0; i < nData; i++ )
+      {
+        pix ( i, j ) = ( pxi ( i, j ) * priors[j] ) / sum_p[i]; // then P(i|x)
+      }
+    }
+
+    // here we compute the log likehood
+    log_lik = sum_log / nData;
+#ifdef DEBUGGMM
+    cout << "diff: " << fabs ( ( log_lik / log_lik_old ) - 1 ) << " thresh: " << log_lik_threshold << " sum: " << sum_log <<  endl;
+    //cout << "logold: " << log_lik_old << " lognew: " << log_lik << endl;
 #endif
-		
-		if(fabs((log_lik/log_lik_old)-1) < log_lik_threshold )
-		{
-			//if log likehood hasn't move enough, the algorithm has converged, exiting the loop 
-			return iter;
-		}
-
-		log_lik_old = log_lik;
-
-		// Update Step
-		sumRow(pix,E);
-		
+
+    if ( fabs ( ( log_lik / log_lik_old ) - 1 ) < log_lik_threshold )
+    {
+      //if log likehood hasn't move enough, the algorithm has converged, exiting the loop
+      return iter;
+    }
+
+    log_lik_old = log_lik;
+
+    // Update Step
+    sumRow ( pix, E );
+
 #pragma omp parallel for
-		for(int j = 0; j < nbgaussians; j++) 
-		{
-			priors[j] = (E[j]+tau)/(nData+tau*nbgaussians); // new priors 
-
-			NICE::Vector tmu(dim);
-			tmu.set(0.0);
-
-			NICE::Vector sparse_tmsigma(dim);
-			sparse_tmsigma.set(0.0);
-
-			for(int i = 0; i < nData; i++) // Means update loop
-			{
-				tmu = tmu + (DataSet[i]*pix(i,j));
-			}
-									
-			NICE::Vector tmu2 = mu[j];
-			mu[j] = tmu + tau*tmu2;
-			mu[j] = mu[j]*(1.0/(E[j]+tau));
-			
-			for(int i = 0; i < nData; i++) // Covariances updates
-			{	
-				// nur diagonal Elemente berechnen
-				for(int d = 0; d < dim; d++)
-				{
-					sparse_tmsigma[d] += DataSet[i][d]*DataSet[i][d]*pix(i, j);
-				}
-			}
-			
-			NICE::Vector sparse_tmsigma2(dim);
-			for(int d = 0; d < dim; d++)
-			{
-				sparse_tmsigma[d] += 1e-5f;
-				sparse_tmsigma2[d] = sparse_sigma[j][d]+tmu2[d]*tmu2[d];
-				sparse_sigma[j][d] = (sparse_tmsigma[d]+tau*sparse_tmsigma2[d])/(E[j]+tau)-(mu[j][d]*mu[j][d]);
-			}				
-			sparse_inv_sigma[j] = diagInverse(sparse_sigma[j]);
-				
-			log_det_sigma[j] = logdiagDeterminant(sparse_sigma[j]);
-		}
-		if(comp)
-		{
-			double dist = compare();
-			cout << "dist for iteration " << iter << endl;
-			cout << "d: " << dist << endl;
-		}	
-	}
+    for ( int j = 0; j < nbgaussians; j++ )
+    {
+      priors[j] = ( E[j] + tau ) / ( nData + tau * nbgaussians ); // new priors
+
+      NICE::Vector tmu ( dim );
+      tmu.set ( 0.0 );
+
+      NICE::Vector sparse_tmsigma ( dim );
+      sparse_tmsigma.set ( 0.0 );
+
+      for ( int i = 0; i < nData; i++ ) // Means update loop
+      {
+        tmu = tmu + ( DataSet[i] * pix ( i, j ) );
+      }
+
+      NICE::Vector tmu2 = mu[j];
+      mu[j] = tmu + tau * tmu2;
+      mu[j] = mu[j] * ( 1.0 / ( E[j] + tau ) );
+
+      for ( int i = 0; i < nData; i++ ) // Covariances updates
+      {
+        // nur diagonal Elemente berechnen
+        for ( int d = 0; d < dim; d++ )
+        {
+          sparse_tmsigma[d] += DataSet[i][d] * DataSet[i][d] * pix ( i, j );
+        }
+      }
+
+      NICE::Vector sparse_tmsigma2 ( dim );
+      for ( int d = 0; d < dim; d++ )
+      {
+        sparse_tmsigma[d] += 1e-5f;
+        sparse_tmsigma2[d] = sparse_sigma[j][d] + tmu2[d] * tmu2[d];
+        sparse_sigma[j][d] = ( sparse_tmsigma[d] + tau * sparse_tmsigma2[d] ) / ( E[j] + tau ) - ( mu[j][d] * mu[j][d] );
+      }
+      sparse_inv_sigma[j] = diagInverse ( sparse_sigma[j] );
+
+      log_det_sigma[j] = logdiagDeterminant ( sparse_sigma[j] );
+    }
+    if ( comp )
+    {
+      double dist = compare();
+      cout << "dist for iteration " << iter << endl;
+      cout << "d: " << dist << endl;
+    }
+  }
 #ifdef DEBUG
-	cerr << "GMM::finished EM after " << iter << " iterations" << endl;
+  cerr << "GMM::finished EM after " << iter << " iterations" << endl;
 #endif
-	return iter;
+  return iter;
 }
 
-int GMM::getBestClass(const NICE::Vector &v, double *bprob)
+int GMM::getBestClass ( const NICE::Vector &v, double *bprob )
 {
-	int bestclass = 0;
-	double maxprob = logpdfState(v,0)+log(priors[0]);  // log(P(x|i))
-	
-	for(int i = 1; i < gaussians; i++)
-	{
-		double prob = logpdfState(v,i)+log(priors[i]);  // log(P(x|i))
-		
-		if(prob > maxprob)
-		{
-			maxprob = prob;
-			bestclass = i;
-		}
-	}
-	
-	if(bprob != NULL)
-		*bprob = maxprob;
-	
-	return bestclass;
+  int bestclass = 0;
+  double maxprob = logpdfState ( v, 0 ) + log ( priors[0] );  // log(P(x|i))
+
+  for ( int i = 1; i < gaussians; i++ )
+  {
+    double prob = logpdfState ( v, i ) + log ( priors[i] );  // log(P(x|i))
+
+    if ( prob > maxprob )
+    {
+      maxprob = prob;
+      bestclass = i;
+    }
+  }
+
+  if ( bprob != NULL )
+    *bprob = maxprob;
+
+  return bestclass;
 }
-		
-void GMM::getProbs(const NICE::Vector &vin, SparseVector &outprobs)
+
+void GMM::getProbs ( const NICE::Vector &vin, SparseVector &outprobs )
 {
-	outprobs.clear();
-	outprobs.setDim(gaussians);
-	Vector probs;
-	getProbs(vin, probs);
-	for(int i = 0; i < gaussians; i++)
-	{
-		if(probs[i] > 1e-7f )
-			outprobs[i] = probs[i];
-	}
+  outprobs.clear();
+  outprobs.setDim ( gaussians );
+  Vector probs;
+  getProbs ( vin, probs );
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    if ( probs[i] > 1e-7f )
+      outprobs[i] = probs[i];
+  }
 }
-		
-void GMM::getProbs(const NICE::Vector &vin, Vector &outprobs)
+
+void GMM::getProbs ( const NICE::Vector &vin, Vector &outprobs )
 {
-	Vector probs;
-	probs.resize(gaussians);
-	probs.set(0.0);
-		
-	double probsum = 0.0;
-	double maxp = -numeric_limits<double>::max();
-	for(int i = 0; i < gaussians; i++)
-	{	
-		probs[i] = logpdfState(vin, i) + log(priors[i]);  // log(P(x|i))
-		maxp = std::max(maxp, probs[i]);		
-	}
-		
-	for(int i = 0; i < gaussians; i++)
-	{
-		probs[i] -= maxp;
-		probs[i] = exp(probs[i]);
-		probsum += probs[i];
-	}
-
-	// normalize probs
+  Vector probs;
+  probs.resize ( gaussians );
+  probs.set ( 0.0 );
+
+  double probsum = 0.0;
+  double maxp = -numeric_limits<double>::max();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] = logpdfState ( vin, i ) + log ( priors[i] );  // log(P(x|i))
+    maxp = std::max ( maxp, probs[i] );
+  }
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] -= maxp;
+    probs[i] = exp ( probs[i] );
+    probsum += probs[i];
+  }
+
+  // normalize probs
 #pragma omp parallel for
-	for(int i = 0; i < gaussians; i++)
-	{
-		probs[i] /= probsum;
-	}
-	outprobs = probs;
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] /= probsum;
+  }
+  outprobs = probs;
 }
 
-void GMM::getFisher(const NICE::Vector &vin, SparseVector &outprobs)
+void GMM::getFisher ( const NICE::Vector &vin, SparseVector &outprobs )
 {
-	int size = gaussians*2*dim;
-	outprobs.clear();
-	outprobs.setDim(size);
-	
-	int counter = 0;
-	
-	NICE::Vector classprobs;
-	classprobs.resize(gaussians);
-	classprobs.set(0.0);
-
-	double maxp = -numeric_limits<double>::max();
-	for(int i = 0; i < gaussians; i++)
-	{
-		classprobs[i] = logpdfState(vin, i) + log(priors[i]);  // log(P(x|i))
-
-		maxp = std::max(maxp, classprobs[i]);
-	}
-
-	for(int i = 0; i < gaussians; i++)
-	{
-		double p = classprobs[i] - maxp;
-		
-		p = exp(p);
-		
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = vin[d]-mu[i][d];
-			
-			double sigma2 = sparse_sigma[i][d]*sparse_sigma[i][d];
-			double sigma3 = sigma2*sparse_sigma[i][d];
-			double normmu = sqrt(priors[i]/sigma2);
-			double normsig = sqrt((2.0*priors[i])/sigma2);
-			
-			double gradmu = (p * (diff/sigma2))/normmu;
-			double gradsig = (p * ((diff*diff)/sigma3 - 1.0/sparse_sigma[i][d])) /normsig;
-			if(fabs(gradmu) > 1e-7f)
-				outprobs[counter] = gradmu;
-			counter++;
-			
-			if(fabs(gradsig) > 1e-7f)
-				outprobs[counter] = gradsig;
-			counter++;
-		}
-	}
+  int size = gaussians * 2 * dim;
+  outprobs.clear();
+  outprobs.setDim ( size );
+
+  int counter = 0;
+
+  NICE::Vector classprobs;
+  classprobs.resize ( gaussians );
+  classprobs.set ( 0.0 );
+
+  double maxp = -numeric_limits<double>::max();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    classprobs[i] = logpdfState ( vin, i ) + log ( priors[i] );  // log(P(x|i))
+
+    maxp = std::max ( maxp, classprobs[i] );
+  }
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    double p = classprobs[i] - maxp;
+
+    p = exp ( p );
+
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = vin[d] - mu[i][d];
+
+      double sigma2 = sparse_sigma[i][d] * sparse_sigma[i][d];
+      double sigma3 = sigma2 * sparse_sigma[i][d];
+      double normmu = sqrt ( priors[i] / sigma2 );
+      double normsig = sqrt ( ( 2.0 * priors[i] ) / sigma2 );
+
+      double gradmu = ( p * ( diff / sigma2 ) ) / normmu;
+      double gradsig = ( p * ( ( diff * diff ) / sigma3 - 1.0 / sparse_sigma[i][d] ) ) / normsig;
+      if ( fabs ( gradmu ) > 1e-7f )
+        outprobs[counter] = gradmu;
+      counter++;
+
+      if ( fabs ( gradsig ) > 1e-7f )
+        outprobs[counter] = gradsig;
+      counter++;
+    }
+  }
 }
 
 void GMM::cluster ( const VVector & features, VVector & prototypes, vector<double> & weights, vector<int> & assignment )
 {
-	computeMixture(features);
-
-	prototypes.clear();
-	weights.clear();
-	assignment.clear();
-
-	for(int i = 0; i < (int)features.size(); i++)
-	{
-		int c = getBestClass(features[i]);
-		assignment.push_back(c);
-		
-		weights.push_back(priors[c]);
-	}
-	for(int c = 0; c < gaussians; c++)
-		prototypes.push_back(mu[c]);
-	
-	cout << "tau: " << tau << endl;
+  computeMixture ( features );
+
+  prototypes.clear();
+  weights.clear();
+  assignment.clear();
+
+  for ( int i = 0; i < ( int ) features.size(); i++ )
+  {
+    int c = getBestClass ( features[i] );
+    assignment.push_back ( c );
+
+    weights.push_back ( priors[c] );
+  }
+  for ( int c = 0; c < gaussians; c++ )
+    prototypes.push_back ( mu[c] );
+
+  cout << "tau: " << tau << endl;
 }
 
-void GMM::saveData(const std::string filename)
+void GMM::saveData ( const std::string filename )
 {
-	ofstream fout( filename.c_str() );
-
-	fout << gaussians << " " << dim << endl;
-	
-	mu >> fout;
-	fout << endl;
-			
-	for(int n = 0; n < gaussians; n++)
-	{
-		fout << sparse_sigma[n] << endl;
-	}
-	
-	for(int n = 0; n < gaussians; n++)
-	{
-		fout << priors[n] << " ";
-	}
-
-	fout.close();
+  ofstream fout ( filename.c_str() );
+
+  fout << gaussians << " " << dim << endl;
+
+  mu >> fout;
+  fout << endl;
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    fout << sparse_sigma[n] << endl;
+  }
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    fout << priors[n] << " ";
+  }
+
+  fout.close();
 }
 
-bool GMM::loadData(const std::string filename)
+bool GMM::loadData ( const std::string filename )
 {
-	cerr << "read GMM Data" << endl;
-	ifstream fin( filename.c_str() );
-
-	if(fin.fail())
-	{
-		cerr << "GMM: Datei " << filename << " nicht gefunden!" << endl;
-		return false;
-	}
-
-	fin >> gaussians;
-	fin >> dim;
-	cdimval = log(pow(2*3.14159,dim));
-	mu.clear();
-
-	for(int i = 0; i < gaussians; i++)
-	{
-		NICE::Vector tmp;
-		fin >> tmp;
-		mu.push_back(tmp);
-	}
-	
-	log_det_sigma.clear();
-
-	for(int n = 0; n < gaussians; n++)
-	{
-		NICE::Matrix _sigma;
-		NICE::Vector _sparse_sigma;
-		
-		_sparse_sigma =NICE::Vector(dim);
-		fin >> _sparse_sigma;
-		sparse_sigma.push_back(_sparse_sigma);
-				
-		sparse_inv_sigma.push_back(diagInverse(sparse_sigma[n]));
-		log_det_sigma.push_back(logdiagDeterminant(sparse_sigma[n]));
-	}
-
-	for(int n = 0; n < gaussians; n++)
-	{
-		double tmpd;
-		fin >> tmpd;
-		priors.push_back(tmpd);
-	}
-	fin.close();
-
-	cerr << "reading GMM Data finished" << endl;
-	return true;
+  cerr << "read GMM Data" << endl;
+  ifstream fin ( filename.c_str() );
+
+  if ( fin.fail() )
+  {
+    cerr << "GMM: Datei " << filename << " nicht gefunden!" << endl;
+    return false;
+  }
+
+  fin >> gaussians;
+  fin >> dim;
+  cdimval = log ( pow ( 2 * 3.14159, dim ) );
+  mu.clear();
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    NICE::Vector tmp;
+    fin >> tmp;
+    mu.push_back ( tmp );
+  }
+
+  log_det_sigma.clear();
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    NICE::Matrix _sigma;
+    NICE::Vector _sparse_sigma;
+
+    _sparse_sigma = NICE::Vector ( dim );
+    fin >> _sparse_sigma;
+    sparse_sigma.push_back ( _sparse_sigma );
+
+    sparse_inv_sigma.push_back ( diagInverse ( sparse_sigma[n] ) );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_sigma[n] ) );
+  }
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    double tmpd;
+    fin >> tmpd;
+    priors.push_back ( tmpd );
+  }
+  fin.close();
+
+  cerr << "reading GMM Data finished" << endl;
+  return true;
 }
 
-void GMM::getParams(VVector &mean, VVector &sSigma, vector<double> &p)
+void GMM::getParams ( VVector &mean, VVector &sSigma, vector<double> &p )
 {
-	mean = mu;
-	sSigma.resize(gaussians);
-	p.clear();
-	for(int i = 0; i < gaussians; i++)
-	{
-		sSigma[i] = sparse_sigma[i];
-		p.push_back(priors[i]);
-	}
+  mean = mu;
+  sSigma.resize ( gaussians );
+  p.clear();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    sSigma[i] = sparse_sigma[i];
+    p.push_back ( priors[i] );
+  }
 }
 
-void GMM::setCompareGM(VVector mean, VVector sSigma, vector<double> p)
+void GMM::setCompareGM ( VVector mean, VVector sSigma, vector<double> p )
 {
-	mu2 = mean;
-	sparse_sigma2 = sSigma;
-	priors2 = vector<double>(p);
+  mu2 = mean;
+  sparse_sigma2 = sSigma;
+  priors2 = vector<double> ( p );
 }
-		
-double GMM::kPPK(NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p)
+
+double GMM::kPPK ( NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p )
 {
-	double d = mu1.size();
-	
-	double det1 = 1.0;
-	double det2 = 1.0;
-	double det3 = 1.0;
-	double eval = 0.0;
-	for(int i = 0; i < d; i++)
-	{
-		det1 *= sigma1[i];
-		det2 *= sigma2[i];
-		double sigma = 1.0/((1.0/sigma1[i]+1.0/sigma2[i])*p);
-		det3 *= sigma;
-		double mu = p*(mu1[i]*sigma1[i]+mu2[i]*sigma2[i]);
-		eval += 0.5*mu*sigma*mu - (p*mu1[i]*mu1[i])/(2.0*sigma1[i]) - (p*mu2[i]*mu2[i]) / (2.0*sigma2[i]);
-	}
-	
-	return (pow(2.0*M_PI, ((1.0-2.0*p)*d)/2.0) * pow(det1, -p/2.0) * pow(det2, -p/2.0) * pow(det3, 0.5) * exp(eval));
+  double d = mu1.size();
+
+  double det1 = 1.0;
+  double det2 = 1.0;
+  double det3 = 1.0;
+  double eval = 0.0;
+  for ( int i = 0; i < d; i++ )
+  {
+    det1 *= sigma1[i];
+    det2 *= sigma2[i];
+    double sigma = 1.0 / ( ( 1.0 / sigma1[i] + 1.0 / sigma2[i] ) * p );
+    det3 *= sigma;
+    double mu = p * ( mu1[i] * sigma1[i] + mu2[i] * sigma2[i] );
+    eval += 0.5 * mu * sigma * mu - ( p * mu1[i] * mu1[i] ) / ( 2.0 * sigma1[i] ) - ( p * mu2[i] * mu2[i] ) / ( 2.0 * sigma2[i] );
+  }
+
+  return ( pow ( 2.0*M_PI, ( ( 1.0 - 2.0*p ) *d ) / 2.0 ) * pow ( det1, -p / 2.0 ) * pow ( det2, -p / 2.0 ) * pow ( det3, 0.5 ) * exp ( eval ) );
 }
 
 double GMM::compare()
 {
-	double distkij = 0.0;
-	double distkjj = 0.0;
-	double distkii = 0.0;
-	for(int i = 0; i < gaussians; i++)
-	{
-		for(int j = 0; j < gaussians; j++)
-		{
-			double kij = kPPK(sparse_sigma[i],sparse_sigma2[j], mu[i], mu2[j], 0.5);
-			double kii = kPPK(sparse_sigma[i],sparse_sigma[j], mu[i], mu[j], 0.5);
-			double kjj = kPPK(sparse_sigma2[i],sparse_sigma2[j], mu2[i], mu2[j], 0.5);
-			kij = priors[i]*priors2[j]*kij;
-			kii = priors[i]*priors[j]*kii;
-			kjj = priors2[i]*priors2[j]*kjj;
-			distkij += kij;
-			distkii += kii;
-			distkjj += kjj;
-		}
-	}
-	return (distkij / (sqrt(distkii)*sqrt(distkjj)));
+  double distkij = 0.0;
+  double distkjj = 0.0;
+  double distkii = 0.0;
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    for ( int j = 0; j < gaussians; j++ )
+    {
+      double kij = kPPK ( sparse_sigma[i], sparse_sigma2[j], mu[i], mu2[j], 0.5 );
+      double kii = kPPK ( sparse_sigma[i], sparse_sigma[j], mu[i], mu[j], 0.5 );
+      double kjj = kPPK ( sparse_sigma2[i], sparse_sigma2[j], mu2[i], mu2[j], 0.5 );
+      kij = priors[i] * priors2[j] * kij;
+      kii = priors[i] * priors[j] * kii;
+      kjj = priors2[i] * priors2[j] * kjj;
+      distkij += kij;
+      distkii += kii;
+      distkjj += kjj;
+    }
+  }
+  return ( distkij / ( sqrt ( distkii ) *sqrt ( distkjj ) ) );
 }
 
-void GMM::comparing(bool c)
+void GMM::comparing ( bool c )
 {
-	comp = c;
+  comp = c;
 }

+ 210 - 206
math/cluster/GMM.h

@@ -1,12 +1,12 @@
-/** 
+/**
  * @file GMM.h
- * @brief Gaussian Mixture Model based on   
+ * @brief Gaussian Mixture Model based on
   article{Calinon07SMC,
-  title="On Learning, Representing and Generalizing a Task in a Humanoid 
+  title="On Learning, Representing and Generalizing a Task in a Humanoid
   Robot",
   author="S. Calinon and F. Guenter and A. Billard",
-  journal="IEEE Transactions on Systems, Man and Cybernetics, Part B. 
-  Special issue on robot learning by observation, demonstration and 
+  journal="IEEE Transactions on Systems, Man and Cybernetics, Part B.
+  Special issue on robot learning by observation, demonstration and
   imitation",
   year="2007",
   volume="37",
@@ -22,7 +22,7 @@
 
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
- 
+
 #include "vislearning/cbaselib/MultiDataset.h"
 #include "vislearning/cbaselib/LocalizationResult.h"
 #include "vislearning/cbaselib/CachedExample.h"
@@ -35,206 +35,210 @@ namespace OBJREC {
 
 class GMM : public ClusterAlgorithm
 {
-	protected:
-		
-		//! number of gaussians
-		int gaussians;
-		
-		//! dimension of each feature
-		int dim;
-
-		//! mean vectors
-		NICE::VVector mu;
-	
-		//! sparse sigma vectors
-		NICE::VVector sparse_sigma;
-			
-		//! sparse inverse sigma vectors (if usediag)
-		NICE::VVector sparse_inv_sigma;
-		
-		//! save det_sigma for fast computing
-		std::vector<double> log_det_sigma;
-				
-		//! the configfile
-		const NICE::Config *conf;
-		
-		//! the weight for each gaussian
-		std::vector<double> priors;
-		
-		//! parameters for other GM to compare
-		NICE::VVector mu2;
-		NICE::VVector sparse_sigma2;
-		std::vector<double> priors2;
-		bool comp;
-		
-		//! maximum number of iterations for EM
-		int maxiter;
-		
-		//! how many features to use, use 0 for alle input features
-		int featsperclass;
-				
-		//! for faster computing cdimval = dim*2*PI
-		double cdimval;
-		
-		//! parameter for the map estimation
-		double tau;
-		
-		//! whether to use pyramid initialisation or not
-		bool pyramid;
-	public:
-		/**
-	 	 * simplest constructor
-		 */
-		GMM();
-		
-		/**
-		 * simple constructor
-		 * @param _no_classes 
-		 */
-		GMM(int _no_classes);
-		
-		/**
-		 * standard constructor
-		 * @param conf a Configfile
-		 * @param _no_classes number of gaussian
-		 */
-		GMM(const NICE::Config *conf, int _no_classes = -1);
-		
-		/**
-		 * standard destructor
-		 */
-		~GMM(){std::cerr << "dadada" << std::endl;};
-		
-		/**
-		 * computes the mixture
-		 * @param examples the input features
-		 */
-		void computeMixture(Examples examples);
-		
-		/**
-		 * computes the mixture
-		 * @param DataSet the input features
-		 */
-		void computeMixture(const NICE::VVector &DataSet);
-		
-		/**
-		 * returns the probabilities for each gaussian in a sparse vector
-		 * @param vin input vector
-		 * @param probs BoV output vector
-		 */
-		void getProbs(const NICE::Vector &vin, SparseVector &probs);
-		
-		/**
-		 * returns the probabilities for each gaussian
-		 * @param vin input vector
-		 * @param probs BoV output vector
-		 */
-		void getProbs(const NICE::Vector &vin, NICE::Vector &probs);
-		
-		/**
-		 * returns the fisher score for the gmm
-		 * @param vin input vector
-		 * @param probs Fisher score output vector
-		 */
-		void getFisher(const NICE::Vector &vin, SparseVector &probs);
-		
-		/**
-		 *   init the GaussianMixture by selecting randomized mean vectors and using the coovariance of all features
-		 * @param DataSet input Matrix
-		 */
-		void initEM(const NICE::VVector &DataSet);
-				
-		/**
-		 *   alternative for initEM: init the GaussianMixture with a K-Means clustering
-		 * @param DataSet input Matrix
-		 */
-		void initEMkMeans(const NICE::VVector &DataSet);
-		
-		/**
-		 * performs Expectation Maximization on the Dataset, 	in order to obtain a nState GMM Dataset is a Matrix(no_classes,nDimensions)
-		 * @param DataSet input Matrix
-		 * @param gaussians number gaussians to use
-		 * @return number of iterations
-		 */
-		int doEM(const NICE::VVector &DataSet, int nbgaussians);
-			
-		/**
-		 * Compute log probabilty of vector v for the given state. *
-		 * @param Vin 
-		 * @param state 
-		 * @return 
-				 */
-		double logpdfState(const NICE::Vector &Vin,int state);
-		
-		/**
-		 * determine the best mixture for the input feature
-		 * @param v input feature
-		 * @param bprob probability of the best mixture
-		 * @return numer of the best mixture
-		 */
-		int getBestClass(const NICE::Vector &v, double *bprob = NULL);
-		
-		/**
-		 * Cluster a given Set of features and return the labels for each feature
-		 * @param features input features
-		 * @param prototypes mean of the best gaussian
-		 * @param weights weight of the best gaussian
-		 * @param assignment number of the best gaussian
-		 */
-		void cluster ( const NICE::VVector & features, NICE::VVector & prototypes, std::vector<double> & weights, std::vector<int> & assignment );
-		
-		/**
-		 * save GMM data
-		 * @param filename filename
-		 */
-		void saveData(const std::string filename);
-		
-        /**
-		 * load GMM data
-		 * @param filename filename
-		 * @return true if everything works fine
-	 	 */
-		bool loadData(const std::string filename);
-		
-		/**
-		 * return the parameter of the mixture
-		 * @param mu 
-		 * @param sSigma 
-		 * @param p 
-		 */
-		void getParams(NICE::VVector &mean, NICE::VVector &sSigma, std::vector<double> &p);
-		
-		/**
-		 * Set the parameters of an other mixture for comparing with this one
-		 * @param mean mean vectors
-		 * @param sSigma diagonal covariance Matrixs
-		 * @param p weights
-		 */
-		void setCompareGM(NICE::VVector mean, NICE::VVector sSigma, std::vector<double> p);
-		
-		/**
-		 * probability product kernel
-		 * @param sigma1 
-		 * @param sigma2 
-		 * @param mu1 
-		 * @param mu2 
-		 * @param p 
-		 * @return 
-		 */
-		double kPPK(NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p);
-		
-		/**
-		 * starts a comparison between this Mixture and a other one seted bei "setComparGM"
-		 */
-		double compare();
-		
-		/**
-		 * whether to compare or not
-		 * @param c 
-		 */
-		void comparing(bool c = true);
-		
-		int getSize(){return gaussians;}
+  protected:
+
+    //! number of gaussians
+    int gaussians;
+
+    //! dimension of each feature
+    int dim;
+
+    //! mean vectors
+    NICE::VVector mu;
+
+    //! sparse sigma vectors
+    NICE::VVector sparse_sigma;
+
+    //! sparse inverse sigma vectors (if usediag)
+    NICE::VVector sparse_inv_sigma;
+
+    //! save det_sigma for fast computing
+    std::vector<double> log_det_sigma;
+
+    //! the configfile
+    const NICE::Config *conf;
+
+    //! the weight for each gaussian
+    std::vector<double> priors;
+
+    //! parameters for other GM to compare
+    NICE::VVector mu2;
+    NICE::VVector sparse_sigma2;
+    std::vector<double> priors2;
+    bool comp;
+
+    //! maximum number of iterations for EM
+    int maxiter;
+
+    //! how many features to use, use 0 for alle input features
+    int featsperclass;
+
+    //! for faster computing cdimval = dim*2*PI
+    double cdimval;
+
+    //! parameter for the map estimation
+    double tau;
+
+    //! whether to use pyramid initialisation or not
+    bool pyramid;
+  public:
+    /**
+      * simplest constructor
+     */
+    GMM();
+
+    /**
+     * simple constructor
+     * @param _no_classes
+     */
+    GMM ( int _no_classes );
+
+    /**
+     * standard constructor
+     * @param conf a Configfile
+     * @param _no_classes number of gaussian
+     */
+    GMM ( const NICE::Config *conf, int _no_classes = -1 );
+
+    /**
+     * standard destructor
+     */
+    ~GMM() {
+      std::cerr << "dadada" << std::endl;
+    };
+
+    /**
+     * computes the mixture
+     * @param examples the input features
+     */
+    void computeMixture ( Examples examples );
+
+    /**
+     * computes the mixture
+     * @param DataSet the input features
+     */
+    void computeMixture ( const NICE::VVector &DataSet );
+
+    /**
+     * returns the probabilities for each gaussian in a sparse vector
+     * @param vin input vector
+     * @param probs BoV output vector
+     */
+    void getProbs ( const NICE::Vector &vin, SparseVector &probs );
+
+    /**
+     * returns the probabilities for each gaussian
+     * @param vin input vector
+     * @param probs BoV output vector
+     */
+    void getProbs ( const NICE::Vector &vin, NICE::Vector &probs );
+
+    /**
+     * returns the fisher score for the gmm
+     * @param vin input vector
+     * @param probs Fisher score output vector
+     */
+    void getFisher ( const NICE::Vector &vin, SparseVector &probs );
+
+    /**
+     *   init the GaussianMixture by selecting randomized mean vectors and using the coovariance of all features
+     * @param DataSet input Matrix
+     */
+    void initEM ( const NICE::VVector &DataSet );
+
+    /**
+     *   alternative for initEM: init the GaussianMixture with a K-Means clustering
+     * @param DataSet input Matrix
+     */
+    void initEMkMeans ( const NICE::VVector &DataSet );
+
+    /**
+     * performs Expectation Maximization on the Dataset,  in order to obtain a nState GMM Dataset is a Matrix(no_classes,nDimensions)
+     * @param DataSet input Matrix
+     * @param gaussians number gaussians to use
+     * @return number of iterations
+     */
+    int doEM ( const NICE::VVector &DataSet, int nbgaussians );
+
+    /**
+     * Compute log probabilty of vector v for the given state. *
+     * @param Vin
+     * @param state
+     * @return
+       */
+    double logpdfState ( const NICE::Vector &Vin, int state );
+
+    /**
+     * determine the best mixture for the input feature
+     * @param v input feature
+     * @param bprob probability of the best mixture
+     * @return numer of the best mixture
+     */
+    int getBestClass ( const NICE::Vector &v, double *bprob = NULL );
+
+    /**
+     * Cluster a given Set of features and return the labels for each feature
+     * @param features input features
+     * @param prototypes mean of the best gaussian
+     * @param weights weight of the best gaussian
+     * @param assignment number of the best gaussian
+     */
+    void cluster ( const NICE::VVector & features, NICE::VVector & prototypes, std::vector<double> & weights, std::vector<int> & assignment );
+
+    /**
+     * save GMM data
+     * @param filename filename
+     */
+    void saveData ( const std::string filename );
+
+    /**
+    * load GMM data
+    * @param filename filename
+    * @return true if everything works fine
+    */
+    bool loadData ( const std::string filename );
+
+    /**
+     * return the parameter of the mixture
+     * @param mu
+     * @param sSigma
+     * @param p
+     */
+    void getParams ( NICE::VVector &mean, NICE::VVector &sSigma, std::vector<double> &p );
+
+    /**
+     * Set the parameters of an other mixture for comparing with this one
+     * @param mean mean vectors
+     * @param sSigma diagonal covariance Matrixs
+     * @param p weights
+     */
+    void setCompareGM ( NICE::VVector mean, NICE::VVector sSigma, std::vector<double> p );
+
+    /**
+     * probability product kernel
+     * @param sigma1
+     * @param sigma2
+     * @param mu1
+     * @param mu2
+     * @param p
+     * @return
+     */
+    double kPPK ( NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p );
+
+    /**
+     * starts a comparison between this Mixture and a other one seted bei "setComparGM"
+     */
+    double compare();
+
+    /**
+     * whether to compare or not
+     * @param c
+     */
+    void comparing ( bool c = true );
+
+    int getSize() {
+      return gaussians;
+    }
 };
 
 

+ 1 - 1
math/cluster/GSCluster.h

@@ -1,6 +1,6 @@
 /** 
 * @file GSCluster.h
-* @brief Generate Signature by Clustering Local Features
+* @brief Generate Signature by Clustering Local Features (image-specific codebook!). The class can be used for the EMD kernel, but not for usual BoV approaches.
 * @author Erik Rodner
 * @date 10/30/2007
 

+ 0 - 1
math/cluster/progs/testKMeans.cpp

@@ -43,7 +43,6 @@ int main(int argc, char **argv)
 
 	char c;
 	const int noClasses = 2;
-	const double alpha = 1.0;
 
 	do
 	{

+ 135 - 129
math/ftransform/PCA.cpp

@@ -30,39 +30,39 @@ using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
-PCA::PCA(uint dim, uint maxiteration, double mindelta)
+PCA::PCA ( uint dim, uint maxiteration, double mindelta )
 {
-	init(dim, maxiteration, mindelta);
+  init ( dim, maxiteration, mindelta );
 }
 
-PCA::PCA(void)
+PCA::PCA ( void )
 {
-	init();
+  init();
 }
 
 PCA::~PCA()
 {
 }
 
-void PCA::init(uint dim, uint maxiteration, double mindelta)
+void PCA::init ( uint dim, uint maxiteration, double mindelta )
 {
-	this->targetDimension = dim;
-	this->maxiteration = maxiteration;
-	this->mindelta = mindelta;
+  this->targetDimension = dim;
+  this->maxiteration = maxiteration;
+  this->mindelta = mindelta;
 }
 
-void PCA::restore(istream & is, int format)
+void PCA::restore ( istream & is, int format )
 {
 
-	is >> basis;
-	is >> normalization;
-	is >> mean;
-	is >> targetDimension;
+  is >> basis;
+  is >> normalization;
+  is >> mean;
+  is >> targetDimension;
 }
 
-void PCA::store(ostream & os, int format) const
+void PCA::store ( ostream & os, int format ) const
 {
-	os << basis << normalization << mean << targetDimension;
+  os << basis << normalization << mean << targetDimension;
 }
 
 void PCA::clear()
@@ -70,165 +70,171 @@ void PCA::clear()
 
 }
 
-void PCA::calculateBasis(const NICE::Matrix &features,
-		const uint targetDimension, const uint mode)
+void PCA::calculateBasis ( const NICE::Matrix &features,
+                           const uint targetDimension, const uint mode )
 {
-	calculateBasis(features, targetDimension, false);
+  calculateBasis ( features, targetDimension, false );
 }
 
 void PCA::calculateMean ( const NICE::Matrix &features, NICE::Vector & mean )
 {
   // data vectors are put row-wise in the matrix
-  mean.resize(features.cols());
+  mean.resize ( features.cols() );
+  mean.set(0);
   for ( uint i = 0 ; i < features.rows(); i++ )
-    mean = mean + features.getRow(i);
+    mean = mean + features.getRow ( i );
 }
 
-void PCA::calculateBasis(const NICE::Matrix &features,
-		const uint targetDimension, const bool adaptive,
-		const double targetRatio)
+void PCA::calculateBasis ( const NICE::Matrix &features,
+                           const uint targetDimension, const bool adaptive,
+                           const double targetRatio )
 {
-	this->targetDimension = targetDimension;
+  this->targetDimension = targetDimension;
   // dimension of the feature vectors
-	uint srcFeatureSize = features.cols();
-	uint mindimension = std::min(this->targetDimension, srcFeatureSize);
+  uint srcFeatureSize = features.cols();
+  uint mindimension = std::min ( this->targetDimension, srcFeatureSize );
 
-	NICE::Matrix eigenvectors;
+  NICE::Matrix eigenvectors;
+
+  NICE::Vector eigenvalue;
+
+  calculateMean ( features, mean );
 
-	NICE::Vector eigenvalue;
-  
-  calculateMean(features, mean);
 #ifdef NICE_USELIB_TRLAN
-  EigValues *eig = new EigValuesTRLAN();//fast lanczos TRLAN
+  EigValues *eig;
+  if(mindimension < 4)
+    eig = new EVArnoldi();//Arnoldi for (srcFeatureSize<n)
+  else
+    eig = new EigValuesTRLAN();//fast lanczos TRLAN
 #else
   EigValues *eig = new EVArnoldi();//Arnoldi for (srcFeatureSize<n)
 #endif
   NICE::Matrix features_transpose = features.transpose();
-  GMCovariance C(&features_transpose);
-  if (adaptive)
+  GMCovariance C ( &features_transpose );
+  if ( adaptive )
   {
-    eig->getEigenvalues(C, eigenvalue, eigenvectors, srcFeatureSize);
+    eig->getEigenvalues ( C, eigenvalue, eigenvectors, srcFeatureSize );
   }
   else
   {
-    eig->getEigenvalues(C, eigenvalue, eigenvectors, mindimension);
+    eig->getEigenvalues ( C, eigenvalue, eigenvectors, mindimension );
   }
 
 #ifdef DEBUG
-	fprintf(stderr, "Eigenvalue Decomposition ready \n");
-	cerr << eigenvectors << endl;
-	cerr << eigenvalue << endl;
+  fprintf ( stderr, "Eigenvalue Decomposition ready \n" );
+  cerr << eigenvectors << endl;
+  cerr << eigenvalue << endl;
 
-	//sort values
-	fprintf(stderr, "Eigenvector-Rows:%i Eigenvector-Cols:%i\n", (int)eigenvectors.rows(), (int)eigenvectors.cols());
+  //sort values
+  fprintf ( stderr, "Eigenvector-Rows:%i Eigenvector-Cols:%i\n", ( int ) eigenvectors.rows(), ( int ) eigenvectors.cols() );
 #endif
 
-	multimap<double, NICE::Vector> map;
-	double sumeigen = 0.0;
-
-	NICE::Vector ratio(eigenvectors.cols());
-	for (uint i = 0; i < eigenvectors.cols(); i++)//every eigenvector
-	{
-		NICE::Vector eigenvector(srcFeatureSize);
-		for (uint k = 0; k < srcFeatureSize; k++)
-		{
-			eigenvector[k] = eigenvectors(k, i);
-		}
-		map.insert(pair<double, NICE::Vector> (eigenvalue[i], eigenvector));
-		sumeigen += eigenvalue[i];
-	}
-
-	//compute basis size
-
-
-	if (adaptive)
-	{ //compute target dimension
-		uint dimensioncount = 0;
-		double addedratio = 0.0;
-		multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
-		while (addedratio <= targetRatio && it != map.rend())
-		{
-			//calc ratio
-			ratio[dimensioncount] = (*it).first / sumeigen;
-			addedratio += ratio[dimensioncount];
-			dimensioncount++;
-			it++;
-		}
-		this->targetDimension = dimensioncount;
-	}
-
-	mindimension = std::min(this->targetDimension, srcFeatureSize);
-	this->targetDimension = mindimension;
-	basis = NICE::Matrix(srcFeatureSize, mindimension);
-	//get sorted values
-	uint count = 0;
-	multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
-	while (count < this->targetDimension && it != map.rend())
-	{
-		NICE::Vector eigenvector = (*it).second;
-		//put eigenvector into column
-		for (uint k = 0; k < srcFeatureSize; k++)
-		{
-			basis(k, count) = eigenvector[k];
-		}
-		//calc ratio
-		ratio[count] = (*it).first / sumeigen;
-
-		count++;
-		it++;
-	}
-	//normalization matrix / modify variance to 1 for all eigenvectors
-	normalization = NICE::Matrix(mindimension, mindimension, 0);
-	for (uint k = 0; k < mindimension; k++)
-	{
-		normalization(k, k) = 1.0 / sqrt(eigenvalue[k]);
-	}
+  multimap<double, NICE::Vector> map;
+  double sumeigen = 0.0;
+
+  NICE::Vector ratio ( eigenvectors.cols() );
+  for ( uint i = 0; i < eigenvectors.cols(); i++ ) //every eigenvector
+  {
+    NICE::Vector eigenvector ( srcFeatureSize );
+    for ( uint k = 0; k < srcFeatureSize; k++ )
+    {
+      eigenvector[k] = eigenvectors ( k, i );
+    }
+    map.insert ( pair<double, NICE::Vector> ( eigenvalue[i], eigenvector ) );
+    sumeigen += eigenvalue[i];
+  }
+
+  //compute basis size
+
+
+  if ( adaptive )
+  { //compute target dimension
+    uint dimensioncount = 0;
+    double addedratio = 0.0;
+    multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
+    while ( addedratio <= targetRatio && it != map.rend() )
+    {
+      //calc ratio
+      ratio[dimensioncount] = ( *it ).first / sumeigen;
+      addedratio += ratio[dimensioncount];
+      dimensioncount++;
+      it++;
+    }
+    this->targetDimension = dimensioncount;
+  }
+
+  mindimension = std::min ( this->targetDimension, srcFeatureSize );
+  this->targetDimension = mindimension;
+  basis = NICE::Matrix ( srcFeatureSize, mindimension );
+  //get sorted values
+  uint count = 0;
+  multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
+  while ( count < this->targetDimension && it != map.rend() )
+  {
+    NICE::Vector eigenvector = ( *it ).second;
+    //put eigenvector into column
+    for ( uint k = 0; k < srcFeatureSize; k++ )
+    {
+      basis ( k, count ) = eigenvector[k];
+    }
+    //calc ratio
+    ratio[count] = ( *it ).first / sumeigen;
+
+    count++;
+    it++;
+  }
+  //normalization matrix / modify variance to 1 for all eigenvectors
+  normalization = NICE::Matrix ( mindimension, mindimension, 0 );
+  for ( uint k = 0; k < mindimension; k++ )
+  {
+    normalization ( k, k ) = 1.0 / sqrt ( eigenvalue[k] );
+  }
 
 #ifdef DEBUG
-	cout << "Eigenvalue-absolute:" << eigenvalue << endl;
-	cout << "Eigenvalue-ratio:" << ratio << endl;
+  cout << "Eigenvalue-absolute:" << eigenvalue << endl;
+  cout << "Eigenvalue-ratio:" << ratio << endl;
 #endif
 
 }
 
-NICE::Vector PCA::getFeatureVector(const NICE::Vector &data,
-		const bool normalize)
+NICE::Vector PCA::getFeatureVector ( const NICE::Vector &data,
+                                     const bool normalize )
 {
-	//free data of mean
-	if (normalize)
-	{
-
-		NICE::Vector meanfree(data);
-		meanfree -= mean;
-		//Y=W^t * B^T
-		if(normbasis.rows() == 0)
-			normbasis.multiply(normalization, basis, false, true);
-		NICE::Vector tmp;
-		tmp.multiply(normbasis, meanfree);
-		return tmp;
-	}
-	else
-	{
-		NICE::Vector meanfree(data);
-		meanfree -= mean;
-		//Y=W^t * B^T
-		NICE::Vector tmp;
-		tmp.multiply(basis, meanfree, true);
-		return tmp;
-	}
+  //free data of mean
+  if ( normalize )
+  {
+
+    NICE::Vector meanfree ( data );
+    meanfree -= mean;
+    //Y=W^t * B^T
+    if ( normbasis.rows() == 0 )
+      normbasis.multiply ( normalization, basis, false, true );
+    NICE::Vector tmp;
+    tmp.multiply ( normbasis, meanfree );
+    return tmp;
+  }
+  else
+  {
+    NICE::Vector meanfree ( data );
+    meanfree -= mean;
+    //Y=W^t * B^T
+    NICE::Vector tmp;
+    tmp.multiply ( basis, meanfree, true );
+    return tmp;
+  }
 }
 
 NICE::Vector PCA::getMean()
 {
-	return mean;
+  return mean;
 }
 
 NICE::Matrix PCA::getBasis()
 {
-	return basis;
+  return basis;
 }
 
 int PCA::getTargetDim()
 {
-	return targetDimension;
+  return targetDimension;
 }

+ 56 - 58
math/ftransform/PCA.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file PCA.h
  * @brief extract fourier domain value
  * @author Michael Koch
@@ -21,63 +21,61 @@ namespace OBJREC {
 class PCA: public FTransform
 {
 
-     protected:
-          NICE::Vector mean;
-
-          NICE::Matrix basis;
-		      NICE::Matrix normbasis;
-		  
-          NICE::Matrix normalization;
-          uint targetDimension; 
-          uint maxiteration;
-          double mindelta; 
-
-          void calculateMean ( const NICE::Matrix &features, NICE::Vector & mean );
- 
-     public:
-       
-          PCA (uint dim,uint maxiteration=100,double mindelta=1e-4);
-          PCA (void);
-
-          NICE::Matrix getBasis();
-     
-          NICE::Vector getMean();       
-          void restore (std::istream & is, int format = 0);
-          void store (std::ostream & os, int format = 0) const;
-          void clear ();
-          
-          /**
-           * get Basis Vectors of PCA
-           * @param features Input Features
-           * @param dimension Dimension size / number of principal components 
-          * @return Basis Vectors 
-          */
-          void calculateBasis(const NICE::Matrix &features,const uint targetDimension,const uint mode=0);
-          void calculateBasis(const NICE::Matrix &features,const uint targetDimension,const bool adaptive,const double targetRatio=1.0);
-		  
-		  /**
-		   * returns the dimension of the transformed features
-		   * @return feature dim
-		   */
-		  int getTargetDim();
-          
-          /**
-           * get Features in PCA Space
-           * @param data input data
-           * @param normalize normalisation switch
-           * @return Features as Vector
-           */
-
-          NICE::Vector getFeatureVector(const NICE::Vector &data,const bool normalize=true);
-          
-       
-          
-          ~PCA();
-
-   private:
- 
-          void init (uint dim=10,uint maxiteration=100,double mindelta=1e-4);
-        
+  protected:
+    NICE::Vector mean;
+
+    NICE::Matrix basis;
+    NICE::Matrix normbasis;
+
+    NICE::Matrix normalization;
+    uint targetDimension;
+    uint maxiteration;
+    double mindelta;
+
+    void calculateMean ( const NICE::Matrix &features, NICE::Vector & mean );
+
+  public:
+
+    PCA ( uint dim, uint maxiteration = 100, double mindelta = 1e-4 );
+    PCA ( void );
+
+    NICE::Matrix getBasis();
+
+    NICE::Vector getMean();
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
+
+    /**
+     * get Basis Vectors of PCA
+     * @param features Input Features
+     * @param dimension Dimension size / number of principal components
+    * @return Basis Vectors
+    */
+    void calculateBasis ( const NICE::Matrix &features, const uint targetDimension, const uint mode = 0 );
+    void calculateBasis ( const NICE::Matrix &features, const uint targetDimension, const bool adaptive, const double targetRatio = 1.0 );
+
+    /**
+     * returns the dimension of the transformed features
+     * @return feature dim
+     */
+    int getTargetDim();
+
+    /**
+     * get Features in PCA Space
+     * @param data input data
+     * @param normalize normalisation switch
+     * @return Features as Vector
+     */
+
+    NICE::Vector getFeatureVector ( const NICE::Vector &data, const bool normalize = true );
+
+    ~PCA();
+
+  private:
+
+    void init ( uint dim = 10, uint maxiteration = 100, double mindelta = 1e-4 );
+
 };
 
 

+ 2 - 0
math/mathbase/Featuretype.cpp

@@ -1,3 +1,5 @@
+#include <stdlib.h>
+#include <assert.h>
 #include "vislearning/math/mathbase/Featuretype.h"
 
 using namespace OBJREC;