Exemplo n.º 1
0
/**
 * Example of a test. To be completed.
 *
 */
bool testSimpleBoard()
{
  unsigned int nbok = 0;
  unsigned int nb = 2;

  trace.beginBlock ( "Testing class SimpleBoard" );
  
  Board2D board;

  board.setPenColorRGBi( 0, 0, 0);
  board.drawRectangle( -1, 1, 2.0, 2.0 );
  board.setPenColorRGBi( 0, 0, 255 );
  board.fillCircle( 2, 2, 1 );
  
  

  board.saveSVG( "simpleboard.svg" );
  board.saveFIG( "simpleboard.fig" );
  board.saveEPS( "simpleboard.eps" );
  board.saveTikZ( "simpleboard.tikz" );
  nbok++;

  typedef  PointVector<2,int> Point2D;
  Point2D apoint, p2;
  apoint[0] = 5;
  p2[0] = 1;
  apoint[1] = 8;
  p2[1] = 1;

  board.setPenColorRGBi( 255, 0, 255 );
  board << apoint;

  board.setPenColorRGBi( 255, 0, 0 );
  Display2DFactory::draw(board, apoint, p2);

  board.scale(10);

  board.saveSVG( "pointsimpleboard.svg" );
  board.saveFIG( "pointsimpleboard.fig" );
  board.saveEPS( "pointsimpleboard.eps" );
  board.saveTikZ( "pointsimpleboard.tikz" );
  nbok++;
  trace.endBlock();
  return nbok == nb;
}
Exemplo n.º 2
0
int main( int argc, char** argv )
{
  trace.beginBlock ( "Example exampleBezierCurve" );
  trace.info() << "Args:";
  for ( int i = 0; i < argc; ++i )
    trace.info() << " " << argv[ i ];
  trace.info() << endl;

  //control points
  typedef PointVector<2,int> Point;
  Point P(0,0), Q(4,4), R(8,0); 

  //display
  Board2D board; 

  //with fill
  board << SetMode(P.className(), "Grid") << P << Q << R; 
  board.drawQuadraticBezierCurve(P[0], P[1], Q[0], Q[1], R[0], R[1]); 

  board.saveSVG("BezierCurve.svg", Board2D::BoundingBox, 5000 ); 
  board.saveEPS("BezierCurve.eps", Board2D::BoundingBox, 5000 ); 
  board.saveTikZ("BezierCurve.tikz", Board2D::BoundingBox, 5000 ); 
  board.saveFIG("BezierCurve.fig", Board2D::BoundingBox, 5000 ); 
#ifdef WITH_CAIRO
  board.saveCairo("BezierCurve.pdf", Board2D::CairoPDF); 
#endif

  board.clear(); 
  //without fill
  board << SetMode(P.className(), "Grid") << P << Q << R; 
  board.setFillColor(Color::None); 
  board.drawQuadraticBezierCurve(P[0], P[1], Q[0], Q[1], R[0], R[1]); 

  board.saveSVG("BezierCurve2.svg", Board2D::BoundingBox, 5000 ); 
  board.saveEPS("BezierCurve2.eps", Board2D::BoundingBox, 5000 ); 
  board.saveTikZ("BezierCurve2.tikz", Board2D::BoundingBox, 5000 ); 
  board.saveFIG("BezierCurve2.fig", Board2D::BoundingBox, 5000 ); 
#ifdef WITH_CAIRO
  board.saveCairo("BezierCurve2.pdf", Board2D::CairoPDF); 
#endif

  trace.endBlock();
  return 0;
}
Exemplo n.º 3
0
int main()
{
  
  typedef SpaceND<2> Space2;
  typedef HyperRectDomain<Space2> TDomain;
  typedef TDomain::Vector Vector;

  //Default image selector = STLVector
  typedef ImageSelector<TDomain, unsigned char>::Type Image;
  

  // Creating FreemanChain from file
  std::string freemanChainFilename = examplesPath + "samples/contourS.fc";
  fstream fst;
  fst.open (freemanChainFilename.c_str(), ios::in);
  FreemanChain<Space::Integer> fc(fst);
  fst.close();
  
  
  // Importing image with MagickReader
  MagickReader<Image> reader;
  std::string filenameImage = examplesPath + "samples/contourS.gif";
  Image img = reader.importImage( filenameImage );
  
  Point ptInf = img.lowerBound(); 
  Point ptSup = img.upperBound(); 
  unsigned int width = abs(ptSup.at(0)-ptInf.at(0)+1);
  unsigned int height = abs(ptSup.at(1)-ptInf.at(1)+1);
  
  // Draw the freemanchain and the contour 
  Board2D dgBoard;
  
  dgBoard.drawImage(filenameImage, 0,height-1, width, height );
  dgBoard << fc;
  
  dgBoard.saveEPS("freemanChainDisplay.eps");
  dgBoard.saveSVG("freemanChainDisplay.svg");
  dgBoard.saveFIG("freemanChainDisplay.fig");
  
  
  return 0;
}
Exemplo n.º 4
0
/**
 * testDisplay
 *
 */
