Esempio n. 1
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;
}
int main()
{
  trace.beginBlock ( "Example dgtalboard-3-custom-classes" );

  Point p1( -3, -2 );
  Point p2( 7, 3 );
  Point p3( 0, 0 );
  Domain domain( p1, p2 );

  Color red( 255, 0, 0 );
  Color dred( 192, 0, 0 );
  Color dgreen( 0, 192, 0 );
  Color blue( 0, 0, 255 );
  Color dblue( 0, 0, 192 );
  
  Board2D board;
  board << domain 
  << CustomStyle( p1.styleName(), new CustomColors( red, dred ) )
  << p1
  << CustomStyle( p2.styleName(), new CustomFillColor( dgreen ) )
  << p2
  << CustomStyle( p3.styleName(), 
      new CustomPen( blue, dblue, 6.0, 
               Board2D::Shape::SolidStyle,
               Board2D::Shape::RoundCap,
               Board2D::Shape::RoundJoin ) )
  << p3;
  board.saveSVG("dgtalboard-3-custom-classes.svg");
  board.saveEPS("dgtalboard-3-custom-classes.eps");

#ifdef WITH_CAIRO
  board.saveCairo("dgtalboard-3-custom-classes-cairo.pdf", Board2D::CairoPDF);
  board.saveCairo("dgtalboard-3-custom-classes-cairo.png", Board2D::CairoPNG);
  board.saveCairo("dgtalboard-3-custom-classes-cairo.ps", Board2D::CairoPS);
  board.saveCairo("dgtalboard-3-custom-classes-cairo.svg", Board2D::CairoSVG);
#endif
  
  trace.endBlock();
  return 0;
}
Esempio n. 3
0
int main(int /*argc*/, char** /*argv*/)
{
  


////////////////////////////////////////
  Board2D board;
  board.setUnit(Board2D::UCentimeter);
  board.drawArc(0.0, 1.0, 5.0, 0, M_PI/2.0, false); 
  board.drawArc(0.0, 1.0, 4.0, 0, M_PI/2.0, true); 
  board.drawArc(0.0, 1.0, 3.0, -0.5, M_PI/2.0-0.5, false); 
  board.drawArc(0.0, 1.0, 2.0, 0.5, M_PI/2.0+0.5, false); 
  board.saveEPS( "essai.eps" );
  board.saveSVG( "essai.svg" );  
  board.saveTikZ( "essai.tikz" );
#ifdef WITH_CAIRO
    board.saveCairo("essai.pdf", Board2D::CairoPDF);
#endif
////////////////////////////////////////

  return 0;
}
/**
* Save the granometric function values stored in an image into an EPS file
*
* @param granuloImage The image containing the granulometric function values
*
* @param maxGranulo The maximum value of the granulometric function
*
* @param fileName A string containing the filename where we store the image
*/
void saveGranulo(myLittleImage& granuloImage, unsigned int maxGranulo, string fileName)
{
	Board2D board;
	HueTwice colorMap(1,maxGranulo+1);
	Point O(0,0);
	string specificStyle =  O.className() + "/Paving";
	Color white(255,255,255);
    board << SetMode(granuloImage.domain().className(), "Paving")
      	  << granuloImage.domain()
          << SetMode(O.className(), "Paving");

   	for (myLittleImage::Domain::ConstIterator it = granuloImage.domain().begin(); it != granuloImage.domain().end(); ++it)
    {
    	if (granuloImage(*it) > 0)
		{
			Color c = colorMap(granuloImage(*it));
       		board << CustomStyle(specificStyle, new CustomColors(c,c)) << *it;
		}
		else
			board << CustomStyle(specificStyle, new  CustomColors(white,white)) << *it;
    }
    board.saveEPS(fileName.c_str());
}
int 
main(int argc, char ** argv){
  typedef Z2i::Point Point;
  std::vector<Point> contour = PointListReader<Point>::getPointsFromFile("../Samples/contourS.sdp");
  Board2D aBoard;
  for (auto&& p :contour) {
    aBoard << p;
  }
  aBoard.setPenColor(DGtal::Color::Red);
  aBoard.setFillColor(DGtal::Color::Red);
  aBoard.drawCircle(contour[30][0], contour[30][1],1); 
  unsigned int startIndex = 30;
  typedef  AlphaThickSegmentComputer< Z2i::Point > AlphaThickSegmentComputer2D;
  AlphaThickSegmentComputer2D aComputer(5);
  aComputer.init(contour.begin()+30);
  while(aComputer.extendFront()){
  }

  aBoard  << CustomStyle( aComputer.className(), new CustomColors( DGtal::Color::Blue, DGtal::Color::None ) );  
  aBoard << aComputer;
  aBoard.saveEPS("resultTuto2.eps");
  
  return 0;
}
Esempio n. 6
0
int main()
{
  trace.beginBlock ( "Example dgtalboard-1-points" );

  Point p1( -3, -2 );
  Point p2( 7, 3 );
  Point p3( 0, 0 );
  Domain domain( p1, p2 );
  
  Board2D board;
  board << domain << p1 << p2 << p3;
  board.saveSVG("dgtalboard-1-points.svg");
  board.saveEPS("dgtalboard-1-points.eps");

#ifdef WITH_CAIRO
  board.saveCairo("dgtalboard-1-points-cairo.pdf", Board2D::CairoPDF);
  board.saveCairo("dgtalboard-1-points-cairo.png", Board2D::CairoPNG);
  board.saveCairo("dgtalboard-1-points-cairo.ps", Board2D::CairoPS);
  board.saveCairo("dgtalboard-1-points-cairo.svg", Board2D::CairoSVG);
#endif
  
  trace.endBlock();
  return 0;
}
bool testCircleFrom3Points()
{

  trace.beginBlock("Simple test for CircleFrom3Points"); 
  
  typedef PointVector<2,Coordinate> Point; 
  CircleFrom3Points<Point> c; 
  Point o(0,0); 

  {
    c.init( Point(0,1), Point(150,18), Point(250,-48) ); 
    trace.info() << c << endl;
    trace.info() << o << " is at distance " << c.signedDistance(o) << endl;
    if (c.signedDistance(o) != -4026300) return false; 
  }
  {
    c.init( Point(0,1), Point(150,18), Point(100,48) ); 
    trace.info() << c << endl;
    trace.info() << o << " is at distance " << c.signedDistance(o) << endl;
    if (c.signedDistance(o) != 442200) return false; 
  }
  {
    c.init( Point(8,4), Point(9,3), Point(10,0) ); 
    trace.info() << c << endl;
    trace.info() << o << " is at distance " << c.signedDistance(o) << endl;
    if (c.signedDistance(o) != 0) return false;
    double cx, cy, r; 
    c.getParameters(cx, cy, r); 
    if ( (cx != 5.0)||(cy != 0.0) )
    {
      trace.emphase() << "error in returned center" << endl;
      trace.info() << "(" << cx << "," << cy << ") " << endl;
      trace.info() << "instead of (5,0)" << endl;
      return false; 
    } 
  }
  {
    c.init( Point(0,0), Point(150,20), Point(15,2) ); 
    trace.info() << c << endl;
    trace.info() << o << " is at distance " << c.signedDistance(o) << endl;
    if (c.signedDistance(o) != 0) return false; 
  }

  Board2D board; 
  board << SetMode(o.className(), "Grid") << o; 
  {
    c.init( Point(8,4), Point(9,3), Point(10,0) ); 
    trace.info() << "arc drawing" << endl;
    
    board << SetMode( c.className(), "Arc" );
    Display2DFactory::draw(board, c, Point(5,10), Point(8,4));
    
    board << SetMode( c.className(), "Sector" );
    Display2DFactory::draw(board, c, Point(9,3), Point(10,0) );
    
    board << SetMode( c.className(), "Annulus" );
    Display2DFactory::draw(board, c, Point(5,-10), Point(2,-4) );
    
    board.saveEPS("arcDisplay.eps");
  }


  trace.endBlock(); 
  
  return true; 
}
bool testSurfelAdjacency()
{
  typedef typename KSpace::Integer Integer;
  typedef typename KSpace::Cell Cell;
  typedef typename KSpace::SCell SCell;
  typedef typename KSpace::Point Point;
  typedef typename KSpace::DirIterator DirIterator;
  typedef typename KSpace::Cells Cells;
  typedef typename KSpace::SCells SCells;
  unsigned int nbok = 0;
  unsigned int nb = 0;
  
  trace.beginBlock ( "Testing block KSpace instantiation and scan ..." );
  KSpace K;
  int xlow[ 4 ] = { -3, -3, -3, -3 };
  int xhigh[ 4 ] = { 5, 3, 3, 3 };
  Point low( xlow );
  Point high( xhigh ); 
  bool space_ok = K.init( low, high, true );
  nbok += space_ok ? 1 : 0; 
  nb++;
  trace.info() << "(" << nbok << "/" << nb << ") "
         << "K.init( low, high )" << std::endl;
  trace.info() << "K.dim()=" << K.dimension << endl;
  trace.endBlock();
  trace.beginBlock ( "Testing surfel adjacency ..." );
  SurfelAdjacency<KSpace::dimension> SAdj( true );
  for ( Dimension i = 0; i < K.dimension; ++i )
    for ( Dimension j = 0; j < K.dimension; ++j )
      if ( i != j )
  trace.info() << "(" << i << "," << j << ")=" 
         << ( SAdj.getAdjacency( i, j ) ? "i2e" : "e2i" );
  trace.info() << endl;
  trace.endBlock();

  int spel[ 4 ] = { 1, 1, 1, 1 }; // pixel
  Point kp( spel );
  SCell sspel = K.sCell( kp, K.POS );
  trace.beginBlock ( "Testing surfel directness ..." );
  for ( Dimension k = 0; k < K.dimension; ++k )
    {
      SCell surfel = K.sIncident( sspel, k, true );
      SCell innerspel = K.sDirectIncident( surfel, K.sOrthDir( surfel ) );
      trace.info() << "spel=" << sspel << " surfel=" << surfel
       << " innerspel=" << innerspel << endl;
      nbok += sspel == innerspel ? 1 : 0; 
      nb++;
      trace.info() << "(" << nbok << "/" << nb << ") "
       << "spel == innerspel" << std::endl;
      surfel = K.sIncident( sspel, k, false );
      innerspel = K.sDirectIncident( surfel, K.sOrthDir( surfel ) );
      trace.info() << "spel=" << sspel << " surfel=" << surfel
       << " innerspel=" << innerspel << endl;
      nbok += sspel == innerspel ? 1 : 0; 
      nb++;
      trace.info() << "(" << nbok << "/" << nb << ") "
       << "spel == innerspel" << std::endl;
    }
  trace.endBlock();

  SurfelNeighborhood<KSpace> SN;
  trace.beginBlock ( "Testing surfel neighborhood ..." );
  SCell surfel = K.sIncident( sspel, 0, false );
  SN.init( &K, &SAdj, surfel );
  trace.info() << "surfel      =" << surfel << endl;
  trace.info() << "follower1(+)=" << SN.follower1( 1, true ) << endl;
  trace.info() << "follower2(+)=" << SN.follower2( 1, true ) << endl;
  trace.info() << "follower3(+)=" << SN.follower3( 1, true ) << endl;
  trace.info() << "follower1(-)=" << SN.follower1( 1, false ) << endl;
  trace.info() << "follower2(-)=" << SN.follower2( 1, false ) << endl;
  trace.info() << "follower3(-)=" << SN.follower3( 1, false ) << endl;
  trace.endBlock();

  trace.beginBlock ( "Testing surface tracking ..." );
  typedef SpaceND< KSpace::dimension, Integer > Space;
  typedef HyperRectDomain<Space> Domain;
  typedef typename DigitalSetSelector< Domain, BIG_DS+HIGH_BEL_DS >::Type DigitalSet;
  Domain domain( low, high );
  DigitalSet shape_set( domain );
  SetPredicate<DigitalSet> shape_set_predicate( shape_set );
  int center[ 4 ] = { 1, 0, 0, 0 }; // pixel
  Point pcenter( center );
  Shapes<Domain>::addNorm1Ball( shape_set, pcenter, 1 );
  trace.info() << "surfel      = " << surfel << endl;
  SCell other1, other2;
  SN.getAdjacentOnDigitalSet( other1, shape_set, 1, K.sDirect( surfel, 1 ) );
  SN.getAdjacentOnDigitalSet( other2, shape_set, 1, !K.sDirect( surfel, 1 ) );
  trace.info() << "directNext  = " << other1 << endl;
  trace.info() << "indirectNext= " << other2 << endl;
  std::set<SCell> bdry;

  // surfel = Surfaces<KSpace>::findABel( K, shape_set );

  Surfaces<KSpace>::trackBoundary( bdry,
           K, SAdj, shape_set_predicate, surfel );
  trace.info() << "tracking finished, size=" << bdry.size() 
         << ", should be " << 2*K.dimension*(2*K.dimension-1) << endl;
  nbok += bdry.size() == ( 2*K.dimension*(2*K.dimension-1) ) ? 1 : 0; 
  nb++;
  trace.info() << "(" << nbok << "/" << nb << ") "
         << "bdry.size() == ( 2*K.dimension*(2*K.dimension-1) )"
         << std::endl;
  std::set<SCell> bdry_direct;
  Surfaces<KSpace>::trackClosedBoundary( bdry_direct,
           K, SAdj, shape_set_predicate, surfel );
  trace.info() << "fast direct tracking finished, size=" << bdry_direct.size() 
         << ", should be " << 2*K.dimension*(2*K.dimension-1) << endl;
  nbok += bdry_direct.size() == ( 2*K.dimension*(2*K.dimension-1) ) ? 1 : 0; 
  nb++;
  trace.info() << "(" << nbok << "/" << nb << ") "
         << "bdry_direct.size() == ( 2*K.dimension*(2*K.dimension-1) )"
         << std::endl;
  
  trace.endBlock();
  if ( K.dimension == 2 )
    {
      Board2D board;
      board.setUnit( LibBoard::Board::UCentimeter );
      board << SetMode( domain.className(), "Paving" )
      << domain;
      for ( typename std::set<SCell>::const_iterator it = bdry_direct.begin(),
        it_end = bdry_direct.end(); it != it_end; ++it )
  board << *it;
      board.saveEPS( "cells-2.eps" );
      board.saveSVG( "cells-2.svg" );
    }
  return nbok == nb;
}
bool testDistancePropagation()
{
  typedef Z2i::Space Space;
  typedef Z2i::Point Point;
  typedef Z2i::Domain Domain;
  typedef Z2i::DigitalSet DigitalSet;
  typedef Z2i::Object4_8 Object;
  
  BOOST_CONCEPT_ASSERT(( CUndirectedSimpleGraph<Z2i::Object4_8> ));

  trace.beginBlock( "Distance propagation in 2D object" );
  Point p1( -41, -36 );
  Point p2( 18, 18 );
  Domain domain( p1, p2 );
  Point c1( -2, -1 );
  Point c2( -14, 5 );
  Point c3( -30, -15 );
  Point c4( -10, -20 );
  Point c5( 12, -1 );
  DigitalSet shape_set( domain );
  
  Shapes<Domain>::addNorm2Ball( shape_set, c1, 9 );
  Shapes<Domain>::addNorm1Ball( shape_set, c2, 9 );
  Shapes<Domain>::addNorm1Ball( shape_set, c3, 10 );
  Shapes<Domain>::addNorm2Ball( shape_set, c4, 12 );
  Shapes<Domain>::addNorm1Ball( shape_set, c5, 4 );

  Object obj(Z2i::dt4_8, shape_set);
  
  
  GradientColorMap<int> cmap_grad( 0, 25);
  cmap_grad.addColor( Color( 0, 0, 255 ) );
  cmap_grad.addColor( Color( 0, 255, 0 ) );
  cmap_grad.addColor( Color( 255, 0, 0 ) );
  
  Board2D board;
  board << SetMode( domain.className(), "Paving" )
        << domain
        << SetMode( p1.className(), "Paving" );
  
  Image image = ImageFromSet<Image>::create(shape_set, 1);
  
  // Type definitions
  typedef CanonicEmbedder<Space> VertexEmbedder;
  typedef VertexEmbedder::Value RealPoint;
  typedef RealPoint::Coordinate Scalar;
  typedef ExactPredicateLpSeparableMetric<Space,2> Distance;
  typedef std::binder1st< Distance > DistanceToPoint; 
  typedef DGtal::functors::Composer<VertexEmbedder, DistanceToPoint, Scalar> VertexFunctor;
  typedef DistanceBreadthFirstVisitor< Object, VertexFunctor, std::set<Point> > Visitor;

  BOOST_CONCEPT_ASSERT(( CGraphVisitor<Visitor> ));


  VertexEmbedder embedder;
  Distance distance;
  DistanceToPoint distanceToPoint = std::bind1st( distance, embedder( c1 ) );
  VertexFunctor vfunctor( embedder, distanceToPoint );
  Visitor visitor( obj, vfunctor, c1 );
  
  while( ! visitor.finished() )
    {
      Scalar v = visitor.current().second;
      image.setValue( visitor.current().first, v ); 
      visitor.expand();
    }
  
  string specificStyle = p1.className() + "/Paving";
  
  for ( DigitalSet::ConstIterator it = shape_set.begin();
        it != shape_set.end();
        ++it )
    {
      if( image(*it) == 0)
        board << CustomStyle( specificStyle,
                              new CustomColors( Color::Black,
                                                Color::Red ) );
      else if( image(*it) > 0 )
        board << CustomStyle( specificStyle,
                              new CustomColors( Color::Black,
                                                cmap_grad( image(*it) ) ) );
      else
        board << CustomStyle( specificStyle,
                              new CustomColors( Color::Black,
                                                cmap_grad( 0 ) ) );
      board << *it;
    }

  trace.info() << "- Output file testDistancePropagation.eps" << std::endl;
  board.saveEPS("testDistancePropagation.eps");
  trace.endBlock();

  trace.beginBlock( "Distance visitor as a range." );
  typedef GraphVisitorRange<Visitor> VisitorRange;
  VisitorRange range( new Visitor( obj, vfunctor, c1 ) );
  Scalar d = -1.0;
  unsigned int nb = 0;
  unsigned int nbok = 0;
  unsigned int nbperfect = 0;
  for ( VisitorRange::NodeConstIterator it = range.beginNode(), itEnd = range.endNode();
        it != itEnd; ++it )
    { // Vertex is *it.first
      Scalar next_d = (*it).second;
      ++nb, nbok += (next_d >= d-0.75 ) ? 1 : 0;
      nbperfect += (next_d >= d ) ? 1 : 0;
      d = next_d;
    }
  trace.info() << "(" << nbok << "/" << nb 
               << ") number of vertices in approximate Euclidean distance ordering."<< std::endl;
  trace.info() << "(" << nbperfect << "/" << nb 
               << ") number of vertices in perfect Euclidean distance ordering."<< std::endl;
  trace.endBlock();
  return nb == nbok;
}
Esempio n. 10
0
int main()
{

    //! [freemanChainFromImage-imageImport]
    typedef DGtal::ImageContainerBySTLVector< DGtal::Z2i::Domain, unsigned char> Image;
    std::string filename =  examplesPath + "samples/circleR10modif.pgm";
    Image image = DGtal::PGMReader<Image>::importPGM(filename);
    //! [freemanChainFromImage-imageImport]

    //![freemanChainFromImage-ksspace]
    Z2i::KSpace ks;
    ks.init( image.domain().lowerBound(), image.domain().upperBound(), true );
    //![freemanChainFromImage-ksspace]

    //! [freemanChainFromImage-setAppend]
    Z2i::DigitalSet set2d (image.domain());
    SetFromImage<Z2i::DigitalSet>::append<Image>(set2d, image, 1, 255);
    //! [freemanChainFromImage-setAppend]


    //! [freemanChainFromImage-displaySet]
    Board2D aBoard;
    aBoard << set2d;
    aBoard << image.domain();
    //! [freemanChainFromImage-displaySet]

    //! [freemanChainFromImage-adj]
    SurfelAdjacency<2> sAdj( true );
    //! [freemanChainFromImage-adj]

    //! [freemanChainFromImage-extraction]
    std::vector< std::vector< Z2i::Point >  >  vectContoursBdryPointels;
    Surfaces<Z2i::KSpace>::extractAllPointContours4C( vectContoursBdryPointels,
            ks, set2d, sAdj );
    //! [freemanChainFromImage-extraction]


    GradientColorMap<int> cmap_grad( 0, (const int)vectContoursBdryPointels.size() );
    cmap_grad.addColor( Color( 50, 50, 255 ) );
    cmap_grad.addColor( Color( 255, 0, 0 ) );
    cmap_grad.addColor( Color( 255, 255, 10 ) );
    cmap_grad.addColor( Color( 25, 255, 255 ) );
    cmap_grad.addColor( Color( 255, 25, 255 ) );
    cmap_grad.addColor( Color( 25, 25, 25 ) );

    //! [freemanChainFromImage-fcConstruction]
    for(unsigned int i=0; i<vectContoursBdryPointels.size(); i++) {
        //  Constructing and displaying FreemanChains from contours.
        FreemanChain<Z2i::Integer> fc (vectContoursBdryPointels.at(i));
        //! [freemanChainFromImage-fcConstruction]
        //! [freemanChainFromImage-fcdysplay]
        aBoard << SetMode( fc.className(), "InterGrid" );
        aBoard<< CustomStyle( fc.className(),
                              new CustomColors(  cmap_grad(i),  Color::None ) );
        aBoard << fc;
        //! [freemanChainFromImage-fcdysplay]
    }

    aBoard.saveEPS("freemanChainFromImage.eps");
    return 0;
}
Esempio n. 11
0
int main( int argc, char** argv )
{
  using namespace DGtal;
  using namespace DGtal::Z2i;
  
  typedef ImageContainerBySTLVector<Domain,unsigned char> GrayLevelImage2D;
  typedef ImageContainerBySTLVector<Domain,float>         FloatImage2D;
  typedef DistanceToMeasure<FloatImage2D>                 Distance;
  if ( argc <= 3 ) return 1;
  GrayLevelImage2D img  = GenericReader<GrayLevelImage2D>::import( argv[ 1 ] );
  double           mass = atof( argv[ 2 ] );
  double           rmax = atof( argv[ 3 ] );
  FloatImage2D     fimg( img.domain() );
  FloatImage2D::Iterator outIt = fimg.begin();
  for ( GrayLevelImage2D::ConstIterator it = img.begin(), itE = img.end();
        it != itE; ++it )
    {
      float v = ((float)*it) / 255.0;
      *outIt++ = v;
    }
  trace.beginBlock( "Computing delta-distance." );
  Distance     delta( mass, fimg, rmax );
  const FloatImage2D& d2 = delta.myDistance2;
  trace.endBlock();

  float m = 0.0f;
  for ( typename Domain::ConstIterator it = d2.domain().begin(),
          itE = d2.domain().end(); it != itE; ++it )
    {
      Point p = *it;
      float v = sqrt( d2( p ) );
      m = std::max( v, m );
    }

  GradientColorMap<float> cmap_grad( 0, m );
  cmap_grad.addColor( Color( 255, 255, 255 ) );
  cmap_grad.addColor( Color( 255, 255, 0 ) );
  cmap_grad.addColor( Color( 255, 0, 0 ) );
  cmap_grad.addColor( Color( 0, 255, 0 ) );
  cmap_grad.addColor( Color( 0,   0, 255 ) );
  cmap_grad.addColor( Color( 0,   0, 0 ) );
  Board2D board;
  board << SetMode( d2.domain().className(), "Paving" );
  

  for ( typename Domain::ConstIterator it = d2.domain().begin(),
          itE = d2.domain().end(); it != itE; ++it )
    {
      Point p = *it;
      float v = sqrt( d2( p ) );
      v = std::min( (float)m, std::max( v, 0.0f ) ); 
      board << CustomStyle( p.className(),
                            new CustomColors( Color::Black, cmap_grad( v ) ) )
            << p;

      RealVector grad = delta.projection( p );
      board.drawLine( p[ 0 ], p[ 1 ], p[ 0 ] + grad[ 0 ], p[ 1 ] + grad[ 1 ], 0 );
    }
  std::cout << endl;
  board.saveEPS("delta2.eps");
  return 0;
}
Esempio n. 12
0
int main( )
{
  trace.beginBlock ( "Example dgtalboard-2-sets" );

  Point p1( -10, -7 );
  Point p2( 10, 7 );
  Domain domain( p1, p2 );
  DigitalSet shape_set( domain );
  Shapes<Domain>::addNorm1Ball( shape_set, Point( -5, -1 ), 5 );
  Shapes<Domain>::addNorm1Ball( shape_set, Point( 5, 1 ), 5 );
  shape_set.erase( Point( -5, -1 ) );
  shape_set.erase( Point( 5, 1 ) );

  Board2D board;
  board << domain << shape_set; // display domain and set
  board.saveSVG( "dgtalboard-2-sets-1.svg");
  board.saveEPS( "dgtalboard-2-sets-1.eps");
  
#ifdef WITH_CAIRO
  board.saveCairo("dgtalboard-2-sets-1-cairo.pdf", Board2D::CairoPDF);
  board.saveCairo("dgtalboard-2-sets-1-cairo.png", Board2D::CairoPNG);
  board.saveCairo("dgtalboard-2-sets-1-cairo.ps", Board2D::CairoPS);
  board.saveCairo("dgtalboard-2-sets-1-cairo.svg", Board2D::CairoSVG);
#endif

  board.clear();

  // Object with couple (4,8) of adjacency.
  Object4_8 shape( dt4_8, shape_set );
  board << domain // display domain
  << SetMode( shape.styleName(), "DrawAdjacencies" )
  << shape; // and object with mode "DrawAdjacencies"
  board.saveSVG( "dgtalboard-2-sets-2.svg");
  board.saveEPS( "dgtalboard-2-sets-2.eps");
 
#ifdef WITH_CAIRO
  board.saveCairo("dgtalboard-2-sets-2-cairo.pdf", Board2D::CairoPDF);
  board.saveCairo("dgtalboard-2-sets-2-cairo.png", Board2D::CairoPNG);
  board.saveCairo("dgtalboard-2-sets-2-cairo.ps", Board2D::CairoPS);
  board.saveCairo("dgtalboard-2-sets-2-cairo.svg", Board2D::CairoSVG);
#endif

  board.clear();

  // Object with couple (8,4) of adjacency.
  Object8_4 shape2( dt8_4, shape_set );
  board << domain // display domain
  << SetMode( shape2.styleName(), "DrawAdjacencies" )
  << shape2; // and object with mode "DrawAdjacencies"
  board.saveSVG( "dgtalboard-2-sets-3.svg");
  board.saveEPS( "dgtalboard-2-sets-3.eps");

#ifdef WITH_CAIRO
  board.saveCairo("dgtalboard-2-sets-3-cairo.pdf", Board2D::CairoPDF);
  board.saveCairo("dgtalboard-2-sets-3-cairo.png", Board2D::CairoPNG);
  board.saveCairo("dgtalboard-2-sets-3-cairo.ps", Board2D::CairoPS);
  board.saveCairo("dgtalboard-2-sets-3-cairo.svg", Board2D::CairoSVG);
#endif

  trace.endBlock();
  return 0;
}
Esempio n. 13
0
int main()
{
  Domain domain(Point(0,0), Point(2,2));
  
  //Testing auto in domain iteration
  trace.beginBlock("Domain iterator with auto");
  for(auto it = domain.begin(), itend=domain.end(); it != itend; ++it)
    trace.info()<< *it << " ";
  trace.info()<<std::endl;
  trace.endBlock();
  
  //For loop on a range
  trace.beginBlock("range-based for on the domain");
  for(auto point : domain)
    trace.info() <<point << " ";
  trace.info() <<std::endl;
  trace.endBlock();
  
  //For loop on an image range
  trace.beginBlock("image (const) iterator on values");
  ImageContainerBySTLVector<Domain, int> image(domain);
  for(auto value: image.range())
    trace.info() <<value << " ";
  trace.info() <<std::endl;
  trace.endBlock();
  
  //For loop on an image domain range
  trace.beginBlock("(const) iterator on image domain");
  for(auto value: image.domain())
    trace.info() <<value << " ";
  trace.info() <<std::endl;
  trace.endBlock();
  
  //R-W for loop on an image range
  trace.beginBlock("image  iterator on values");
  int cpt=0;
  for(auto& value: image.range())
  {
    value = cpt;
    cpt++;
    trace.info() <<value << " ";
  }
  trace.info() <<std::endl;
  trace.endBlock();
  
  //Testing lambda expressions
  trace.beginBlock("Lambda exps");
  std::for_each(image.range().begin(), image.range().end(), [](int a){ trace.info() <<a<<" "; });
  trace.info()<<std::endl;
  std::transform(image.range().begin(), image.range().end(), image.range().begin(), [](int a){return 2*a+1;});
  std::for_each(image.range().begin(), image.range().end(), [](int a){ trace.info() <<a<<" "; });
  trace.info() <<std::endl;
  trace.endBlock();
  
  //Lambda expression based ultimate homotopic thining
  trace.beginBlock("STL+Lambda homotopic thinning");
  Domain domain2( Point(-32,-32), Point(32,32));
  DigitalSet set(domain2);
  //constructing a torus
  std::for_each(domain2.begin(), domain2.end(), [&set](Point p){ if ((p.norm() < 10 ) && p.norm() > 5) set.insertNew(p); });
  trace.info() << set << std::endl;
  Board2D board;
  board << set;
  board.saveEPS("original.eps");

  Object4_8 object(dt4_8 , set);
  std::vector<Point> Q;
  auto stable = false;
  auto step = 0;
  DigitalSet & S = object.pointSet();
  while(!stable)
  {
    trace.info() << "step = "<<step;
    stable = true;
    std::for_each(S.begin(), S.end(),
                  [&Q,&object](Point p){ if (object.isSimple(p)) Q.push_back(p); });
    std::for_each(Q.begin(), Q.end(),
                  [&object,&stable,&S](Point p){ if (object.isSimple(p))  {stable = false; S.erase(p);} });
    Q.clear();
    trace.info() << "|S| = "<< S.size() << std::endl;
    step++;
  }
  trace.endBlock();
  board << CustomStyle( object.pointSet().className(), new CustomColors(Color::Black, Color::Red))
        << object.pointSet();
  board.saveEPS("skeleton.eps");
  return 0;
}
Esempio n. 14
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());
      }
  
}
bool testCellDrawOnBoard()
{
  typedef typename KSpace::Integer Integer;
  typedef typename KSpace::Cell Cell;
  typedef typename KSpace::SCell SCell;
  typedef typename KSpace::Point Point;
  typedef typename KSpace::DirIterator DirIterator;
  typedef typename KSpace::Cells Cells;
  typedef typename KSpace::SCells SCells;
  typedef SpaceND<2, Integer> Z2;
  typedef HyperRectDomain<Z2> Domain;
  unsigned int nbok = 0;
  unsigned int nb = 0;
  trace.beginBlock ( "Testing cell draw on digital board ..." );
  KSpace K;
  int xlow[ 4 ] = { -3, -3 };
  int xhigh[ 4 ] = { 5, 3 };
  Point low( xlow );
  Point high( xhigh ); 
  bool space_ok = K.init( low, high, true );
  Domain domain( low, high );
  Board2D board;
  board.setUnit( LibBoard::Board::UCentimeter );
  board << SetMode( domain.className(), "Paving" )
  << domain;
  int spel[ 2 ] = { 1, 1 }; // pixel 0,0
  Point kp( spel );
  Cell uspel = K.uCell( kp );
  board << uspel 
  << low << high
  << K.uIncident( uspel, 0, false )
  << K.uIncident( uspel, 1, false );
  int spel2[ 2 ] = { 5, 1 }; // pixel 2,0
  Point kp2( spel2 );
  SCell sspel2 = K.sCell( kp2, K.POS );
  board << CustomStyle( sspel2.className(), 
      new CustomPen( Color( 200, 0, 0 ), 
               Color( 255, 100, 100 ),
               2.0, 
               Board2D::Shape::SolidStyle ) )
  << sspel2 
      << K.sIncident( sspel2, 0, K.sDirect( sspel2, 0 ) )
  << K.sIncident( sspel2, 1, K.sDirect( sspel2, 0 ) );
  board.saveEPS( "cells-1.eps" );
  board.saveSVG( "cells-1.svg" );
  trace.endBlock();
  board.clear();
  board << domain;
  SCell slinel0 = K.sIncident( sspel2, 0, K.sDirect( sspel2, 0 ) );
  SCell spointel01 = K.sIncident( slinel0, 1, K.sDirect( slinel0, 1 ) );
  board << CustomStyle( sspel2.className(), 
      new CustomColors( Color( 200, 0, 0 ), 
            Color( 255, 100, 100 ) ) )
  << sspel2
  << CustomStyle( slinel0.className(), 
      new CustomColors( Color( 0, 200, 0 ), 
            Color( 100, 255, 100 ) ) )
  << slinel0
  << CustomStyle( spointel01.className(), 
      new CustomColors( Color( 0, 0, 200 ), 
            Color( 100, 100, 255 ) ) )
  << spointel01;
  board.saveEPS( "cells-3.eps" );
  board.saveSVG( "cells-3.svg" );
  
  return ((space_ok) && (nbok == nb));
}
Esempio n. 16
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. 17
0
int main( int argc, char** argv )
{
  using namespace DGtal;
  using namespace DGtal::Z2i;
  
  typedef ImageContainerBySTLVector<Domain,unsigned char> GrayLevelImage2D;
  typedef ImageContainerBySTLVector<Domain,double>         DoubleImage2D;
  typedef DistanceToMeasure<DoubleImage2D>                 Distance;
  if ( argc <= 3 ) return 1;
  GrayLevelImage2D img  = GenericReader<GrayLevelImage2D>::import( argv[ 1 ] );
  double           mass = atof( argv[ 2 ] );
  double           rmax = atof( argv[ 3 ] );
  double           R    = atof( argv[ 4 ] );
  double           r    = atof( argv[ 5 ] );
  double           T1    = atof( argv[ 6 ] );
  double           T2    = atof( argv[ 7 ] );
  DoubleImage2D     fimg( img.domain() );
  DoubleImage2D::Iterator outIt = fimg.begin();
  for ( GrayLevelImage2D::ConstIterator it = img.begin(), itE = img.end();
        it != itE; ++it )
    {
      double v = ((double)*it) / 255.0;
      *outIt++ = v;
    }
  trace.beginBlock( "Computing delta-distance." );
  Distance     delta( mass, fimg, rmax );
  const DoubleImage2D& d2 = delta.myDistance2;
  trace.endBlock();

  double m = 0.0f;
  for ( typename Domain::ConstIterator it = d2.domain().begin(),
          itE = d2.domain().end(); it != itE; ++it )
    {
      Point p = *it;
      double v = sqrt( d2( p ) );
      m = std::max( v, m );
    }

  GradientColorMap<double> cmap_grad( 0, m );
  cmap_grad.addColor( Color( 255, 255, 255 ) );
  cmap_grad.addColor( Color( 255, 255, 0 ) );
  cmap_grad.addColor( Color( 255, 0, 0 ) );
  cmap_grad.addColor( Color( 0, 255, 0 ) );
  cmap_grad.addColor( Color( 0,   0, 255 ) );
  cmap_grad.addColor( Color( 0,   0, 0 ) );
  Board2D board;
  board << SetMode( d2.domain().className(), "Paving" );
  
  for ( typename Domain::ConstIterator it = d2.domain().begin(),
          itE = d2.domain().end(); it != itE; ++it )
    {
      Point p = *it;
      double v = sqrt( d2( p ) );
      v = std::min( (double) m, std::max( v, 0.0 ) ); 
      board << CustomStyle( p.className(),
                            new CustomColors( Color::Black, cmap_grad( v ) ) )
            << p;
      RealVector grad = delta.projection( p );
      board.drawLine( p[ 0 ], p[ 1 ], p[ 0 ] + grad[ 0 ], p[ 1 ] + grad[ 1 ], 0 );
    }
  std::cout << endl;
  board.saveEPS("dvcm-delta2.eps");
  board.clear();
  
  trace.beginBlock( "Computing delta-VCM." );
  typedef DeltaVCM< Distance > DVCM;
  typedef DVCM::Matrix                     Matrix;
  DVCM dvcm( delta, R, r );
  trace.endBlock();

  {
    GrayLevelImage2D pm_img( dvcm.myProjectedMeasure.domain() );
    DoubleImage2D::ConstIterator it    = dvcm.myProjectedMeasure.begin();
    DoubleImage2D::ConstIterator itE   = dvcm.myProjectedMeasure.end();
    GrayLevelImage2D::Iterator  outIt = pm_img.begin();
    for ( ; it != itE; ++it )
      {
        double v = std::max( 0.0, std::min( (*it) * 255.0, 255.0 ) );
        *outIt++ = v;
      }
    
    GenericWriter< GrayLevelImage2D >::exportFile( "dvcm-projmeasure.pgm", pm_img );
  }

  typedef EigenDecomposition<2,double> LinearAlgebraTool;
  typedef functors::HatPointFunction<Point,double> KernelFunction;
  KernelFunction chi( 1.0, r );

  // Flat zones are metallic blue, slightly curved zones are white,
  // more curved zones are yellow till red.
  double size = 1.0;
  GradientColorMap<double> colormap( 0.0, T2 );
  colormap.addColor( Color( 128, 128, 255 ) );
  colormap.addColor( Color( 255, 255, 255 ) );
  colormap.addColor( Color( 255, 255, 0 ) );
  colormap.addColor( Color( 255, 0, 0 ) );
  Matrix vcm_r, evec, null;
  RealVector eval;
  for ( Domain::ConstIterator it = dvcm.domain().begin(), itE = dvcm.domain().end();
        it != itE; ++it )
    {
      // Compute VCM and diagonalize it.
      Point p = *it;
      vcm_r = dvcm.measure( chi, p );
      if ( vcm_r == null ) continue;
      LinearAlgebraTool::getEigenDecomposition( vcm_r, evec, eval );
      //double feature = eval[ 0 ] / ( eval[ 0 ] +  eval[ 1 ] );
      eval[ 0 ] = std::max( eval[ 0 ], 0.00001 );
      double tubular = ( eval[ 1 ] <= 0.00001 ) // (R*R/4.0) )
        ? 0
        : ( eval[ 1 ] / ( eval[ 0 ] + eval[ 1 ] ) );
      double bound = T1;
      double tubular2 = tubular * (eval[ 0 ] + eval[ 1 ]) / (R*R*r/12.0);
      double display = tubular2 <= bound ? 0.0 : ( tubular2 - bound ) / (1.0 - bound);
      //: eval[ 1 ] / ( 1.0 + eval[ 0 ] ) / ( 1.0 + delta( p )*delta( p ) );
      //: eval[ 1 ] * eval[ 1 ] / ( 1.0 + eval[ 0 ] ) / ( 1.0 + delta( p ) );
      trace.info() << "l0=" << eval[ 0 ] << " l1=" << eval[ 1 ]
                   << " tub=" << tubular
                   << " tub2=" << tubular2
                   << " disp=" << display << std::endl;
      board << CustomStyle( p.className(), 
                            new CustomColors( Color::Black,
                                              colormap( display > T2 ? T2 : display ) ) )
            << p;
      // Display normal
      RealVector normal = evec.column( 0 );
      RealPoint rp( p[ 0 ], p[ 1 ] ); 
      Display2DFactory::draw( board, size*normal, rp );
      Display2DFactory::draw( board, -size*normal, rp );
    }      
  board.saveEPS("dvcm-hat-r.eps");
  board.clear();
  
  return 0;
}
void testBreadthFirstPropagation()
{
  typedef Z2i::Point Point;
  typedef Z2i::Domain Domain;
  typedef Z2i::DigitalSet DigitalSet;
  typedef Z2i::Object4_8 Object;
  
  BOOST_CONCEPT_ASSERT(( CUndirectedSimpleGraph<Z2i::Object4_8> ));
  
  Point p1( -41, -36 );
  Point p2( 18, 18 );
  Domain domain( p1, p2 );
  Point c1( -2, -1 );
  Point c2( -14, 5 );
  Point c3( -30, -15 );
  Point c4( -10, -20 );
  Point c5( 12, -1 );
  DigitalSet shape_set( domain );
  
  Shapes<Domain>::addNorm2Ball( shape_set, c1, 9 );
  Shapes<Domain>::addNorm1Ball( shape_set, c2, 9 );
  Shapes<Domain>::addNorm1Ball( shape_set, c3, 10 );
  Shapes<Domain>::addNorm2Ball( shape_set, c4, 12 );
  Shapes<Domain>::addNorm1Ball( shape_set, c5, 4 );

  Object obj(Z2i::dt4_8, shape_set);
  
  
  GradientColorMap<int> cmap_grad( 0, 52);
  cmap_grad.addColor( Color( 0, 0, 255 ) );
  cmap_grad.addColor( Color( 0, 255, 0 ) );
  cmap_grad.addColor( Color( 255, 0, 0 ) );
  
  Board2D board;
  board << SetMode( domain.className(), "Paving" )
  << domain
  << SetMode( p1.className(), "Paving" );
  
  Image image = ImageFromSet<Image>::create(shape_set, 1);
  
  typedef BreadthFirstVisitor<Object, set<Point> > Visitor;
  BOOST_CONCEPT_ASSERT(( CGraphVisitor< Visitor > ));
  Visitor bfv (obj, c1);
  
  
  while( !bfv.finished() )
  {
    image.setValue(bfv.current().first, bfv.current().second);
    bfv.expand();
  }
  
  string specificStyle = p1.className() + "/Paving";
  
  for ( DigitalSet::ConstIterator it = shape_set.begin();
  it != shape_set.end();
  ++it )
  {
    if( image(*it) == 0)
    {
      board << CustomStyle( specificStyle,
        new CustomColors( Color::Black,
        Color::Red ) )
      << *it;
    }
    else
    {
      if( image(*it) > 0 )
      {
	board << CustomStyle( specificStyle,
	  new CustomColors( Color::Black,
	  cmap_grad( image(*it) ) ) )
	<< *it;
      }
      else
      {
	board << CustomStyle( specificStyle,
	  new CustomColors( Color::Black,
	  cmap_grad( 0 ) ) )
	<< *it;
      }
    }
  }
  
  board.saveEPS("testBreadthFirstPropagation.eps");
}
Esempio n. 19
0
bool testSegmentation(const TCurve& curve)
{

  typedef typename TCurve::IncidentPointsRange Range; //range
  Range r = curve.getIncidentPointsRange(); //range
  
  typedef typename Range::ConstIterator ConstIterator; //iterator
  typedef GeometricalDSS<ConstIterator> SegmentComputer; //segment computer
  
  unsigned int nbok = 0;
  unsigned int nb = 0;  

  
  trace.beginBlock ( "Greedy segmentation" );
  {
    typedef GreedySegmentation<SegmentComputer> Segmentation;
    Segmentation theSegmentation( r.begin(), r.end(), SegmentComputer() );
    
    Board2D board; 
    board << r; 
      
    typename Segmentation::SegmentComputerIterator it = theSegmentation.begin();
    typename Segmentation::SegmentComputerIterator itEnd = theSegmentation.end();
    unsigned int n = 0; 
    unsigned int suml = 0; 
    for ( ; it != itEnd; ++it, ++n) {
      board << (*it); 
      for (ConstIterator i = it->begin(); i != it->end(); ++i)
        suml += 1; 
    }
    
    board.saveEPS("GeometricalDSSGreedySegmentationTest.eps", Board2D::BoundingBox, 5000 ); 

    trace.info() << r.size() << ";" << n << ";" << suml << endl;
    //comparison with the results gave by another program
    nbok += ((r.size()==85)&&(n==10)&&(suml==94)) ? 1 : 0; 
    nb++;
  }
  trace.endBlock();

  trace.beginBlock ( "Saturated segmentation" );
  {
    typedef SaturatedSegmentation<SegmentComputer> Segmentation;
    Segmentation theSegmentation( r.begin(), r.end(), SegmentComputer() );
    
    Board2D board; 
    board << r; 
    
    typename Segmentation::SegmentComputerIterator it = theSegmentation.begin();
    typename Segmentation::SegmentComputerIterator itEnd = theSegmentation.end();
    unsigned int n = 0; 
    unsigned int suml = 0; 
    for ( ; it != itEnd; ++it, ++n) {
      board << (*it); 
      for (ConstIterator i = it->begin(); i != it->end(); ++i)
        suml += 1; 
    }
    
    board.saveEPS("GeometricalDSSSaturatedSegmentationTest.eps", Board2D::BoundingBox, 5000 ); 

    trace.info() << r.size() << ";" << n << ";" << suml << endl;
    //comparison with the results gave by another program
    nbok += ((r.size()==85)&&(n==25)&&(suml==255)) ? 1 : 0; 
    nb++;
  }
  trace.endBlock();
  
  
  trace.info() << "(" << nbok << "/" << nb << ") " << endl;
  return (nbok == nb);
}
int main(  )
{
  trace.beginBlock ( "Example exampleAlphaThickSegment" );


  typedef FreemanChain<Z2i::Space::Integer>::ConstIterator FCConstIterator;
  typedef  AlphaThickSegmentComputer< Z2i::Point, FCConstIterator > AlphaThickSegmentComputer2D;
  Board2D aBoard;

  // Reading input contour
  std::string freemanChainFilename = examplesPath + "samples/contourS.fc";
  fstream fst;
  fst.open (freemanChainFilename.c_str(), ios::in);
  FreemanChain<Z2i::Space::Integer> fc(fst);
  fst.close();
  aBoard << fc;

  //construction of an AlphaThickSegmentComputer2D from the freemanchain iterator
  AlphaThickSegmentComputer2D anAlphaSegment(15), anAlphaSegment2(5), anAlphaSegment3(2);
  anAlphaSegment.init(fc.begin());                           
  while (anAlphaSegment.end() != fc.end() && 
         anAlphaSegment.extendFront()) {
  }
  aBoard << anAlphaSegment;  
  
  anAlphaSegment2.init(fc.begin());
  while (anAlphaSegment2.end() != fc.end() && anAlphaSegment2.extendFront()) {
  }
  aBoard  << CustomStyle( anAlphaSegment2.className(), new CustomColors( DGtal::Color::Blue, DGtal::Color::None ) );  
  aBoard << anAlphaSegment2;
  
  // Example of thickness definition change: usin the euclidean thickness definition.
  //! [exampleAlphaThickSegmentEuclDef]
  AlphaThickSegmentComputer2D anAlphaSegment2Eucl(5, functions::Hull2D::EuclideanThickness);
  //! [exampleAlphaThickSegmentEuclDef]

  anAlphaSegment2Eucl.init(fc.begin());
  while (anAlphaSegment2Eucl.end() != fc.end() && 
         anAlphaSegment2Eucl.extendFront()) {
  }

  aBoard << CustomStyle( anAlphaSegment2Eucl.className(), 
                         new CustomColors( DGtal::Color(20, 250, 255), DGtal::Color::None ) ); 
  aBoard << anAlphaSegment2Eucl;

  
  FCConstIterator fcIt = fc.begin();
  while (anAlphaSegment3.extendFront(*fcIt)) {
    fcIt++;
  }


  aBoard  << CustomStyle( anAlphaSegment3.className(), new CustomColors( DGtal::Color::Green, DGtal::Color::None ) );  
  aBoard << anAlphaSegment3;
  
 

  aBoard.saveEPS("exampleAlphaThickSegment.eps");

  trace.endBlock();
  return 0;
}
Esempio n. 21
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);
    }

}
Esempio n. 22
0
int main( int argc, char** argv )
{
  trace.beginBlock ( "Example FrechetShortcut" );
  trace.info() << "Args:";
  for ( int i = 0; i < argc; ++i )
    trace.info() << " " << argv[ i ];
  trace.info() << endl;

  std::string filename;
  double error;
  
  if(argc == 1)
    {
      trace.info() << "Use default file and error value\n";
      filename = examplesPath + "samples/plant-frechet.dat";
      error = 3;
    }
  else
    if(argc != 3)
      {
	trace.info() << "Please enter a filename and error value.\n";
	return 0;
      }
    else
      {
	filename = argv[1];
	error = atof(argv[2]);
      }
  ifstream instream; // input stream
  instream.open (filename.c_str(), ifstream::in);
  

  
  Curve c; //grid curve
  c.initFromVectorStream(instream);
  
  Board2D board;
  
  // Display the pixels as arrows range to show the way the curve is scanned
  board << c.getArrowsRange();
  
  trace.beginBlock("Simple example");

  //! [FrechetShortcutUsage]
  Curve::PointsRange r = c.getPointsRange(); 
  
  typedef FrechetShortcut<Curve::PointsRange::ConstIterator,int> Shortcut;
  
  // Computation of one shortcut
  Shortcut s(error);
  
  s.init( r.begin() );
  while ( ( s.end() != r.end() )
  	  &&( s.extendFront() ) ) {}
  


  // Computation of a greedy segmentation
  
  typedef GreedySegmentation<Shortcut> Segmentation;
  
  Segmentation theSegmentation( r.begin(), r.end(), Shortcut(error) );
  
  // the segmentation is computed here
  Segmentation::SegmentComputerIterator it = theSegmentation.begin();
  Segmentation::SegmentComputerIterator itEnd = theSegmentation.end();

  for ( ; it != itEnd; ++it) {
    s=Shortcut(*it);
    trace.info() << s << std::endl;
    board << s; 
  }
  
  board.saveEPS("FrechetShortcutExample.eps", Board2D::BoundingBox, 5000 ); 

  //! [FrechetShortcutUsage]
  #ifdef WITH_CAIRO
    board.saveCairo("FrechetShortcutExample.png"); 
  #endif


  trace.endBlock();
  return 0;
}
Esempio n. 23
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;
}
Esempio n. 24
0
bool testSegmentation()
{
  unsigned int nbok = 0;
  unsigned int nb = 0;
  
  typedef PointVector<2,int> Point;
  //typedef std::vector<Point>::iterator Iterator;
  //typedef FrechetShortcut<Iterator,int> SegmentComputer;  

  std::vector<Point> contour;
  contour.push_back(Point(0,0));
  contour.push_back(Point(1,0));
  contour.push_back(Point(2,0));
  contour.push_back(Point(3,0));
  contour.push_back(Point(4,0));
  contour.push_back(Point(5,0));
  contour.push_back(Point(6,0));
  contour.push_back(Point(7,0));
  contour.push_back(Point(7,1));
  contour.push_back(Point(6,1));
  contour.push_back(Point(5,1));
  contour.push_back(Point(4,1));
  contour.push_back(Point(3,1));
  contour.push_back(Point(2,1));
  contour.push_back(Point(2,2));
  contour.push_back(Point(3,2));
  contour.push_back(Point(4,2));
  contour.push_back(Point(5,2));
  contour.push_back(Point(6,2));
  contour.push_back(Point(7,2));
  contour.push_back(Point(8,2));
  contour.push_back(Point(9,2));

  trace.beginBlock ( "Testing block ..." );
  
  typedef Curve::PointsRange::ConstIterator Iterator;
  typedef FrechetShortcut<Iterator,int> SegmentComputer;
  
  Curve aCurve; //grid curve
  aCurve.initFromVector(contour);
  
  typedef Curve::PointsRange Range; //range
  Range r = aCurve.getPointsRange(); //range
  
  Board2D board; 
  board << r;
  board << aCurve.getArrowsRange();
  

  double error = 3;
  nbok =3;
  
  trace.beginBlock ( "Greedy segmentation" );
  {
    typedef GreedySegmentation<SegmentComputer> Segmentation;
    Segmentation theSegmentation( r.begin(), r.end(), SegmentComputer(error) );
    
    Segmentation::SegmentComputerIterator it = theSegmentation.begin();
    Segmentation::SegmentComputerIterator itEnd = theSegmentation.end();
    
    for ( ; it != itEnd; ++it) {
      SegmentComputer s(*it);
      trace.info() << s << std::endl;
      board << (*it); 
      nb++;
    }

    //board << aCurve;
    trace.info() << theSegmentation << std::endl;
    board.saveEPS("FrechetShortcutGreedySegmentationTest.eps", Board2D::BoundingBox, 5000 ); 
  }
  
  /* Saturated segmentation does not work for FrechetShortcut
     computer. Indeed, given two maximal Frechet shortcuts s1(begin, end) et
     s2(begin, end),  we can have s1.begin < s2.begin < s2.end <
     s1.end. */ 
  

  trace.endBlock();
  
  return nbok == nb;
}
Esempio n. 25
0
bool
testDigitization( const Shape & aShape, double h,
      const string & fileName )
{
  typedef typename Space::Point Point;
  typedef typename Space::RealPoint RealPoint;
  typedef HyperRectDomain<Space> Domain;
  typedef typename DigitalSetSelector
    < Domain, BIG_DS + HIGH_ITER_DS + HIGH_BEL_DS >::Type MySet;

  // Creates a digitizer on the window (xLow, xUp).
  RealPoint xLow( -5.3, -4.3 );
  RealPoint xUp( 7.4, 4.7 );
  GaussDigitizer<Space,Shape> dig;  
  dig.attach( aShape ); // attaches the shape.
  dig.init( xLow, xUp, h ); 
  
  // The domain size is given by the digitizer according to the window
  // and the step.
  Domain domain = dig.getDomain(); // ( dig.getLowerBound(), dig.getUpperBound() );
  MySet aSet( domain );
  // Creates a set from the digitizer.
  Shapes<Domain>::shaper( aSet, dig );
  
  // Create cellular space
  typedef Z2i::KSpace KSpace;
  typedef Z2i::SCell SCell;
  KSpace K;
  bool ok = K.init( dig.getLowerBound(), dig.getUpperBound(), true );
 
  ASSERT( ok );

  SurfelAdjacency<KSpace::dimension> SAdj( true );

 

  // Extracts shape boundary
  SCell bel = Surfaces<KSpace>::findABel( K, dig, 10000 );
  // Getting the consecutive surfels of the 2D boundary
  std::vector<Point> points;
  Surfaces<KSpace>::track2DBoundaryPoints( points, K, SAdj, dig, bel );
  GridCurve<KSpace> gridcurve;
  gridcurve.initFromVector( points );

  // Display all
  Board2D board;
  board.setUnit( LibBoard::Board::UCentimeter );
  board << SetMode( domain.styleName(), "Paving" )
    << domain << aSet;

  board << SetMode( gridcurve.styleName(), "Edges" )
  << CustomStyle( bel.styleName(), 
      new CustomColors( DGtal::Color( 0, 0, 0 ),
            DGtal::Color( 0, 192, 0 ) ) )
  << gridcurve;
  board << SetMode( gridcurve.styleName(), "Points" )
  << CustomStyle( bel.styleName(), 
      new CustomColors( DGtal::Color( 255, 0, 0 ),
            DGtal::Color( 200, 0, 0 ) ) )
  << gridcurve;

  board.saveEPS( ( fileName + ".eps" ).c_str() );
  board.saveSVG( ( fileName + ".svg" ).c_str() );
  
  return true;
}