Esempio n. 1
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());
      }
  
}
int main ()
{
  
  Delaunay t;
  
  trace.beginBlock("Construction the shape");
  typedef Ellipse2D<Z2i::Space> Ellipse; 
  int a = 5, b = 3;
  Ellipse2D<Z2i::Space> ellipse(Z2i::Point(0,0), a, b, 0.3 );
  // Ellipse2D<Z2i::Space> ellipse(Z2i::Point(0,0), 5.5, 5.5, 0 );
  double h = 0.25; 
  GaussDigitizer<Z2i::Space,Ellipse> dig;  
  dig.attach( ellipse );
  dig.init( ellipse.getLowerBound()+Z2i::Vector(-1,-1),
            ellipse.getUpperBound()+Z2i::Vector(1,1), h ); 
  // typedef Flower2D<Z2i::Space> Flower; 
  // Flower2D<Z2i::Space> flower(Z2i::Point(0,0), 15, 2, 5, 0);
  // double h = 0.25; 
  // GaussDigitizer<Z2i::Space,Flower> dig;  
  // dig.attach( flower );
  // dig.init( flower.getLowerBound()+Z2i::Vector(-1,-1),
  //           flower.getUpperBound()+Z2i::Vector(1,1), h ); 
  Z2i::KSpace ks;
  ks.init( dig.getLowerBound(), dig.getUpperBound(), true );
  SurfelAdjacency<2> sAdj( true );
  Z2i::SCell bel = Surfaces<Z2i::KSpace>::findABel( ks, dig, 1000 );
  std::vector<Z2i::Point> boundaryPoints;
  Surfaces<Z2i::KSpace>
    ::track2DBoundaryPoints( boundaryPoints, ks, sAdj, dig, bel );
  Z2i::Curve c;
  c.initFromVector( boundaryPoints );  
  typedef Z2i::Curve::PointsRange Range; 
  Range r = c.getPointsRange(); 
  trace.endBlock();


  trace.beginBlock("Delaunay");
  for(Range::ConstIterator it=r.begin(), itend=r.end(); it != itend;
      ++it)
    { 
      t.insert( Point( (*it)[0], (*it)[1]));
      t.insert( Point( (*it)[0] + 3 + (int) ceil( ((double)b)/h ),
		       (*it)[1] - 3 - (int) ceil( ((double)a)/h ) ));
    }
  trace.endBlock();

  std::cout << "number of vertices :  " ;
  std::cout << t.number_of_vertices() << std::endl;
  std::cout << "number of faces :  " ;
  std::cout << t.number_of_faces() << std::endl;
  
  trace.beginBlock("Area minimizing triangulation");
  Edge_iterator itnext;
  bool flip = true;
  bool inverse = false;
  unsigned int pass = 0;
  while ( flip ) {
    std::cout << "----------- pass " << pass << " -------------------" << std::endl;
    inverse = false;
    flip = false;
    int nb_flip = 0;
    int nb_random_flip = 0;
    for( Edge_iterator it = t.edges_begin(), itend=t.edges_end();
	 it != itend; it = itnext )
      {
	// vertex(cw(i)) and vertex(ccw(i)) of f.
	itnext = it; ++itnext;
	Edge e1 = *it;
	if ( isEdgeElementary( t,
			       e1.first->vertex( t.ccw( e1.second ) ),
			       e1.first->vertex( t.cw( e1.second ) ) ) )
	  continue;
	Edge e2 = t.mirror_edge( e1 );
	if ( ! isQuadrilateral( t, 
				e1.first->vertex( e1.second ),
				e1.first->vertex( t.ccw( e1.second ) ),
				e2.first->vertex( e2.second ),
				e1.first->vertex( t.cw( e1.second ) ) ) )
	  continue;
	int nb_f1 = twiceNbLatticePointsInTriangle( t, e1.first );
	int nb_f2 = twiceNbLatticePointsInTriangle( t, e2.first );
	int nb_flip_f1 = twiceNbLatticePointsInTriangle( t,
							 e1.first->vertex( e1.second ), 
							 e1.first->vertex( t.ccw( e1.second ) ),
							 e2.first->vertex( e2.second ) );
	int nb_flip_f2 = twiceNbLatticePointsInTriangle( t,
							 e1.first->vertex( e1.second ), 
							 e1.first->vertex( t.cw( e1.second ) ),
							 e2.first->vertex( e2.second ) );
	int nb_min = nb_f1 <= nb_f2 ? nb_f1 : nb_f2;
	int nb_flip_min = nb_flip_f1 <= nb_flip_f2 ? nb_flip_f1 : nb_flip_f2;
	if ( nb_flip_min < nb_min )
	  {
	    std::cout << "flipped " << e1.first->vertex( e1.second )->point()
		      << "->" << e1.first->vertex( e1.second )->point()
		      << std::endl;
	    t.flip( e1.first, e1.second );
	    nb_flip++;
	    flip = true;
	  }
	if ( nb_flip_min == nb_min )
	  {
	    inverse = true;
	    if ( random() % 2 == 1 )
	      {
		std::cout << "Random flipped " << e1.first->vertex( e1.second )->point()
			  << "->" << e1.first->vertex( e1.second )->point()
			  << std::endl;
		t.flip( e1.first, e1.second );
		nb_random_flip++;
	      }
	  }
	// if ( ( empty_f1 == false )
	//      && ( empty_f2 == false ) )
	//   { // try if flip is better.
	//     bool empty_flip_f1 
	//       = twiceNbLatticePointsInTriangle( t,
	// 					e1.first->vertex( e1.second ), 
	// 					e1.first->vertex( t.ccw( e1.second ) ),
	// 					e2.first->vertex( e2.second ) ) == 0;
	//     bool empty_flip_f2 
	//       = twiceNbLatticePointsInTriangle( t,
	// 					e2.first->vertex( e2.second ), 
	// 					e2.first->vertex( t.ccw( e2.second ) ),
	// 					e1.first->vertex( e1.second ) ) == 0;
	//     if ( empty_flip_f1 || empty_flip_f2 )
	//       {
	// 	if ( isEdgeElementary( t,
	// 			       e1.first->vertex( t.ccw( e1.second ) ),
	// 			       e1.first->vertex( t.cw( e1.second ) ) ) )
	// 	  {
	// 	    std::cout << "Flip forbidden:  " << e1.first->vertex( e1.second )->point()
	// 		  << "->" << e1.first->vertex( e1.second )->point()
	// 		  << std::endl;
	// 	  }
	// 	else
	// 	  {
	// 	    std::cout << "flipped " << e1.first->vertex( e1.second )->point()
	// 		      << "->" << e1.first->vertex( e1.second )->point()
	// 		      << std::endl;
	// 	    t.flip( e1.first, e1.second );
	// 	    flip = true;
	// 	  }
	//       }
	//   }
      }
    std::cout << "----------- nb_flip " << nb_flip 
	      << ", nb_random " << nb_random_flip << " -------------" << std::endl;
    ++pass;
    if ( inverse && ( (nb_random_flip+4) > log(pass) ) ) 
      flip = true;
  }  
  trace.endBlock();


  // GridCurve
  Z2i::Curve gc;
  gc.initFromPointsRange( r.begin(), r.end() );
  typedef Z2i::Curve::PointsRange::ConstIterator ConstIterator;
  typedef ArithmeticalDSS<ConstIterator,int,4> DSS4;
  typedef SaturatedSegmentation<DSS4> Segmentation;
  //Segmentation
  Z2i::Curve::PointsRange range = gc.getPointsRange();
  DSS4 dss4RecognitionAlgorithm;
  Segmentation theSegmentation( range.begin(), range.end(), dss4RecognitionAlgorithm );
         

  DGtal::Board2D board;

  Z2i::Point dP;
  board << CustomStyle( dP.className(), 
                        new CustomPen( Color(0,0,0), Color(230,230,230), 1, 
                                       Board2D::Shape::SolidStyle,
                                       Board2D::Shape::RoundCap,
                                       Board2D::Shape::RoundJoin ));
  for(Range::ConstIterator it=r.begin(), itend=r.end(); it != itend;
      ++it)
    board << *it;
  
  for(Faces_iterator it = t.finite_faces_begin(), itend=t.finite_faces_end();
      it != itend; ++it)
    {
      Z2i::Point a( toDGtal(it->vertex(0)->point())),
	b(toDGtal(it->vertex(1)->point())),
	c(toDGtal(it->vertex(2)->point()));

      // Z2i::Vector ab( b - a ), ac( c - a );
      // int d = ab[ 0 ] * ac[ 1 ] - ab[ 1 ] * ac[ 0 ];
      if ( emptyLatticeTriangle( t, it ) ) //( ( d == 1 ) || (d == -1 ) )
        {
          board.setPenColor(DGtal::Color::Blue);
          board.setFillColor( DGtal::Color::None );
          board.setLineWidth( 3.0 );
          board.drawTriangle(a[0],a[1],b[0],b[1],c[0],c[1]);
        }
      else
        {
          board.setPenColor(DGtal::Color::Red);
          board.setFillColor( DGtal::Color::None );
          //          board.setFillColorRGBi(200,200,200,128);
          board.setLineWidth( 2.0 );
          board.drawTriangle(a[0],a[1],b[0],b[1],c[0],c[1]);
        }
    }

  Segmentation::SegmentComputerIterator i = theSegmentation.begin();
  Segmentation::SegmentComputerIterator end = theSegmentation.end();
  board.setPenColor(DGtal::Color::Green);
  board.setFillColor( DGtal::Color::None );
  board << SetMode( "ArithmeticalDSS", "BoundingBox" );
  std::string aStyleName = "ArithmeticalDSS/BoundingBox";
  for ( ; i != end; ++i) {
    DSS4 current(*i);
    board << CustomStyle( aStyleName, 
                          new CustomPenColor( DGtal::Color::Green ) )
          << current;
  } 

  // Display Voronoi.
  // for(Edge_iterator it = t.edges_begin(), itend=t.edges_end();
  //     it != itend; ++it)
  //   {
  //     // vertex(cw(i)) and vertex(ccw(i)) of f.
  //     Face_handle itf = it->first;
  //     int i = it->second;
  //     Z2i::Point a( toDGtal(itf->vertex( t.cw( i ) )->point()));
  //     Z2i::Point b( toDGtal(itf->vertex( t.ccw( i ) )->point()));

  //     CGAL::Object o = t.dual( it );
  //     if (CGAL::object_cast<K::Segment_2>(&o)) 
  //       {
  //         const K::Segment_2* ptrSegment = CGAL::object_cast<K::Segment_2>(&o);
  //         board.setPenColor(DGtal::Color::Black);
  //         board.setFillColor( DGtal::Color::None );
  //         board.setLineWidth( 2.0 );
  //         board.drawLine( ptrSegment->source().x(),
  //                         ptrSegment->source().y(),
  //                         ptrSegment->target().x(),
  //                         ptrSegment->target().y() );
  //       }
  //     else if (CGAL::object_cast<K::Ray_2>(&o)) 
  //       {
  //         const K::Ray_2* ptrRay = CGAL::object_cast<K::Ray_2>(&o);
  //         board.setPenColor(DGtal::Color::Black);
  //         board.setFillColor( DGtal::Color::None );
  //         board.setLineWidth( 2.0 );
  //         double dx = ptrRay->to_vector().x();
  //         double dy = ptrRay->to_vector().y();
  //         double norm = sqrt( dx*dx+dy*dy );
  //         dx = 5.0 * dx / norm;
  //         dy = 5.0 * dy / norm;
  //         board.drawArrow( ptrRay->source().x(),
  //                          ptrRay->source().y(),
  //                          ptrRay->source().x() + dx, //1*ptrRay->to_vector().x(),
  //                          ptrRay->source().y() + dy ); //1*ptrRay->to_vector().y() );
  //       }
  //   }

  
  board.saveSVG("delaunay.svg");
  board.saveEPS("delaunay.eps");
  
  return 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());
	    }
  
}
Esempio n. 4
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)")    
    ("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>  contours.fc --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>();
  }
  
  DGtalBoard 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( DGtalBoard::Color::Red  ,  DGtalBoard::Color::None ) );    
   for(unsigned int i=0; i<vectFc.size(); i++){
     aBoard <<  vectFc.at(i) ;
   }
 }
 
 

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<  RealPointVector<2>  >  contour = 
      PointListReader<  RealPointVector<2>  >::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(DGtalBoard::Color::Red);
  aBoard.setLineStyle (LibBoard::Shape::SolidStyle );
  aBoard.setLineWidth (lineWidth);
  aBoard.drawPolyline(contourPt);
  
  
 }

 


  string outputFileName= "output.eps";

  

  
  if (vm.count("outputSVG")){
    string outputFileName= vm["outputSVG"].as<string>();
    aBoard.saveSVG(outputFileName.c_str());
  }
  
  if (vm.count("outputFIG")){
    string outputFileName= vm["outputFIG"].as<string>();
    aBoard.saveFIG(outputFileName.c_str());
  }
#ifndef WITH_CAIRO
  if (vm.count("outputEPS")){
    string outputFileName= vm["outputEPS"].as<string>();
    aBoard.saveEPS(outputFileName.c_str());
  }  
#endif

#ifdef WITH_CAIRO
  if (vm.count("outputEPS")){
    string outputFileName= vm["outputEPS"].as<string>();
    aBoard.saveCairo(outputFileName.c_str(),DGtalBoard::CairoEPS );
  }
  if (vm.count("outputPDF")){
    string outputFileName= vm["outputPDF"].as<string>();
    aBoard.saveCairo(outputFileName.c_str(),DGtalBoard::CairoPDF );
  }
  if (vm.count("outputPNG")){
    string outputFileName= vm["outputPNG"].as<string>();
    aBoard.saveCairo(outputFileName.c_str(),DGtalBoard::CairoPNG );
  }
#endif


  

	
}