bool testDisplay()
{
  typedef FreemanChain<int> FreemanChain;
  //typedef FreemanChain::Point Point;
  //typedef FreemanChain::Vector Vector;
  //typedef FreemanChain::ConstIterator Iterator;
  //typedef std::vector<unsigned int> numVector;

  Board2D aBoard;
  aBoard.setUnit(Board::UCentimeter);
  
  fstream fst;
  fst.open ((testPath + "samples/contourS.fc").c_str() , ios::in);
  FreemanChain fc(fst);  

  aBoard.setPenColor(Color::Red);
  
  //aBoard << DrawPavingPixel();
  
  aBoard << fc;
  
  std::string filenameImage = testPath + "samples/contourS.png"; // ! only PNG with Cairo for the moment !
  LibBoard::Image image( 0, 84, 185, 85, filenameImage, 20 ); 
  image.shiftDepth(500);
  LibBoard::Board & board = aBoard;
  board << image;
  
  aBoard.saveSVG( "testDisplayFC.svg", Board::BoundingBox, 5000 );
  aBoard.saveEPS( "testDisplayFC.eps", Board::BoundingBox, 5000 );
  aBoard.saveFIG( "testDisplayFC.fig", Board::BoundingBox, 5000 );
  
#ifdef WITH_CAIRO
  aBoard.saveCairo("testDisplayFC-cairo.pdf", Board2D::CairoPDF, Board::BoundingBox, 5000);
  aBoard.saveCairo("testDisplayFC-cairo.png", Board2D::CairoPNG, Board::BoundingBox, 5000);
  aBoard.saveCairo("testDisplayFC-cairo.ps",  Board2D::CairoPS,  Board::BoundingBox, 5000);
  aBoard.saveCairo("testDisplayFC-cairo.svg", Board2D::CairoSVG, Board::BoundingBox, 5000);
#endif
  
  return true;
}
Exemplo n.º 5
0
int main( int argc, char** argv )
{
  // parse command line ----------------------------------------------
  po::options_description general_opt("Allowed options are: ");
  general_opt.add_options()
    ("help,h", "display this message")
    ("FreemanChain,f", po::value<std::string>(), "FreemanChain file name")
    ("SDP", po::value<std::string>(), "Import a contour as a Sequence of Discrete Points (SDP format)")
    ("SFP", po::value<std::string>(), "Import a contour as a Sequence of Floating Points (SFP format)")
    ("drawContourPoint", po::value<double>(), "<size> display contour points as disk of radius <size>")    
    ("lineWidth", po::value<double>()->default_value(1.0), "Define the linewidth of the contour (SDP format)") 
    ("withProcessing", po::value<std::string>(), "Processing (used only with --FreemanChain):\n\t DSS segmentation {DSS}\n\t  Maximal segments {MS}\n\t Faithful Polygon {FP}\n\t Minimum Length Polygon {MLP}")   
    ("outputEPS", po::value<std::string>(), " <filename> specify eps format (default format output.eps)")
    ("outputSVG", po::value<std::string>(), " <filename> specify svg format.")
    ("outputFIG", po::value<std::string>(), " <filename> specify fig format.")
#ifdef WITH_CAIRO
    ("outputPDF", po::value<std::string>(), "outputPDF <filename> specify pdf format. ")
    ("outputPNG", po::value<std::string>(), "outputPNG <filename> specify png format.")
    ("invertYaxis", " invertYaxis invert the Y axis for display contours (used only with --SDP)")
#endif
#ifdef WITH_MAGICK
    ("backgroundImage", po::value<std::string>(), "backgroundImage <filename> <alpha> : display image as background with transparency alpha (defaut 1) (transparency works only if cairo is available)")
    ("alphaBG", po::value<double>(), "alphaBG <value> 0-1.0 to display the background image in transparency (default 1.0)")
#endif
    ("scale", po::value<double>(), "scale <value> 1: normal; >1 : larger ; <1 lower resolutions  )");
  
  
  
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, general_opt), vm);  
  po::notify(vm);    
  if(vm.count("help")||argc<=1 || (not(vm.count("FreemanChain")) && not(vm.count("SDP")) && not(vm.count("SFP"))&&
           not(vm.count("backgroundImage")) ) )
    {
      trace.info()<< "Display discrete contours. " <<std::endl << "Basic usage: "<<std::endl
      << "\t displayContours [options] --FreemanChain  <fileName>  --imageName image.png "<<std::endl
      << general_opt << "\n";
      return 0;
    }
  
  
  
  double lineWidth=  vm["lineWidth"].as<double>();
  
  double scale=1.0;
  if(vm.count("scale")){
    scale = vm["scale"].as<double>();
  }
  
  Board2D aBoard;
  aBoard.setUnit (0.05*scale, LibBoard::Board::UCentimeter);
  



#ifdef WITH_MAGICK
  double alpha=1.0;
  if(vm.count("alphaBG")){
    alpha = vm["alphaBG"].as<double>(); 
  }
  
  if(vm.count("backgroundImage")){
    string imageName = vm["backgroundImage"].as<string>();
    typedef ImageSelector<Z2i::Domain, unsigned char>::Type Image;
    DGtal::MagickReader<Image> reader;
    Image img = reader.importImage( imageName );
    Z2i::Point ptInf = img.lowerBound(); 
    Z2i::Point ptSup = img.upperBound(); 
    unsigned int width = abs(ptSup.at(0)-ptInf.at(0)+1);
    unsigned int height = abs(ptSup.at(1)-ptInf.at(1)+1);
    
    aBoard.drawImage(imageName, 0-0.5,height-0.5, width, height, -1, alpha );
  }
