/**
* @file testSegmentation.cpp
* @brief test segmentation algorithm
* @author Björn Fröhlich
* @date 01/20/2010

*/
#include <core/basics/Config.h>

#include <segmentation/RSMeanShift.h>
#include <segmentation/RSGraphBased.h>
#include <segmentation/RSSlic.h>

#include <core/imagedisplay/OverlayColors.h>

#include "core/basics/Timer.h"

#include <core/imagedisplay/ImageDisplay.h>

using namespace OBJREC;
using namespace NICE;
using namespace std;

int main ( int argc, char **argv )
{
  if ( argc < 2 )
  {
    cerr << "Bitte Bild angeben" << endl;
    return -1;
  }

  int type = 0;

  RegionSegmentationMethod *rg = NULL;

  if ( argc >= 3 )
  {
    string tmp;
    tmp += argv[2];

    if ( argc >= 4 )
    {
      string configfile;
      configfile += argv[3];
      Config conf ( configfile );
      if ( tmp == "f" )
      {
        rg = new RSGraphBased ( &conf );
      }
      else if ( tmp == "m" ) {
        rg = new RSMeanShift ( &conf );
      }
      else if ( tmp == "s" ) {
        rg = new RSSlic ( &conf );
      }
      else
      {
        cout << "please choose between \nm: MeanShift and \nf: Felzenswalb \nas a segmentation method" << endl;
        return -1;
      }
    }
    else {

      if ( tmp == "f" )
      {
        rg = new RSGraphBased();
      }
      else if ( tmp == "m" )
      {
        rg = new RSMeanShift();
      }
      else if ( tmp == "s" ) {
        rg = new RSSlic ();
      }
      else
      {
        cout << "please choose between \nm: MeanShift and \nf: Felzenswalb \nas a segmentation method" << endl;
        return -1;
      }
    }
  }
  else
  {
    rg = new RSGraphBased();
  }

  string filename;
  filename += argv[1];


  NICE::ColorImage img;

  img.read ( filename );

  Matrix result;

  Timer timer;
  timer.start();
  rg->segRegions ( img, result );
  timer.stop();
  cerr << "segmentation finished in: " << timer.getLastAbsolute() << " seconds" << endl;
  //rg->visualizeGraphRepresentation(img,result);

  Image overlay ( img.width(), img.height() );

  double maxval = 0.0;

  for ( int y = 0; y < img.height(); y++ )
  {
    for ( int x = 0; x < img.width(); x++ )
    {
      int val = ( ( int ) result ( x, y ) + 1 ) % 256;
      overlay.setPixel ( x, y, val );
      maxval = std::max ( result ( x, y ), maxval );
    }
  }

  cout << maxval << " different regions found" << endl;

  vector<int> color (3);
  color[0] = 255;
  ColorImage marked(img.width(), img.height());
  rg->markContours(img,result,color,marked);
  NICE::showImage ( marked, "Segmentation Result" );
  marked.write("segmented.ppm");
  return 0;
}