#endif
 

 
  if(vm.count("FreemanChain")){
    string fileName = vm["FreemanChain"].as<string>();
    vector< FreemanChain<int> > vectFc =  PointListReader< Z2i::Point>:: getFreemanChainsFromFile<int> (fileName); 
    //aBoard <<  SetMode( vectFc.at(0).styleName(), "InterGrid" );
    aBoard << CustomStyle( vectFc.at(0).styleName(), 
         new CustomColors( Color::Red  ,  Color::None ) );    
    for(unsigned int i=0; i<vectFc.size(); i++){
      aBoard <<  vectFc.at(i) ;

      if(vm.count("withProcessing")){
  std::string processingName = vm["withProcessing"].as<std::string>();

  vector<Z2i::Point> vPts(vectFc.at(i).size()+1); 
  copy ( vectFc.at(i).begin(), vectFc.at(i).end(), vPts.begin() ); 
  bool isClosed;
  if ( vPts.at(0) == vPts.at(vPts.size()-1) ) { 
          isClosed = true;
          vPts.pop_back(); 
  } else isClosed = false;

  if (processingName == "DSS") {

          typedef ArithmeticalDSS<vector<Z2i::Point>::iterator,int,4> DSS4;
          typedef deprecated::GreedyDecomposition<DSS4> Decomposition4;

          //Segmentation
    DSS4 computer;
          Decomposition4 theDecomposition( vPts.begin(),vPts.end(),computer,isClosed );
          //for each segment
          aBoard << SetMode( computer.styleName(), "BoundingBox" );
          string styleName = computer.styleName() + "/BoundingBox";
          for ( Decomposition4::SegmentIterator it = theDecomposition.begin();
    it != theDecomposition.end(); ++it ) 
            {
        DSS4 segment(*it);
        aBoard << CustomStyle( styleName, 
             new CustomPenColor( DGtal::Color::Gray ) ); 
        aBoard << segment; // draw each segment
            } 

  } else if (processingName == "MS") {

          typedef ArithmeticalDSS<vector<Z2i::Point>::iterator,int,4> DSS4;
          typedef deprecated::MaximalSegments<DSS4> Decomposition4;

          //Segmentation
    DSS4 computer;
          Decomposition4 theDecomposition( vPts.begin(),vPts.end(),computer,isClosed );

          //for each segment
          aBoard << SetMode( computer.styleName(), "BoundingBox" );
          string styleName = computer.styleName() + "/BoundingBox";
          for ( Decomposition4::SegmentIterator it = theDecomposition.begin();
    it != theDecomposition.end(); ++it ) 
            {
        DSS4 segment(*it);
        aBoard << CustomStyle( styleName, 
             new CustomPenColor( DGtal::Color::Black ) ); 
        aBoard << segment; // draw each segment
            } 


  } else if (processingName == "FP") {

    typedef FP<vector<Z2i::Point>::iterator,int,4> FP;
    FP theFP( vPts.begin(),vPts.end(),isClosed );
          aBoard << CustomStyle( theFP.styleName(), 
         new CustomPenColor( DGtal::Color::Black ) ); 
          aBoard << theFP;


  } else if (processingName == "MLP") {

    typedef FP<vector<Z2i::Point>::iterator,int,4> FP;
    FP theFP( vPts.begin(),vPts.end(),isClosed );

          vector<FP::RealPoint> v( theFP.size() );
          theFP.copyMLP( v.begin() );

          //polyline to draw
    vector<LibBoard::Point> polyline;
    vector<FP::RealPoint>::const_iterator it = v.begin();
    for ( ;it != v.end();++it) {
      FP::RealPoint p = (*it);
      polyline.push_back(LibBoard::Point(p[0],p[1]));
    }
          if (isClosed) {
      FP::RealPoint p = (*v.begin());
      polyline.push_back(LibBoard::Point(p[0],p[1]));
          }
          aBoard.setPenColor(DGtal::Color::Black);
          aBoard.drawPolyline(polyline);

  }

      }

    }



  }
 
 

  if(vm.count("SDP") || vm.count("SFP")){
    bool drawPoints= vm.count("drawContourPoint");
    bool invertYaxis = vm.count("invertYaxis");
    double pointSize=1.0;
    if(drawPoints){
      pointSize = vm["drawContourPoint"].as<double>();
    }
    vector<LibBoard::Point> contourPt;
    if(vm.count("SDP")){
      string fileName = vm["SDP"].as<string>();
      vector< Z2i::Point >  contour = 
  PointListReader< Z2i::Point >::getPointsFromFile(fileName); 
      for(unsigned int j=0; j<contour.size(); j++){
  LibBoard::Point pt((double)(contour.at(j)[0]),
         (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
  contourPt.push_back(pt);
  if(drawPoints){
    aBoard.fillCircle(pt.x, pt.y, pointSize);
  }
      }
    }
 
    if(vm.count("SFP")){
      string fileName = vm["SFP"].as<string>();
      vector< PointVector<2,double>  >  contour = 
	PointListReader<  PointVector<2,double>  >::getPointsFromFile(fileName); 
      for(unsigned int j=0; j<contour.size(); j++){
  LibBoard::Point pt((double)(contour.at(j)[0]),
         (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
  contourPt.push_back(pt);
  if(drawPoints){
    aBoard.fillCircle(pt.x, pt.y, pointSize);
  }
      }
    }
  
  
    aBoard.setPenColor(Color::Red);
    aBoard.setLineStyle (LibBoard::Shape::SolidStyle );
    aBoard.setLineWidth (lineWidth);
    aBoard.drawPolyline(contourPt);
  
  
  }

 



  

  
  if (vm.count("outputSVG")){
    string outputFileName= vm["outputSVG"].as<string>();
    aBoard.saveSVG(outputFileName.c_str());
  } else   
    if (vm.count("outputFIG")){
      string outputFileName= vm["outputFIG"].as<string>();
      aBoard.saveFIG(outputFileName.c_str());
    } else
      if (vm.count("outputEPS")){
  string outputFileName= vm["outputEPS"].as<string>();
  aBoard.saveEPS(outputFileName.c_str());
      }  
#ifdef WITH_CAIRO
      else
  if (vm.count("outputEPS")){
    string outputFileName= vm["outputEPS"].as<string>();
    aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoEPS );
  } else 
    if (vm.count("outputPDF")){
      string outputFileName= vm["outputPDF"].as<string>();
      aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPDF );
    } else 
      if (vm.count("outputPNG")){
        string outputFileName= vm["outputPNG"].as<string>();
        aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPNG );
      }
#endif
      else { //default output
        string outputFileName= "output.eps";
        aBoard.saveEPS(outputFileName.c_str());
      }
  
}
Exemplo n.º 6
0
int main( int /*argc*/, char** /*argv*/ )
{
  trace.beginBlock ( "Example ctopo-fillContours" );
  DGtal::KhalimskySpaceND< 2, int > K; 
  K.init(Z2i::Point(0, 10),  Z2i::Point(20, 30), false);
  
  // We choose a direct and indirect oriented contour.
  //! [ctopoFillContoursInit]
  FreemanChain<int> fc1 ("001001001001001111101111011222222223222222322233333330301033333003", 6, 14);
  FreemanChain<int> fc2 ("1111000033332222", 6, 20);  
  //! [ctopoFillContoursInit]
  
  Board2D aBoard;
  Board2D aBoard2;
  aBoard << K.lowerBound() << K.upperBound() ;
  aBoard2 << K.lowerBound() << K.upperBound() ;
    
  //From the FreemanChain we can get a vector of SCell wrapped in a SurfelSetPredicate with sign defined from the FreemanChain orientation:
  //! [ctopoFillContoursGetSCells]
  
  typedef  KhalimskySpaceND<2, int>::SCell SCell;
  std::set<DGtal::KhalimskySpaceND< 2, int >::SCell> boundarySCell;
  FreemanChain<int>::getInterPixelLinels(K, fc1, boundarySCell, false); 
  //! [ctopoFillContoursGetSCells]
  
  aBoard << CustomStyle((*boundarySCell.begin()).className(),  new CustomColors(DGtal::Color::Red, DGtal::Color::Red) );
  for( std::set<DGtal::KhalimskySpaceND< 2, int >::SCell>::const_iterator it= boundarySCell.begin();  
       it!= boundarySCell.end(); it++){
    aBoard << *it;
  }
  
  // We can also add other freeman chains with indirect orientation to construct a hole in interior of the shape:
  //! [ctopoFillContoursGetSCellsHole]
  std::set<DGtal::KhalimskySpaceND< 2, int >::SCell> boundarySCellhole;
  FreemanChain<int>::getInterPixelLinels(K, fc2, boundarySCellhole, false); 
  //! [ctopoFillContoursGetSCellsHole]
  
  
  aBoard << CustomStyle((*boundarySCell.begin()).className(),  new CustomColors(DGtal::Color::Blue, DGtal::Color::Blue) );
  aBoard2 << CustomStyle((*boundarySCell.begin()).className(),  new CustomColors(DGtal::Color::Blue, DGtal::Color::Blue) );
  
 
  
   for( std::set<DGtal::KhalimskySpaceND< 2, int >::SCell>::const_iterator it= boundarySCellhole.begin();  it!= boundarySCellhole.end(); it++){
    aBoard << *it;
    aBoard2 << *it;
    boundarySCell.insert(*it);
  }
  
  
  // Now we can compute the unsigned cell associated to interior pixels: 

  //! [ctopoFillContoursFillRegion]
  typedef ImageContainerBySTLMap< Z2i::Domain, bool> BoolImage2D;
  BoolImage2D::Domain imageDomain( Z2i::Point(0,10), Z2i::Point(20,30) );
  BoolImage2D interiorCellImage( imageDomain );
  Surfaces<DGtal::KhalimskySpaceND< 2, int > >::uFillInterior(K, functors::SurfelSetPredicate<std::set<SCell>,SCell>(boundarySCell), 
                                                              interiorCellImage, 1, false);  
  //! [ctopoFillContoursFillRegion]

  aBoard << CustomStyle(K.uSpel(Z2i::Point(0,0)).className(),  new CustomColors(DGtal::Color::None, Color(200, 200, 200)) );
  for(BoolImage2D::Domain::ConstIterator it = interiorCellImage.domain().begin(); 
      it!=interiorCellImage.domain().end(); it++){
    if(interiorCellImage(*it)){
      aBoard << K.uSpel(*it);
    }
  }
  
  
  // We can also compute the unsigned cell associated to interior and exterior pixels: 
  //! [ctopoFillContoursFillRegionHoles]
  BoolImage2D interiorCellHoleImage( imageDomain );
  BoolImage2D exteriorCellHoleImage( imageDomain );

  
  Surfaces<DGtal::KhalimskySpaceND< 2, int > >::uFillInterior(K, functors::SurfelSetPredicate<std::set<SCell>, SCell>(boundarySCellhole), 
                                                              interiorCellHoleImage, 1, true);  
  Surfaces<DGtal::KhalimskySpaceND< 2, int > >::uFillExterior(K, functors::SurfelSetPredicate<std::set<SCell>, SCell>(boundarySCellhole), 
                                                              exteriorCellHoleImage, 1,  false);  
  //! [ctopoFillContoursFillRegionHoles]  

  aBoard2 << CustomStyle(K.uSpel(Z2i::Point(0,0)).className(),  
                          new CustomColors(DGtal::Color::None, Color(200, 200, 200)) );
  for(BoolImage2D::Domain::ConstIterator it = interiorCellHoleImage.domain().begin();
      it!=interiorCellHoleImage.domain().end(); it++){
    if(interiorCellHoleImage(*it)){
      aBoard2 << K.uSpel(*it);
    }
  }
  aBoard2 << CustomStyle(K.uSpel(Z2i::Point(0,0)).className(),  
                         new CustomColors(DGtal::Color::None, Color(100, 100, 100)) );
  for(BoolImage2D::Domain::ConstIterator it = exteriorCellHoleImage.domain().begin(); 
      it!=exteriorCellHoleImage.domain().end(); it++){
    if(exteriorCellHoleImage(*it)){
      aBoard2 << K.uSpel(*it);
    }
  }
  
  aBoard.saveEPS("example_ctopo-fillContours.eps");
  aBoard.saveFIG("example_ctopo-fillContours.fig");

  aBoard2.saveEPS("example_ctopo-fillContours2.eps");
  aBoard2.saveFIG("example_ctopo-fillContours2.fig");
  trace.endBlock();
  return 0;
}
Exemplo n.º 7
0
int main( int argc, char** argv )
{

    // parse command line ----------------------------------------------
    po::options_description general_opt("Allowed options are: ");
    general_opt.add_options()
    ("help,h", "display this message")
    ("input,i", po::value<std::string>(), "input FreemanChain file name")
    ("SDP", po::value<std::string>(), "Import a contour as a Sequence of Discrete Points (SDP format)")
    ("SFP", po::value<std::string>(), "Import a contour as a Sequence of Floating Points (SFP format)")
    ("drawContourPoint", po::value<double>(), "<size> display contour points as disk of radius <size>")
    ("fillContour", "fill the contours with default color (gray)")
    ("lineWidth", po::value<double>()->default_value(1.0), "Define the linewidth of the contour (SDP format)")
    ("drawPointOfIndex", po::value<int>(), "<index> Draw the contour point of index <index> (default 0) ")
    ("pointSize", po::value<double>()->default_value(2.0), "<size> Set the display point size of the point displayed by drawPointofIndex option (default 2.0) ")
    ("noXFIGHeader", " to exclude xfig header in the resulting output stream (no effect with option -outputFile).")
    ("withProcessing", po::value<std::string>(), "Processing (used only when the input is a Freeman chain (--input)):\n\t DSS segmentation {DSS}\n\t  Maximal segments {MS}\n\t Faithful Polygon {FP}\n\t Minimum Length Polygon {MLP}")
    ("outputFile,o", po::value<std::string>(), " <filename> save output file automatically according the file format extension.")
    ("outputStreamEPS", " specify eps for output stream format.")
    ("outputStreamSVG", " specify svg for output stream format.")
    ("outputStreamFIG", " specify fig for output stream format.")
    ("invertYaxis", " invertYaxis invert the Y axis for display contours (used only with --SDP)")

    ("backgroundImage", po::value<std::string>(), "backgroundImage <filename> : display image as background ")
    ("alphaBG", po::value<double>(), "alphaBG <value> 0-1.0 to display the background image in transparency (default 1.0), (transparency works only if cairo is available)")

    ("scale", po::value<double>(), "scale <value> 1: normal; >1 : larger ; <1 lower resolutions  )");



    bool parseOK=true;
    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, general_opt), vm);
    } catch(const std::exception& ex) {
        parseOK=false;
        trace.info()<< "Error checking program options: "<< ex.what()<< std::endl;
    }

    po::notify(vm);
    if(!parseOK||vm.count("help")||argc<=1 || (!(vm.count("input")) && !(vm.count("SDP")) && !(vm.count("SFP"))&&
            !(vm.count("backgroundImage")) ) )
    {
        trace.info()<< "Display discrete contours. " <<std::endl << "Basic usage: "<<std::endl
                    << "\t displayContours [options] --input  <fileName>  "<<std::endl
                    << general_opt << "\n";
        return 0;
    }



    double lineWidth=  vm["lineWidth"].as<double>();
    bool filled = vm.count("fillContour");
    double scale=1.0;
    if(vm.count("scale")) {
        scale = vm["scale"].as<double>();
    }

    Board2D aBoard;
    aBoard.setUnit (0.05*scale, LibBoard::Board::UCentimeter);





    double alpha=1.0;
    if(vm.count("alphaBG")) {
        alpha = vm["alphaBG"].as<double>();
    }

    if(vm.count("backgroundImage")) {
        std::string imageName = vm["backgroundImage"].as<std::string>();
        typedef ImageSelector<Z2i::Domain, unsigned char>::Type Image;
        Image img = DGtal::GenericReader<Image>::import( imageName );
        Z2i::Point ptInf = img.domain().lowerBound();
        Z2i::Point ptSup = img.domain().upperBound();
        unsigned int width = abs(ptSup[0]-ptInf[0]+1);
        unsigned int height = abs(ptSup[1]-ptInf[1]+1);

        aBoard.drawImage(imageName, 0-0.5,height-0.5, width, height, -1, alpha );
    }




    if(vm.count("input")) {
        std::string fileName = vm["input"].as<std::string>();
        std::vector< FreemanChain<int> > vectFc =  PointListReader< Z2i::Point>:: getFreemanChainsFromFile<int> (fileName);
        aBoard << CustomStyle( vectFc.at(0).className(),
                               new CustomColors( Color::Red  ,  filled?  Color::Gray: Color::None  ) );
        aBoard.setLineWidth (lineWidth);
        for(unsigned int i=0; i<vectFc.size(); i++) {
            aBoard <<  vectFc.at(i) ;
            if(vm.count("drawPointOfIndex")) {
                int index = vm["drawPointOfIndex"].as<int>();
                double size = vm["pointSize"].as<double>();
                aBoard.setPenColor(Color::Blue);

                aBoard.fillCircle((double)(vectFc.at(i).getPoint(index)[0]), (double)(vectFc.at(i).getPoint(index)[1]), size);
            }

            if(vm.count("withProcessing")) {
                std::string processingName = vm["withProcessing"].as<std::string>();

                std::vector<Z2i::Point> vPts(vectFc.at(i).size()+1);
                copy ( vectFc.at(i).begin(), vectFc.at(i).end(), vPts.begin() );
                bool isClosed;
                if ( vPts.at(0) == vPts.at(vPts.size()-1) ) {
                    isClosed = true;
                    vPts.pop_back();
                } else isClosed = false;

                if (processingName == "DSS") {

                    typedef ArithmeticalDSSComputer<std::vector<Z2i::Point>::iterator,int,4> DSS4;
                    typedef GreedySegmentation<DSS4> Decomposition4;

                    DSS4 computer;
                    Decomposition4 theDecomposition( vPts.begin(),vPts.end(),computer );

                    //for each segment
                    std::string className;
                    for ( Decomposition4::SegmentComputerIterator it = theDecomposition.begin();
                            it != theDecomposition.end(); ++it )
                    {
                        DSS4::Primitive segment(it->primitive());

                        aBoard << SetMode( segment.className(), "BoundingBox" );
                        className = segment.className() + "/BoundingBox";
                        aBoard << CustomStyle( className,
                                               new CustomPenColor( DGtal::Color::Gray ) );
                        aBoard << segment; // draw each segment
                    }

                } else if (processingName == "MS") {

                    typedef ArithmeticalDSSComputer<std::vector<Z2i::Point>::iterator,int,4> DSS4;
                    typedef SaturatedSegmentation<DSS4> Decomposition4;

                    //Segmentation
                    DSS4 computer;
                    Decomposition4 theDecomposition( vPts.begin(),vPts.end(),computer );

                    //for each segment
                    std::string className;
                    for ( Decomposition4::SegmentComputerIterator it = theDecomposition.begin();
                            it != theDecomposition.end(); ++it )
                    {
                        DSS4::Primitive segment(it->primitive());

                        aBoard << SetMode( segment.className(), "BoundingBox" );
                        className = segment.className() + "/BoundingBox";
                        aBoard << CustomStyle( className,
                                               new CustomPenColor( DGtal::Color::Gray ) );
                        aBoard << segment; // draw each segment
                    }

                } else if (processingName == "FP") {

                    typedef FP<std::vector<Z2i::Point>::iterator,int,4> FP;
                    FP theFP( vPts.begin(),vPts.end() );
                    aBoard << CustomStyle( theFP.className(),
                                           new CustomPenColor( DGtal::Color::Black ) );
                    aBoard << theFP;


                } else if (processingName == "MLP") {

                    typedef FP<std::vector<Z2i::Point>::iterator,int,4> FP;
                    FP theFP( vPts.begin(),vPts.end() );

                    std::vector<FP::RealPoint> v( theFP.size() );
                    theFP.copyMLP( v.begin() );

                    //polyline to draw
                    std::vector<LibBoard::Point> polyline;
                    std::vector<FP::RealPoint>::const_iterator it = v.begin();
                    for ( ; it != v.end(); ++it) {
                        FP::RealPoint p = (*it);
                        polyline.push_back(LibBoard::Point(p[0],p[1]));
                    }
                    if (isClosed) {
                        FP::RealPoint p = (*v.begin());
                        polyline.push_back(LibBoard::Point(p[0],p[1]));
                    }
                    aBoard.setPenColor(DGtal::Color::Black);
                    aBoard.drawPolyline(polyline);

                } else if (processingName == "MDCA") {
                    typedef KhalimskySpaceND<2,int> KSpace;
                    typedef GridCurve<KSpace> Curve;
                    Curve curve; //grid curve
                    curve.initFromPointsVector( vPts );
                    typedef Curve::IncidentPointsRange Range; //range
                    Range r = curve.getIncidentPointsRange(); //range
                    typedef Range::ConstCirculator ConstCirculator; //iterator
                    typedef StabbingCircleComputer<ConstCirculator> SegmentComputer; //segment computer
                    //typedef GeometricalDCA<ConstIterator> SegmentComputer; //segment computer
                    typedef SaturatedSegmentation<SegmentComputer> Segmentation;
                    //Segmentation theSegmentation( r.begin(), r.end(), SegmentComputer() );
                    Segmentation theSegmentation( r.c(), r.c(), SegmentComputer() );
                    theSegmentation.setMode("Last");
                    // board << curve;
                    Segmentation::SegmentComputerIterator it = theSegmentation.begin();
                    Segmentation::SegmentComputerIterator itEnd = theSegmentation.end();
                    Board2D otherBoard;
                    otherBoard.setPenColor(DGtal::Color::Black);
                    otherBoard << curve;
                    for ( ; it != itEnd; ++it ) {
                        aBoard << SetMode(SegmentComputer().className(), "") << (*it);
                        otherBoard << SetMode(SegmentComputer().className(), "") << (*it);
                    }
                    otherBoard.saveSVG("mdca.svg", Board2D::BoundingBox, 5000 );
                }
            }

        }



    }



    if(vm.count("SDP") || vm.count("SFP")) {
        bool drawPoints= vm.count("drawContourPoint");
        bool invertYaxis = vm.count("invertYaxis");
        double pointSize=1.0;
        if(drawPoints) {
            pointSize = vm["drawContourPoint"].as<double>();
        }
        std::vector<LibBoard::Point> contourPt;
        if(vm.count("SDP")) {
            std::string fileName = vm["SDP"].as<std::string>();
            std::vector< Z2i::Point >  contour =
                PointListReader< Z2i::Point >::getPointsFromFile(fileName);
            for(unsigned int j=0; j<contour.size(); j++) {
                LibBoard::Point pt((double)(contour.at(j)[0]),
                                   (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
                contourPt.push_back(pt);
                if(drawPoints) {
                    aBoard.fillCircle(pt.x, pt.y, pointSize);
                }
            }
        }

        if(vm.count("SFP")) {
            std::string fileName = vm["SFP"].as<std::string>();
            std::vector< PointVector<2,double>  >  contour =
                PointListReader<  PointVector<2,double>  >::getPointsFromFile(fileName);
            for(unsigned int j=0; j<contour.size(); j++) {
                LibBoard::Point pt((double)(contour.at(j)[0]),
                                   (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
                contourPt.push_back(pt);
                if(drawPoints) {
                    aBoard.fillCircle(pt.x, pt.y, pointSize);
                }
            }

        }


        aBoard.setPenColor(Color::Red);
        aBoard.setFillColor(Color::Gray);
        aBoard.setLineStyle (LibBoard::Shape::SolidStyle );
        aBoard.setLineWidth (lineWidth);
        if(!filled) {
            aBoard.drawPolyline(contourPt);
        } else {
            aBoard.fillPolyline(contourPt);
        }
        if(vm.count("drawPointOfIndex")) {
            int index = vm["drawPointOfIndex"].as<int>();
            double size = vm["pointSize"].as<double>();
            aBoard.fillCircle((double)(contourPt.at(index).x), (double)(contourPt.at(index).y), size);
        }



    }




    if(vm.count("outputFile")) {
        std::string outputFileName= vm["outputFile"].as<std::string>();
        std::string extension = outputFileName.substr(outputFileName.find_last_of(".") + 1);

        if(extension=="svg") {
            aBoard.saveSVG(outputFileName.c_str());
        }
#ifdef WITH_CAIRO
        else if (extension=="eps") {
            aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoEPS );
        } else if (extension=="pdf") {
            aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPDF );
        } else if (extension=="png") {
            aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPNG );
        }
#endif
        else if(extension=="eps") {
            aBoard.saveEPS(outputFileName.c_str());
        } else if(extension=="fig") {
            aBoard.saveFIG(outputFileName.c_str(),LibBoard::Board::BoundingBox, 10.0, !vm.count("noXFIGHeader") );
        }
    }

    if (vm.count("outputStreamSVG")) {
        aBoard.saveSVG(std::cout);
    } else if (vm.count("outputStreamFIG")) {
        aBoard.saveFIG(std::cout, LibBoard::Board::BoundingBox, 10.0,  !vm.count("noXFIGHeader"));
    } else if (vm.count("outputStreamEPS")) {
        aBoard.saveEPS(std::cout);
    }

}
Exemplo n.º 8
0
int main( int argc, char** argv )
{
  
  // Contour import
  args.addOption("-fc", "-fc <freemanChain.fc> : FreemanChain file name", "freeman.fc" );
  args.addOption("-sdp", "-sdp <contour.sdp> : Import a contour as a Sequence of Discrete Points (SDP format)", "contour.sdp" );
  args.addOption("-sfp", "-sdp <contour.sdp> : Import a contour as a Sequence of Floating Points (SFP format)", "contour.sdp" );
  
  // Display options
  args.addOption("-drawContourPoint", "-drawContourPoint <size> (double): display contour points as disk of radius <size> (default 1.0) ", "1.0" );
  args.addBooleanOption("-fillContour", "-fillContour fill the contours with default color");
  args.addOption("-lineWidth", "-lineWidth <width> : define the linewidth <width> of the contour (default 1.0) (SDP format)", "1.0");
  
  args.addOption("-outputEPS", "-outputEPS <filename> specify eps format (default format output.eps)", "output.eps");
  args.addOption("-outputSVG", "-outputSVG <filename> specify svg format. (default name output.svg)", "output.svg");
  args.addOption("-outputFIG", "-outputFIG <filename> specify svg format. (default name output.fig)", "output.fig");
  
#ifdef WITH_CAIRO
  args.addOption("-outputPDF", "-outputPDF <filename> specify svg format. (default name output.pdf)", "output.pdf");
  args.addOption("-outputPNG", "-outputPNG <filename> specify png format. (default name output.png)", "output.png");
  args.addBooleanOption("-invertYaxis", "-invertYaxis: invert the Y axis for display contours (used only with --SDP) ");  
#endif
  
#ifdef WITH_MAGICK
  args.addOption("-backgroundImage", "-backgroundImage <filename> <alpha> : display image as background with transparency alpha (defaut 1) (transparency works only if cairo is available)", "imageBG.png", "1.0"  );
#endif

  args.addOption("-backgroundImageXFIG", "-backgroundImageXFIG <filename> <width> <height> : display image as background in XFIG format", "imageBG.png", "256","256"  );
  args.addOption("-scale", "-scale <value> 1: normal; >1 : larger ; <1 lower resolutions  ) (default 1.0) ", "1.0");
  
  bool parseOK=  args.readArguments( argc, argv );
  
  
  if(!parseOK || args.check("-h") || (! args.check("-fc") && ! args.check("-sdp") && ! args.check("-sfp"))){
    trace.info()<<args.usage("displayContours", "Display discrete contours. \n Basic usage: \n \t displayContours [options] -fc  <fileName>  \n", "");
    
      return 1;
  } 


  
  double lineWidth =  args.getOption("-lineWidth")->getFloatValue(0);
  double scale = args.getOption("-scale")->getIntValue(0);
  bool filled = args.check("-fillContour");
  Board2D aBoard;
  aBoard.setUnit (0.05*scale, LibBoard::Board::UCentimeter);
  
  
  
#ifdef WITH_MAGICK
  double alpha=args.getOption("-alphaBG")->getFloatValue(0);
  if(args.check("-backgroundImage")){
    string imageName = args.check("-backgroundImage")->getValue(0);
    typedef ImageSelector<Z2i::Domain, unsigned char>::Type Image;
    DGtal::MagickReader<Image> reader;
    Image img = reader.importImage( imageName );
    Z2i::Point ptInf = img.domain().lowerBound(); 
    Z2i::Point ptSup = img.domain().upperBound(); 
    unsigned int width = abs(ptSup.at(0)-ptInf.at(0)+1);
    unsigned int height = abs(ptSup.at(1)-ptInf.at(1)+1);
    aBoard.drawImage(imageName, 0-0.5,height-0.5, width, height, -1, alpha );
  }
#endif
 
  if(args.check("-backgroundImageXFIG")){
    string imageName = args.getOption("-backgroundImageXFIG")->getValue(0);
    unsigned int width = args.getOption("-backgroundImageXFIG")->getIntValue(1);
    unsigned int height = args.getOption("-backgroundImageXFIG")->getIntValue(2);
    aBoard.drawImage(imageName, 0,height-1, width, height, -1, 1.0 );
    }
 
  if(args.check("-fc")){
    string fileName = args.getOption("-fc")->getValue(0);
    vector< FreemanChain<int> > vectFc =  PointListReader< Z2i::Point>:: getFreemanChainsFromFile<int> (fileName); 
    //aBoard <<  SetMode( vectFc.at(0).className(), "InterGrid" );
    aBoard << CustomStyle( vectFc.at(0).className(), 
			   new CustomColors( Color::Red  ,  (filled ? (Color::Black) : (Color::None))  ) );    
    for(unsigned int i=0; i<vectFc.size(); i++){
      aBoard <<  vectFc.at(i) ;
    }
  } 
 

  if( args.check("-sdp") || args.check("-sfp")){
    bool drawPoints= args.check("-drawContourPoint");
    bool invertYaxis = args.check("-invertYaxis");
    
    double pointSize = args.getOption("-drawContourPoint")->getFloatValue(0);
    
    vector<LibBoard::Point> contourPt;
    if(args.check("-sdp")){
      string fileName = args.getOption("-sdp")->getValue(0);
      vector< Z2i::Point >  contour = 
	PointListReader< Z2i::Point >::getPointsFromFile(fileName); 
      for(unsigned int j=0; j<contour.size(); j++){
	LibBoard::Point pt((double)(contour.at(j)[0]),
			   (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
	contourPt.push_back(pt);
	if(drawPoints){
	  aBoard.fillCircle(pt.x, pt.y, pointSize);
	}
      }
    }
    
    if(args.check("-sfp")){
      string fileName = args.getOption("-sfp")->getValue(0);
      vector< PointVector<2,double>  >  contour = 
	PointListReader<  PointVector<2,double>  >::getPointsFromFile(fileName); 
      for(unsigned int j=0; j<contour.size(); j++){
	LibBoard::Point pt((double)(contour.at(j)[0]),
			   (invertYaxis? (double)(-contour.at(j)[1]+contour.at(0)[1]):(double)(contour.at(j)[1])));
	contourPt.push_back(pt);
	if(drawPoints){
	  aBoard.fillCircle(pt.x, pt.y, pointSize);
	}
      }
    }
    aBoard.setPenColor(Color::Red);
    aBoard.setLineStyle (LibBoard::Shape::SolidStyle );
    aBoard.setLineWidth (lineWidth);
    if(!filled){
      aBoard.drawPolyline(contourPt);
    }else{
      aBoard.fillPolyline(contourPt);
    }
    
  
  }

 
  
  if (args.check("-outputSVG")){
    string outputFileName= args.getOption("-outputSVG")->getValue(0);
    aBoard.saveSVG(outputFileName.c_str());
  } else   
    if (args.check("-outputFIG")){
      string outputFileName= args.getOption("-outputFIG")->getValue(0);
      aBoard.saveFIG(outputFileName.c_str());
    } else
      if (args.check("-outputEPS")){
	string outputFileName= args.getOption("-outputEPS")->getValue(0);
	aBoard.saveEPS(outputFileName.c_str());
      }  
#ifdef WITH_CAIRO
      else
	if (args.check("-outputEPS")){
	  string outputFileName= args.getOption("-outputSVG")->getValue(0);
	  aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoEPS );
	} else 
	  if (args.check("-outputPDF")){
	    string outputFileName= args.getOption("-outputPDF")->getValue(0);
	    aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPDF );
	  } else 
	    if (args.check("-outputPNG")){
	      string outputFileName= args.getOption("-outputPNG")getValue(0);
	      aBoard.saveCairo(outputFileName.c_str(),Board2D::CairoPNG );
	    }
#endif
	    else { //default output
	      string outputFileName= "output.eps";
	      aBoard.saveEPS(outputFileName.c_str());
	    }
  
}
int main(int argc, char** argv)
{

  Point ptL(-1, -1);
  Point ptU(3, 3);
  Domain d (ptL, ptU);    
    
  Point pt0(0,0);
  Point pt1(1,0);
  Point pt2(0,1);
  Point pt3(2,1);
  Point pt4(1,2);
  Point pt5(2,2);
  
  
  DigitalSet aSet( d );
  aSet.insert(pt0);
  aSet.insert(pt1);
  aSet.insert(pt2);
  aSet.insert(pt3);
  aSet.insert(pt4);
  
  Board2D boardAdj;

  boardAdj << d;    

  
  std::set<SCell> bdry;
  Z2i::KSpace ks;  
  ks.init( ptL, ptU, true );

  boardAdj << aSet;
  
  // Extracting the surface boundary of the shape
  Surfaces<Z2i::KSpace>::sMakeBoundary( bdry, ks, aSet, ks.lowerBound(), ks.upperBound() );

  SurfelAdjacency<Z2i::KSpace::dimension>  sAdjInt( true );
  SurfelAdjacency<Z2i::KSpace::dimension>  sAdjExt( false );
  

  //Displaying the boundary bels
  std::set<SCell>::iterator itBoundary;
  int i=0;

  Board2D boardDisplayAll;
  boardDisplayAll<< d;
  boardAdj.saveFIG("illustrationAdjSRC.fig");
  for(itBoundary= bdry.begin(); itBoundary!= bdry.end(); itBoundary++){
    boardDisplayAll << *itBoundary;
  }
  boardDisplayAll.saveFIG("illustrationAdjBdr.fig");

  itBoundary = bdry.begin();
  for (int i =0; i<10; i++) itBoundary++;
  SCell surfel = *itBoundary;
  
  // Defining surfel Neighborhood given an surfel Adjacency
  SurfelNeighborhood<KSpace> sNeighInt;
  sNeighInt.init( &ks, &sAdjInt, surfel );
  
  SurfelNeighborhood<KSpace> sNeighExt;
  sNeighExt.init( &ks, &sAdjExt, surfel );
  
  
  SCell surfelFollowerInt;
  SCell surfelFollowerExt;

  sNeighInt.getAdjacentOnDigitalSet ( surfelFollowerInt, aSet, *(ks.sDirs(surfel)), true);
  sNeighExt.getAdjacentOnDigitalSet ( surfelFollowerExt, aSet, *(ks.sDirs(surfel)), true);
  
  
  
  boardAdj <<  CustomStyle( surfel.className() ,
			    new CustomColors( Color::Blue,
					      Color::Gray ));
  boardAdj << surfel;
  
  boardAdj <<  CustomStyle( surfel.className() ,
			    new CustomColors( Color::Red,
					      Color::Black ));

  boardAdj << surfelFollowerInt;
  boardAdj <<  CustomStyle( surfel.className() ,
			    new CustomColors( Color::Green,
					      Color::White ));
  boardAdj << surfelFollowerExt;

  
  boardAdj.saveFIG("illustrationAdjIntExt.fig");
  

  
  // Extraction of contour
  std::set<SCell> aContour1;
  Surfaces<Z2i::KSpace>::trackBoundary( aContour1, ks, 
					sAdjExt,
					aSet, surfel ); 
		    
  Board2D boardContour1;
  boardContour1 << d;
  std::set<SCell>::iterator iterOnContour;
  for( iterOnContour= aContour1.begin(); iterOnContour != aContour1.end(); iterOnContour++){
    if(*iterOnContour != surfel){
      boardContour1 <<  CustomStyle( surfel.className() ,
				     new CustomColors( Color::Green,
						       Color::White ));
      boardContour1<< *iterOnContour;
    }else{
				 
      boardContour1 <<  CustomStyle( surfel.className() ,
				     new CustomColors( Color::Blue,
						       Color::Gray ));
      boardContour1<< *iterOnContour;
    }
  }
  boardContour1.saveFIG("illustrationAdjContour.fig");



  // Extraction of contour
  std::set<SCell> aContour2;
  Surfaces<Z2i::KSpace>::trackBoundary( aContour2, ks, 
					sAdjInt,
					aSet, surfel ); 
  Board2D boardContour2;
  boardContour2 << d;
  std::set<SCell>::iterator iterOnContour2;
  for( iterOnContour2= aContour2.begin(); iterOnContour2 != aContour2.end(); iterOnContour2++){
    if(*iterOnContour2 != surfel){
      boardContour2 <<  CustomStyle( surfel.className() ,
				     new CustomColors( Color::Red,
						       Color::White ));
      boardContour2<< *iterOnContour2;
    }else{
      
      boardContour2 <<  CustomStyle( surfel.className() ,
				     new CustomColors( Color::Blue,
						       Color::Gray ));
      boardContour2<< *iterOnContour2;
    }
  }
  boardContour2.saveFIG("illustrationAdjContour2.fig");









  return 0;
}