zoukankan      html  css  js  c++  java
  • Delaunay三角剖分

    转载:http://blog.csdn.net/raby_gyl/article/details/17409717


    相关文章:OpenCV三角剖分的遍历和纹理映射:http://blog.csdn.net/raby_gyl/article/details/19758167


    Delaunay三角剖分是1934年发明的将空间点连接为三角形,使得所有三角形中最小角最大的一个技术。


    如果你熟悉计算机图形学,你便会知道Delaunay三角剖分是变现三维形状的基础。如果我们在三维空间渲染一个,我们可以通过这个物体的投影来建立二维视觉图,并用二维Delaunay三角剖分来分析识别该物体,或者将它与实物相比较。Delaunay剖分是连接计算机视觉与计算机图形学的桥梁。然而使用OpenCV实现三角剖分的不足之处就是OpenCV只实现了二维的Delaunay剖分。如果我们能够对三维点进行三角剖分,也就是说构成立体视觉,那么我们可以在三维的计算机图形和计算机视觉进行无缝的转换。然而二维三角剖分通常用于计算机视觉中标记空间目标的特征或运动场景跟踪,目标识别,或两个不同的摄像机的场景匹配(如图从立体图像中获得深度信息)。


    下面内容摘自:http://www.cnblogs.com/RenLiQQ/archive/2008/02/06/1065399.html


    1、三角剖分与Delaunay剖分的定义


    如何把一个离散几何剖分成不均匀的三角形网格,这就是离散点的三角剖分问题,散点集的三角剖分,对数值分析以及图形学来说,都是极为重要的一项处理技术。该问题图示如下:


    1.1 三角剖分定义


    【定义】三角剖分:假设V是二维实数域上的有限点集,边e是由点集中的点作为端点构成的封闭线段,E为e的集合。那么该点集V的一个三角剖分T=(V,E)是一个平面图G,该平面图满足条件:

    1、除了端点,平面图中的边不包含点集中的任何点。

    2、没有相交边。(边和边没有交叉点)

    3、平面图中所有的面都是三角面,且所有三角面的合集是散点集V的凸包。


    1.2 Delaunay三角剖分的定义


    在实际中运用的最多的三角剖分是Delaunay三角剖分,它是一种特殊的三角剖分。先从Delaunay边说起:

    【定义】Delaunay边:假设E中的一条边e(两个端点为a,b),e若满足下列条件,则称之为Delaunay边:存在一个圆经过a,b亮点,圆内(注意是园内,圆上最多三点共圆)不含点集V中任何其他的点,这一特性又称空圆特性。

    【定义】Delaunay三角剖分:如果点集V的一个三角剖分T只包含Delaunay边,那么该三角剖分称为Delaunay三角剖分。


    1.3 Delaunay三角剖分的准则


    要满足Delaunay三角剖分的定义,必须符合两个重要的准则:

    1、空圆特性:Delaunay三角网是唯一的(任意四点不能共圆),在Delaunay三角形网中任一三角形的外接圆范围内不会有其它点存在。如下图所示:


    2、最大化最小角特性:在散点集可能形成的三角剖分中,Delaunay三角剖分所形成的三角形的最小角最大。从这个意义上讲,Delaunay三角网是“最接近于规则化的”三角网。具体的说是在两个相邻的三角形构成凸四边形的对角线,在相互交换后,两个内角的最小角不再增大。如下图所示:



    1.4 Delaunay三角剖分的特性


    以下是Delaunay剖分所具备的优异特性:

    1、最接近:以最接近的 三点形成三角形,且各线段(三角行的边)皆不相交。

    2、唯一性:不论从区域何处开始构建,最终都将得到一致的结果。

    3、最优性:任意两个相邻三角形构成的凸四边形的对角线如何可以互换的话,那么两个三角形六个内角中最小角度不会变化。

    4、最规则:如果将三角网中的每个三角形的最小角进行升序排列,则Delaunay三角网的排列得到的数值最大。

    5、区域性:新增、删除、移动某一个顶点只会影响邻近的三角形。

    6、具有凸边形的外壳:三角网最外层的边界形成一个凸多边形的外壳。


    1.5局部最优化处理


    理论上为了构造Delaunay三角网,Lawson提出的局部优化过程LOP(Local Optimization Procedure),一般三角网经过LOP处理,即可确保为Delaunay三角网,其基本做法如下所示:

    1、将两个具有共同边的三角形合成一个多边形。

    2、以最大空圆准则作检查,看其第四个顶点是否在三角形的外接圆内。

    3、如果在,修正对角线即将对角线对调,即完成局部优化过程的处理。

    LOP处理过程如下图所示:



    2、Delaunay剖分的算法


    Delaunay剖分是一种三角剖分的标准,实现它有多种算法。


    由表可以看出,三角网生成法的时间效率最低,分治算法的时间效率最高,逐点插入法效率居中。由于区域生长法本质的缺陷,导致其效率受限,这种方法在80年代中期以后已经很少使用。分治算法时间效率相对较高,但是由于其递归执行,所以需要较大的内存空间,导致其空间效率较低。此外,分治法的数据处理及结果的优化需要的工作量也比较大。逐点插入算法实现简单,时间效率比较高,而运行占用的空间也较小,从时间效率和空间效率综合考虑,性价比最高,因而应用广泛。

    1977年,Lawson提出了逐点插入法建立Delaunay三角网的算法思想。之后Lee和Schachlter,Bowyer,Watson,Sloan,先后进行了发展和完善。他们的算法在初始化三角网的建立方法、定位点所在三角形的过程、以及插入的过程方面各具特点。


    2.1 Lawson算法


    逐点插入的Lawson算法是Lawson在1977提出的,该算法思路简单,易于编程实现。基本原理为:首先建立一个大的三角形或多边形,把所有数据点包围起来,向其中插入一点,该点与包含它的三角形三个顶点相连,形成三个新的三角形,然后逐个对它们进行空外接圆检测,同时用Lawson设计的局部最优化过程LOP进行优化,集通过交换对角线的方法来保证所形成的三角网为Delaunay三角网。

    上述基于散点的构网算法理论严密、唯一性好,网格满足空圆特性,较为理想。由其逐点插入的构网过程可知,遇到非Delaunay边时,通过删除调整,可以构造形成新的Delaunay边。在完成构网后,增加新点时,无需对所有点进行重新构网,只需要对新点的影响三角形范围进行局部联网,且局部联网的方法简单易行。同样,点的删除、移动也可快速动态地进行。但在实际应用当中,这种构网算法当点集较大时网速度也较慢,如果点集范围是非凸区域或者存在内环,则会产生非法三角形。


    2.2 Bowyer-Watson算法


    目前采用逐点插入方式生成的Delaunay三角网的算法主要基于Bowyer-Watson算法,Bowyer-Watson算法的主要步骤如下:

    1)建立初始三角网格:针对给定的点集V,找到一个包含该点集的矩形R,我们称R为辅助窗口。连接R的任意一条对角线,形成两个三角形,作为初始Delaunay三角网格。

    2)逐点插入:假设目前已经有一个Delaunay三角网格T,现在在它里面再插入一个点P,需要找到该点P所在的三角形。从P所在的三角形开始,搜索该三角形的邻近三角形,并进行空外接圆检测。找到外接圆包含点P的所有的三角形并删除这些三角形,形成一个包含P的多边形空腔,我们称之为Delaunay空腔。然后连接P与Delaunay腔的每一个顶点,形成新的Delaunay三角网格。

    3)删除辅助窗口R:重复步骤2),当点集V中所有点都已经插入到三角形网格中后,将顶点包含辅助窗口R的三角形全部删除。

    在这些步骤中,快速定位点所在的三角形、确定点的影响并构建Delaunay腔的过程是每插入一个点都会进行的。随着点数的增加,三角形数目增加很快,因此缩短这两个过程的计算时间,是提高算法效率的关键。

    算法执行图示如下:



    3、OpenCV中的Delaunay和Voronoi细分

    学习这部分,也是一个头疼的问题,要理解需要较好的数据结构作为基础。由于自己对数据结构也是敬畏三分,所以下面理解不免有误。

    OpenCV中现实的Delaunay三角剖分应该是Bowyer-Watson算法。


    3.1创建一个Delaunay或Voronoi细分。

    我们需要存储Delaunay的内存空间和一个外接矩形(该矩形盒子用来确定虚拟三角形)

    1. // STORAGE AND STRUCTURE FOR DELAUNAY SUBDIVISION //存储和结构 for三角剖分  
    2. //  
    3. CvRect rect = { 0, 0, 600, 600 };  //Our outer bounding box //我们的外接边界盒子  
    4. CvMemStorage* storage;    //Storage for the Delaunay subdivsion //用来存储三角剖分  
    5. storage = cvCreateMemStorage(0);    //Initialize the storage //初始化存储器  
    6. CvSubdiv2D* subdiv; //The subdivision itself // 细分  
    7. subdiv = init_delaunay( storage, rect);   //See this function below //函数返回CvSubdiv类型指针  

    init_delaunay函数如下,它是一个OpenCV函数,是一个包含一些OpenCV函数的函数包。

    1. //INITIALIZATION CONVENIENCE FUNCTION FOR DELAUNAY SUBDIVISION //为三角剖分初始化便利函数  
    2. //  
    3. CvSubdiv2D* init_delaunay(CvMemStorage* storage,CvRect rect) {  
    4. CvSubdiv2D* subdiv;  
    5. subdiv = cvCreateSubdiv2D(CV_SEQ_KIND_SUBDIV2D,sizeof(*subdiv),sizeof(CvSubdiv2DPoint),sizeof(CvQuadEdge2D),storage);//为数据申请空间  
    6. cvInitSubdivDelaunay2D( subdiv, rect ); //rect sets the bounds  
    7. return subdiv;//返回申请空间的指针  
    8. }  
    我们知道三角剖分是对散点集进行处理的,我们知道了散点集就可以获得点集的三角剖分。如何传入(插入)散点集呢?

    这些点必须是32位浮点型,并通过下面的方式插入点:

    1. CvPoint2D32f fp; //This is our point holder//这是我们点的持有者(容器)  
    2. for( i = 0; i < as_many_points_as_you_want; i++ ) {  
    3. // However you want to set points //如果我们的点集不是32位的,在这里我们将其转为CvPoint2D32f,如下两种方法。  
    4. //  
    5. fp = your_32f_point_list[i];  
    6. cvSubdivDelaunay2DInsert( subdiv, fp );  
    7. }  
    转换为CvPoint2D32f的两种方法:

    1)通过宏cvPoint2D32f(double x,double y)

    2)通过cxtype.h下的cvPointTo32f(CvPoint point)函数将整形点方便的转换为32位浮点型。

    当可以通过输入点(散点集)得到Delaunay三角剖分后,接下来,我们用一下两个函数设置和清除相关的Voronoi划分:

    1. cvCalcSubdivVoronoi2D( subdiv ); // Fill out Voronoi data in subdiv //在subdiv中填充Vornoi的数据  
    2. cvClearSubdivVoronoi2D( subdiv ); // Clear the Voronoi from subdiv//从subdiv中清除Voronoi的数据  


    CvSubdiv2D结构如下:

    1. #define CV_SUBDIV2D_FIELDS()   
    2. CV_GRAPH_FIELDS()   
    3. int quad_edges;   
    4. int is_geometry_valid;   
    5. CvSubdiv2DEdge recent_edge;   
    6. CvPoint2D32f topleft;   
    7. CvPoint2D32f bottomright;  
    8. typedef struct CvSubdiv2D  
    9. {  
    10. CV_SUBDIV2D_FIELDS()  
    11. }  
    12. CvSubdiv2D;  
    1. #define CV_GRAPH_FIELDS()                 
    2. CV_SET_FIELDS() /* set of vertices */     
    3. CvSet *edges;  /* set of edges    */  
    1. #define CV_SET_FIELDS()                                              
    2. CV_SEQUENCE_FIELDS()             /*inherits from [#CvSeq CvSeq] */   
    3. struct CvSetElem* free_elems;   /*list of free nodes           */  

    平面划分是将一个平面分割为一组不重叠的、能够覆盖整个平面的区域。结构CvSubdiv2D描述了建立在二维点集上的划分结构,其中点集互相连接且构成平面图形,该图形通过结合一些无线连接外部划分点(称为凸形点)的边缘,将一个平面用按照其边缘划分成很多小区域。

    对于每一个划分操作,都有一个对偶划分与之对应。对偶的意思是小区域与点(划分的顶点)变换角色,即在对偶划分中,小区域被当做一个顶点(以下称为虚拟点)而原始的划分顶点被当做小区域。如下图所示,原始的划分用实线表示,而对偶划分用虚线表示。

    OpenCV使用Delaunay算法将平面分割成小的三角形区域(该三角形确保包括所有的分割点)开始不断迭代完成。在这种情况下,对偶划分就是输入的二维点集的Voronoi图表。这种划分可以用于对一个平面进行三维分段变换、形态变换、平面点的快速 定位以及建立特定的图结构(如NNG,RNG)。


    CvQuadEdge2D

    CvQuadEdge2D结构包含了两个Delaunay点和两个Vorionoi点以及连接它们的边缘(假设Voronoi点和边缘已经由函数计算出来,通过上面的函数:cvCalSubdivVoronoi2D(subdiv))。

    CvQuadEdge2D定义平面划分中的Quad-edge(四方边缘结构),其结构如下:


    1. /  
    2. *  
    3. one of edges within quad-edge, lower 2 bits is index (0..3)  
    4. and upper bits are quad-edge pointer  
    5. *  
    6. /  
    7. typedef long CvSubdiv2DEdge;  //四方边缘结构中的一条边缘,低两位表示该边缘的索引号,其他高位表示边缘指针。  
    8.   
    9.  /*quad-edge structure fields*/四方边缘的结构场  
    10. #define CV_QUADEDGE2D_FIELDS()   
    11. int flags;   
    12. struct CvSubdiv2DPoint*pt[4];   
    13. CvSubdiv2DEdge next[4];  
    14. typedef struct CvQuadEdge2D  
    15. {  
    16. CV_QUADEDGE2D_FIELDS()  
    17. }  
    18. CvQuadEdge2D;  
    四方边缘结构是平面划分的基元,其中包括四条边缘(e,eRot,以及他们的反方向),如下图所示:

    CvSubdiv2DPoint

    CvSubdiv2DPoint结构包含Delaunay边缘及其相连的顶点。

    其结构定义如下:

    1. #define CV_SUBDIV2D_POINT_FIELDS()  
    2. int flags;   
    3. CvSubdiv2DEdge first;   
    4. CvPoint2D32f pt;   
    5. int id; //This integer can be used to index auxillary data asscoiated with each vertex of the planar subdivison.  
    6. #define CV_SUBDIV2D_VIRTUAL_POINT_FLAG (1 << 30)  
    7. typedef struct CvSubdiv2DPoint  
    8. {  
    9. CV_SUBDIV2D_POINT_FIELDS()  
    10. }  
    11. CvSubdiv2DPoint;  

    边缘的遍历

    Subdiv2DRotateEdge函数

    功能:函数Subdiv2DRotateEdge根据输入的边缘返回四方边缘结构中的一条边缘。

    格式:

    1. CvSubdiv2DEdge cvSubdiv2DRotateEdge(CvSubdiv2DEdge edge,int rotate );  
    参数:

    edge划分的边缘(不是四方边缘结构,即不是CvQuadEdge2D)

    rotate 确定函数根据输入的边缘返回同一四方边缘结构中的哪条边缘,为下列值之一:

    1)0 输入边缘(如果e是输入边缘,则为e)。

    2)1 旋转比那样(eRot)

    3)2 逆边缘(e的反向边缘)。

    4)3旋转比那样的反向边缘(eRot的反向边缘)。

    cvSubdiv2DGetEdge函数

    使用该函数我们可以遍历Delaunay图。该函数返回与输入边缘相关的边缘。

    格式:

    1. CvSubdiv2DEdge cvSubdiv2DGetEdge( CvSubdiv2DEdge edge, CvNextEdgeType type );  

    参数:

    edge 划分的边缘(不是四方边缘结构)

    type 确定函数返回哪条相关边缘,为下列值之一:

    CV_NEXT_AROUND_ORG  边缘原点的下一条(eOnext,如果e是输入边)。

    CV_NEXT_AROUND_DST 边缘顶点的下一条(eDnext)

    CV_PREV_AROUND_ORG 边缘原点的前一条(eRnext的反向)

    CV_PREV_AROUND_DST边缘终点的前一条(eLnext的反向)

    CV_NEXT_AROUND_LEFT 左区域的下一条(eLnext)  或下一个左平面

    CV_NEXT_AROUND_RIGHT 右区域的下一条(eRnext) 或下一个右平面

    CV_PREV_AROUND_LEFT 左区域的前一条(eOnext的反向)或前一个左平面

    CV_PREV_AROUND_RIGHT 右区域的前一条(eDnext的反向)或前一个右平面



    来至边缘的点

    我们可以通过下面的两个函数获得Delaunay或者Voronoi边缘的两个实际点:

    1. CvSubdiv2DPoint* cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge );  
    2. CvSubdiv2DPoint* cvSubdiv2DEdgeDst( CvSubdiv2DEdge edge );  

    下面是将CvSubdiv2DPoint点转换为更熟悉的点CvPoint2D32f 或者CvPoint:

    1. CvSubdiv2DPoint ptSub;   //Subdivision vertex point  
    2. CvPoint2D32f pt32f = ptSub->pt;    // to 32f point  
    3. CvPoint pt = cvPointFrom32f(pt32f);  // to an integer point  

    如何从Delaunay/Voronoi细分得到第一条边或点?

    有两种方法:1)使用一个外部点定位边缘或顶点 2)遍历一系列点或边缘

    方法一:使用外部点定位边缘或顶点

    第一种方法是任取一点,然后在细分中定位该点。该点不一定是三角剖分中点,而可以为任意点。

    cvSubdiv2DLocate()函数填充三角形的边缘和顶点(如果必要)或者填充该点所在的Voronoi面,函数的声明如下:

    1. CvSubdiv2DPointLocation cvSubdiv2DLocate(  
    2. CvSubdiv2D*   subdiv,  
    3. CvPoint2D32f    pt,  
    4. CvSubdiv2DEdge* edge,//要填充的边缘  
    5. CvSubdiv2DPoint** vertex = NULL//如果需要,则填充顶点  
    6. );  

    请注意,这些不必是最接近的边缘或顶点,它们只需要在三角形上。此函数的返回值按下列的方式说明点的位置:

    1)CV_PTLOC_INSIDE 点落入某些面;*edge将包含该面的一个边缘。

    2)CV_PTLOC_ON_ENCODE 点落于边缘;*edge含有这个边缘。

    3)CV_PTLOC_VERTEX 该点与一个细分顶点重合;*vertex将包含该顶点的指针。

    4)CV_PTLOC_OUTSIDE_RECT 该点处于细分参考矩形之外;该函数返回后不填充指针。

    5)CV_PTLOC_ERROR 输入变量无效。


    方法二:遍历一系列点或边缘

    外接三角形(虚拟)的三个顶点和三个边的获取:

    1)首先我们要有一个建立的Delaunay细分。

    2)我们还需要调用cvCalcSubdivVoronoi2D(subdiv)函数计算相关的Voronoi划分。

    3)然后我们就能用CvSubdiv2DPoint *outer_vtx[3]和CvQuadEdge2D*outer_gedges[3]来存储三个顶点和三条边。

    如下:

    1. CvSubdiv2DPoint* outer_vtx[3];  
    2. for( i = 0; i < 3; i++ ) {  
    3. outer_vtx[i] =  
    4. (CvSubdiv2DPoint*)cvGetSeqElem( (CvSeq*)subdiv, I );  
    5. }  

    1. CvQuadEdge2D* outer_ qedges[3];  
    2. for( i = 0; i < 3; i++ ) {  
    3. outer_qedges[i] =  
    4. (CvQuadEdge2D*)cvGetSeqElem( (CvSeq*)(my_subdiv->edges), I );  
    5. }  

    确定凸包的外接三角形(Bounding triangle)或边缘并遍历凸包

    我们回想一下,我们通过调用cvInitSubdivDelaunay2D(subdiv,rect)来初始化Delaunay三角剖分。在这种情况下,下面的论述成立:

    1、如果边缘的起点和终点都在矩形之外,那么此边缘也在细分的外接三角形上。(即如果一个边缘的两个点出了矩形边界,那么该边缘为虚拟三角形的边缘)

    2、如果边缘的一端在矩形内,一段在矩形外,那么矩形边界内的点落在凸集上,凸集上的每个点与虚拟外接三角形的两顶点相连,这两边相继出现。

    (英语原文:If you are on an edge with one point inside and one point outside the rect bounds,then the point in bounds is on the convex hull of the set。。。)

    (注释:Learning OpenCV中第343页,将In bounds翻译为在边界上,这里个人感觉应该是在翻译为在边界内,为了方便理解,个人猜测如下图,可能不对:)

    从上述第二个条件可知,我们可以使用cvSubdiv2DNextEdge(),移动到第一条边上,这条边的dst端点在边界内。

    两个端点都在边界内的这条边在点集的凸包上,因此记下那个点和边。一旦它在凸包上,那么你可以如下遍历所有顶点。(切记参考英文原版,我感觉下面的步骤应该参考具体操作理解。)
    1·、将凸包遍历一周后,通过cvSubdiv2DRotateEdge(CvSubdiv2DEdge edge,0)函数移动到凸包的下一条边。

    2、接着,两次调用宏cvSubdiv2DNextEdge()就到了凸包的下一条边。跳转到第一步。

    使用实例:

    1、使用函数cvSubdiv2DLoacate()遍历Delaunay三角剖分的边。

    2、使用函数cvFindNearestPoint2D()函数找到距离输入最近的点。

    3、使用函数draw_subdiv_facet()函数逐步遍历Voronoi面,这个函数是组合函数,实现参考OpenCV的344页。

    4、使用CvSeqReader逐步遍历Delaunay或者Voronoi边。

    5、找到了三角剖分的所有顶点,我们就可以利用内敛宏cvTriangleArea()函数来计算剖分的面积。


    三角剖分例程序:

    在OpenCV的sample的c目录下:delaunay.c文件

    代码理解参考图:


    程序一:

    1. #include <opencv2/imgproc/imgproc_c.h>  
    2. #include <opencv2/legacy/legacy.hpp>  
    3. #include "opencv2/highgui/highgui.hpp"  
    4. #include<opencv2opencv.hpp>  
    5. #include<iostream>  
    6. #include <stdio.h>  
    7. using namespace std;  
    8. using namespace cv;  
    9. static void help( void )  
    10. {  
    11.     printf(" This program demostrates iterative construction of "//这个程序阐述了delaunay剖分和voronoi细分的迭代构造  
    12.         "delaunay triangulation and voronoi tesselation. "  
    13.         "It draws a random set of points in an image and then delaunay triangulates them. "//在图像上画出一些随机点,然后进行delaunay三角剖分  
    14.         "Usage:  "  
    15.         "./delaunay  "  
    16.         " This program builds the traingulation interactively, you may stop this process by "  
    17.         "hitting any key. ");//迭代构造三角剖分,如果像停止,则按任意键  
    18. }  
    19.   
    20. static CvSubdiv2D* init_delaunay( CvMemStorage* storage,//初始化三角剖分结构,为其分配单元  
    21.     CvRect rect )  
    22. {  
    23.     CvSubdiv2D* subdiv;//三角剖分的数据单元  
    24.   
    25.     subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv),  
    26.         sizeof(CvSubdiv2DPoint),  
    27.         sizeof(CvQuadEdge2D),  
    28.         storage );  
    29.     cvInitSubdivDelaunay2D( subdiv, rect );  
    30.   
    31.     return subdiv;  
    32. }  
    33.   
    34.   
    35. static void draw_subdiv_point( IplImage* img, CvPoint2D32f fp, CvScalar color )//画出三角剖分的顶点  
    36. {  
    37.     cvCircle( img, cvPoint(cvRound(fp.x), cvRound(fp.y)),5, color, CV_FILLED, 8, 0 );  
    38. }  
    39.   
    40.   
    41. static void draw_subdiv_edge( IplImage* img, CvSubdiv2DEdge edge, CvScalar color )//画出三角剖分的边  
    42. {  
    43.     CvSubdiv2DPoint* org_pt;//源顶点  
    44.     CvSubdiv2DPoint* dst_pt;//目地顶点  
    45.     CvPoint2D32f org;  
    46.     CvPoint2D32f dst;  
    47.     CvPoint iorg, idst;  
    48.   
    49.     org_pt = cvSubdiv2DEdgeOrg(edge);//通过边获取顶点  
    50.     dst_pt = cvSubdiv2DEdgeDst(edge);  
    51.   
    52.     if( org_pt && dst_pt )//如果两个端点不为空  
    53.     {  
    54.         org = org_pt->pt;  
    55.         dst = dst_pt->pt;  
    56.   
    57.         iorg = cvPoint( cvRound( org.x ), cvRound( org.y ));  
    58.         idst = cvPoint( cvRound( dst.x ), cvRound( dst.y ));  
    59.   
    60.         cvLine( img, iorg, idst, color, 1, CV_AA, 0 );  
    61.     }  
    62. }  
    63.   
    64.   
    65. static void draw_subdiv( IplImage* img, CvSubdiv2D* subdiv,  
    66.     CvScalar delaunay_color, CvScalar voronoi_color  )//画出剖分和细分  
    67. {  
    68.     CvSeqReader  reader;  
    69.     int i, total = subdiv->edges->total;//边的数量  
    70.     int elem_size = subdiv->edges->elem_size;//边的大小  
    71.     cout<<typeid(subdiv->edges).name()<<endl;  
    72.   
    73.     cvStartReadSeq( (CvSeq*)(subdiv->edges), &reader, 0 );//使用CvSeqReader遍历Delaunay或者Voronoi边  
    74.   
    75.     for( i = 0; i < total; i++ )  
    76.     {  
    77.         CvQuadEdge2D* edge = (CvQuadEdge2D*)(reader.ptr);  
    78.   
    79.         if( CV_IS_SET_ELEM( edge ))  
    80.         {  
    81.             // draw_subdiv_edge( img, (CvSubdiv2DEdge)edge + 1, voronoi_color );  
    82.             draw_subdiv_edge( img, (CvSubdiv2DEdge)edge, delaunay_color );  
    83.         }  
    84.   
    85.         CV_NEXT_SEQ_ELEM( elem_size, reader );  
    86.     }  
    87.   
    88. }  
    89.   
    90.   
    91. static void locate_point( CvSubdiv2D* subdiv, CvPoint2D32f fp, IplImage* img,//遍历三角剖分的边  
    92.     CvScalar active_color )  
    93. {  
    94.     CvSubdiv2DEdge e;  
    95.     CvSubdiv2DEdge e0 = 0;  
    96.     CvSubdiv2DPoint* p = 0;  
    97.   
    98.     cvSubdiv2DLocate( subdiv, fp, &e0, &p );  
    99.   
    100.     if( e0 )  
    101.     {  
    102.         e = e0;  
    103.         do  
    104.         {  
    105.             draw_subdiv_edge( img, e, active_color );  
    106.             e = cvSubdiv2DGetEdge(e,CV_NEXT_AROUND_LEFT);  
    107.         }  
    108.         while( e != e0 );  
    109.     }  
    110.   
    111.     draw_subdiv_point( img, fp, active_color );  
    112. }  
    113.   
    114. //@author andme-单目视觉  
    115. void dashLine(Mat &img, Point2d& pt1, Point2d& pt2, int n)//n为虚线段数  
    116. {  
    117.     Point sub = pt2 - pt1;  
    118.     for (int i = 0; i < 2*n; i += 2)  
    119.     {  
    120.         line(img, Point(pt1.x + sub.x * i / (2 * n - 1), pt1.y + sub.y * i / (2 * n - 1)), Point(pt1.x + sub.x * (i+1) / (2 * n - 1), pt1.y + sub.y * (i+1) / (2 * n - 1)), Scalar(0,255,0), 2);  
    121.     }  
    122. }  
    123.   
    124.   
    125.   
    126. //调用形式draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 1 ));  
    127. static void draw_subdiv_facet( IplImage* img, CvSubdiv2DEdge edge )//画出voronoi面   
    128. {  
    129.     //cout<<edge<<endl;//edge低两位表示表示索引,高位表示四方边缘指针。  
    130.     //cout<<(edge&3)<<endl;  
    131.     CvSubdiv2DEdge t = edge;//当我们按上面的调用形式时,edge为eRot。  
    132.     int i, count = 0;  
    133.     CvPoint* buf = 0;  
    134.     Point2d *buf1=0;  
    135.   
    136.     // count number of edges in facet //面内边的计数  
    137.     do  
    138.     {  
    139.         count++;  
    140.         t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );  
    141.     } while (t != edge );//我们绕着一个voronoi单元一周,遍历该vornonoi边缘所拥有的边缘数。  
    142.   
    143.     buf = (CvPoint*)malloc( count * sizeof(buf[0]));  
    144.     buf1=(Point2d*)malloc(count*sizeof(buf1[0]));  
    145.   
    146.     // gather points  
    147.     t = edge;  
    148.     for( i = 0; i < count; i++ )  
    149.     {  
    150.         CvSubdiv2DPoint* pt = cvSubdiv2DEdgeOrg( t );//第一次获取eRot边缘的起始点  
    151.         if( !pt ) break;//如果得不到该源点,则退出循环  
    152.         buf[i] = cvPoint( cvRound(pt->pt.x), cvRound(pt->pt.y));//将该点转换为cvPoint类型点,存储在buf中  
    153.         t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );//然后绕着vornonoi单元,左旋转。  
    154.     }  
    155.   
    156.     if( i == count )//如果所有的点都存储起来了。  
    157.     {  
    158.         CvSubdiv2DPoint* pt = cvSubdiv2DEdgeDst( cvSubdiv2DRotateEdge( edge, 1 ));//这里eRot的旋转边缘应该是reversed e,那么目的点,就是e的源点。  
    159.         // cvFillConvexPoly( img, buf, count, CV_RGB(rand()&255,rand()&255,rand()&255), CV_AA, 0 );//填充凸多边形  
    160.         for(i=0;i<count;i++)  
    161.         {  
    162.             buf1[i].x=buf[i].x;  
    163.             buf1[i].y=buf[i].y;  
    164.         }  
    165.         Mat mat_img(img);  
    166.   
    167.         cvPolyLine( img, &buf, &count, 1, 1, CV_RGB(0,200,0), 1, CV_AA, 0);//画出线。  
    168.         //for(int i=0;i<count-1;i++)  
    169.         //{  
    170.         //dashLine(mat_img,buf1[i],buf1[i+1],100);  
    171.         //}  
    172.         //dashLine(mat_img,buf1[i],buf1[0],100);  
    173.         draw_subdiv_point( img, pt->pt, CV_RGB(255,0,0));//用黑色画出画出剖分顶点。  
    174.     }  
    175.     free( buf );  
    176. }  
    177.   
    178. static void paint_voronoi( CvSubdiv2D* subdiv, IplImage* img )//画出voronoi面  
    179. {  
    180.     CvSeqReader  reader;  
    181.     int i, total = subdiv->edges->total;//边缘总数  
    182.     int elem_size = subdiv->edges->elem_size;//边缘的大小  
    183.   
    184.     cvCalcSubdivVoronoi2D( subdiv );  
    185.   
    186.     cvStartReadSeq( (CvSeq*)(subdiv->edges), &reader, 0 );  
    187.   
    188.     for( i = 0; i < total; i++ )  
    189.     {  
    190.         CvQuadEdge2D* edge = (CvQuadEdge2D*)(reader.ptr);//获取四方边缘  
    191.   
    192.         if( CV_IS_SET_ELEM( edge ))//判断边缘是否在边缘集中  
    193.         {  
    194.             CvSubdiv2DEdge e = (CvSubdiv2DEdge)edge;//edge是四方边缘的指针,而CvSubdiv2DEdge高位表示四方边缘的指针。  
    195.             //cout<<(e&3)<<endl;//通过测试e低2位即索引值应该设置为0了,即输入边缘  
    196.             // left  
    197.             draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 1 ));//e为Delaunay边,获得Delaunay边对应的voronoi边,即e的旋转边缘  
    198.   
    199.             // right  
    200.             draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 3 ));//反向的旋转边缘  
    201.         }  
    202.   
    203.         CV_NEXT_SEQ_ELEM( elem_size, reader );//移动到下一个位置  
    204.     }  
    205. }  
    206.   
    207.   
    208. static void run(void)  
    209. {  
    210.     char win[] = "source";  
    211.     int i;  
    212.     CvRect rect = { 0, 0, 600, 600 };  
    213.     CvMemStorage* storage;  
    214.     CvSubdiv2D* subdiv;  
    215.     IplImage* img;  
    216.     CvScalar active_facet_color, delaunay_color, voronoi_color, bkgnd_color;  
    217.   
    218.     active_facet_color = CV_RGB( 255, 0, 0 );//红色  
    219.     delaunay_color  = CV_RGB( 0,0,0);//黑色  
    220.     voronoi_color = CV_RGB(0, 180, 0);//绿色  
    221.     bkgnd_color = CV_RGB(255,255,255);//白色  
    222.   
    223.     img = cvCreateImage( cvSize(rect.width,rect.height), 8, 3 );  
    224.     cvSet( img, bkgnd_color, 0 );  
    225.   
    226.     cvNamedWindow( win, 1 );  
    227.   
    228.     storage = cvCreateMemStorage(0);  
    229.     subdiv = init_delaunay( storage, rect );  
    230.   
    231.     printf("Delaunay triangulation will be build now interactively. "  
    232.         "To stop the process, press any key ");  
    233.   
    234.     vector<CvPoint2D32f> points;  
    235.     for( i = 0; i < 5; i++ )  
    236.     {  
    237.         CvPoint2D32f fp = cvPoint2D32f( (float)(rand()%(rect.width-10)),//使点约束在距离边框10像素之内。  
    238.             (float)(rand()%(rect.height-10)));  
    239.         points.push_back(fp);  
    240.   
    241.         locate_point( subdiv, fp, img, active_facet_color );//定位点的位置,并画出点所在voronoi面的边。  
    242.         cvShowImage( win, img );//刷新显示  
    243.   
    244.         if( cvWaitKey( 100 ) >= 0 )  
    245.             break;  
    246.   
    247.         cvSubdivDelaunay2DInsert( subdiv, fp );//向三角剖分中插入该点,即对该点进行三角剖分  
    248.         cvCalcSubdivVoronoi2D( subdiv );//计算Voronoi细分,有时候我们不需要  
    249.         cvSet( img, bkgnd_color, 0 );//设置图像的背景颜色为白色  
    250.         draw_subdiv( img, subdiv, delaunay_color, voronoi_color);  
    251.         cvShowImage( win, img );  
    252.   
    253.         //cvWaitKey();  
    254.         if( cvWaitKey( 100 ) >= 0 )  
    255.             break;  
    256.     }  
    257.     for(int i=0;i<points.size();i++)  
    258.         draw_subdiv_point( img, points[i], active_facet_color );  
    259.     cvShowImage(win,img);  
    260.     cvWaitKey();  
    261.   
    262.     //  cvSet( img, bkgnd_color, 0 );//重新刷新画布,即设置背景颜色为白色  
    263.     paint_voronoi( subdiv, img );//画出细分  
    264.     cvShowImage( win, img );//  
    265.   
    266.     cvWaitKey(0);  
    267.   
    268.     cvReleaseMemStorage( &storage );  
    269.     cvReleaseImage(&img);  
    270.     cvDestroyWindow( win );  
    271. }  
    272.   
    273. int main( int argc, char** argv )  
    274. {  
    275.     (void)argc; (void)argv;  
    276.     help();  
    277.     run();  
    278.     return 0;  
    279. }  
    280.   
    281. #ifdef _EiC  
    282. main( 1, "delaunay.c" );  
    283. #endif  


    执行效果如下图所示:黑色线表示三角剖分、绿色线表示相应的Voronoi细分,顶点用红色表示。


    程序二:

    和程序一类似,只是加了根据一个点,然后获取该点在所在的剖分平面(即包含该点的三角形),然后遍历该三角形:

    1. #include <opencv2/imgproc/imgproc_c.h>  
    2. #include <opencv2/legacy/legacy.hpp>  
    3. #include "opencv2/highgui/highgui.hpp"  
    4. #include<opencv2opencv.hpp>  
    5. #include<iostream>  
    6. #include <stdio.h>  
    7. using namespace std;  
    8. using namespace cv;  
    9. static void help( void )  
    10. {  
    11.     printf(" This program demostrates iterative construction of "//这个程序阐述了delaunay剖分和voronoi细分的迭代构造  
    12.         "delaunay triangulation and voronoi tesselation. "  
    13.         "It draws a random set of points in an image and then delaunay triangulates them. "//在图像上画出一些随机点,然后进行delaunay三角剖分  
    14.         "Usage:  "  
    15.         "./delaunay  "  
    16.         " This program builds the traingulation interactively, you may stop this process by "  
    17.         "hitting any key. ");//迭代构造三角剖分,如果像停止,则按任意键  
    18. }  
    19.   
    20.   
    21. static CvSubdiv2D* init_delaunay( CvMemStorage* storage,//初始化三角剖分结构,为其分配单元  
    22.     CvRect rect )  
    23. {  
    24.     CvSubdiv2D* subdiv;//三角剖分的数据单元  
    25.   
    26.     subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv),  
    27.         sizeof(CvSubdiv2DPoint),  
    28.         sizeof(CvQuadEdge2D),  
    29.         storage );  
    30.     cvInitSubdivDelaunay2D( subdiv, rect );  
    31.   
    32.     return subdiv;  
    33. }  
    34.   
    35.   
    36. static void draw_subdiv_point( IplImage* img, CvPoint2D32f fp, CvScalar color )//画出三角剖分的顶点  
    37. {  
    38.     cvCircle( img, cvPoint(cvRound(fp.x), cvRound(fp.y)),5, color, CV_FILLED, 8, 0 );  
    39. }  
    40.   
    41.   
    42. static void draw_subdiv_edge( IplImage* img, CvSubdiv2DEdge edge, CvScalar color )//画出三角剖分的边  
    43. {  
    44.     CvSubdiv2DPoint* org_pt;//源顶点  
    45.     CvSubdiv2DPoint* dst_pt;//目地顶点  
    46.     CvPoint2D32f org;  
    47.     CvPoint2D32f dst;  
    48.     CvPoint iorg, idst;  
    49.   
    50.     org_pt = cvSubdiv2DEdgeOrg(edge);//通过边获取顶点  
    51.     dst_pt = cvSubdiv2DEdgeDst(edge);  
    52.   
    53.     if( org_pt && dst_pt )//如果两个端点不为空  
    54.     {  
    55.         org = org_pt->pt;  
    56.         dst = dst_pt->pt;  
    57.   
    58.         iorg = cvPoint( cvRound( org.x ), cvRound( org.y ));  
    59.         idst = cvPoint( cvRound( dst.x ), cvRound( dst.y ));  
    60.   
    61.         cvLine( img, iorg, idst, color, 1, CV_AA, 0 );  
    62.     }  
    63. }  
    64.   
    65.   
    66. static void draw_subdiv( IplImage* img, CvSubdiv2D* subdiv,  
    67.     CvScalar delaunay_color, CvScalar voronoi_color  )//画出剖分和细分  
    68. {  
    69.     CvSeqReader  reader;  
    70.     int i, total = subdiv->edges->total;//边的数量  
    71.     int elem_size = subdiv->edges->elem_size;//边的大小  
    72.     cout<<typeid(subdiv->edges).name()<<endl;  
    73.   
    74.     cvStartReadSeq( (CvSeq*)(subdiv->edges), &reader, 0 );//使用CvSeqReader遍历Delaunay或者Voronoi边  
    75.   
    76.     for( i = 0; i < total; i++ )  
    77.     {  
    78.         CvQuadEdge2D* edge = (CvQuadEdge2D*)(reader.ptr);  
    79.   
    80.         if( CV_IS_SET_ELEM( edge ))  
    81.         {  
    82.             // draw_subdiv_edge( img, (CvSubdiv2DEdge)edge + 1, voronoi_color );  
    83.             draw_subdiv_edge( img, (CvSubdiv2DEdge)edge, delaunay_color );  
    84.         }  
    85.   
    86.         CV_NEXT_SEQ_ELEM( elem_size, reader );  
    87.     }  
    88.   
    89. }  
    90.   
    91.   
    92. static void locate_point( CvSubdiv2D* subdiv, CvPoint2D32f fp, IplImage* img,//遍历三角剖分的边  
    93.     CvScalar active_color )  
    94. {  
    95.     CvSubdiv2DEdge e;  
    96.     CvSubdiv2DEdge e0 = 0;  
    97.     CvSubdiv2DPoint* p = 0;  
    98.   
    99.     cvSubdiv2DLocate( subdiv, fp, &e0, &p );  
    100.   
    101.     if( e0 )  
    102.     {  
    103.         e = e0;  
    104.         do  
    105.         {  
    106.             draw_subdiv_edge( img, e, active_color );  
    107.             e = cvSubdiv2DGetEdge(e,CV_NEXT_AROUND_LEFT);  
    108.         }  
    109.         while( e != e0 );  
    110.     }  
    111.   
    112.     draw_subdiv_point( img, fp, active_color );  
    113. }  
    114.   
    115. //@author andme-单目视觉  
    116. void dashLine(Mat &img, Point2d& pt1, Point2d& pt2, int n)//n为虚线段数  
    117. {  
    118.     Point sub = pt2 - pt1;  
    119.     for (int i = 0; i < 2*n; i += 2)  
    120.     {  
    121.         line(img, Point(pt1.x + sub.x * i / (2 * n - 1), pt1.y + sub.y * i / (2 * n - 1)), Point(pt1.x + sub.x * (i+1) / (2 * n - 1), pt1.y + sub.y * (i+1) / (2 * n - 1)), Scalar(0,255,0), 2);  
    122.     }  
    123. }  
    124.   
    125.   
    126.   
    127. //调用形式draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 1 ));  
    128. static void draw_subdiv_facet( IplImage* img, CvSubdiv2DEdge edge )//画出voronoi面   
    129. {  
    130.     //cout<<edge<<endl;//edge低两位表示表示索引,高位表示四方边缘指针。  
    131.     //cout<<(edge&3)<<endl;  
    132.     CvSubdiv2DEdge t = edge;//当我们按上面的调用形式时,edge为eRot。  
    133.     int i, count = 0;  
    134.     CvPoint* buf = 0;  
    135.     Point2d *buf1=0;  
    136.   
    137.     // count number of edges in facet //面内边的计数  
    138.     do  
    139.     {  
    140.         count++;  
    141.         t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );  
    142.     } while (t != edge );//我们绕着一个voronoi单元一周,遍历该vornonoi边缘所拥有的边缘数。  
    143.   
    144.     buf = (CvPoint*)malloc( count * sizeof(buf[0]));  
    145.     buf1=(Point2d*)malloc(count*sizeof(buf1[0]));  
    146.   
    147.     // gather points  
    148.     t = edge;  
    149.     for( i = 0; i < count; i++ )  
    150.     {  
    151.         CvSubdiv2DPoint* pt = cvSubdiv2DEdgeOrg( t );//第一次获取eRot边缘的起始点  
    152.         if( !pt ) break;//如果得不到该源点,则退出循环  
    153.         buf[i] = cvPoint( cvRound(pt->pt.x), cvRound(pt->pt.y));//将该点转换为cvPoint类型点,存储在buf中  
    154.         t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );//然后绕着vornonoi单元,左旋转。  
    155.     }  
    156.   
    157.     if( i == count )//如果所有的点都存储起来了。  
    158.     {  
    159.         CvSubdiv2DPoint* pt = cvSubdiv2DEdgeDst( cvSubdiv2DRotateEdge( edge, 1 ));//这里eRot的旋转边缘应该是reversed e,那么目的点,就是e的源点。  
    160.         // cvFillConvexPoly( img, buf, count, CV_RGB(rand()&255,rand()&255,rand()&255), CV_AA, 0 );//填充凸多边形  
    161.         for(i=0;i<count;i++)  
    162.         {  
    163.             buf1[i].x=buf[i].x;  
    164.             buf1[i].y=buf[i].y;  
    165.         }  
    166.         Mat mat_img(img);  
    167.       
    168.         cvPolyLine( img, &buf, &count, 1, 1, CV_RGB(0,200,0), 1, CV_AA, 0);//画出线。  
    169.           
    170.         //for(int i=0;i<count-1;i++)  
    171.         //{  
    172.         //dashLine(mat_img,buf1[i],buf1[i+1],100);  
    173.         //}  
    174.         //dashLine(mat_img,buf1[i],buf1[0],100);  
    175.         draw_subdiv_point( img, pt->pt, CV_RGB(255,0,0));//用黑色画出画出剖分顶点。  
    176.     }  
    177.     free( buf );  
    178. }  
    179. /**********************************************重点部分:如何实现变量所有的Delauany或者Voronoi边*****************************/  
    180. static void paint_voronoi( CvSubdiv2D* subdiv, IplImage* img )//画出voronoi面  
    181. {  
    182.     CvSeqReader  reader;  
    183.     int i, total = subdiv->edges->total;//边缘总数  
    184.     int elem_size = subdiv->edges->elem_size;//边缘的大小  
    185.   
    186.     cvCalcSubdivVoronoi2D( subdiv );  
    187.   
    188.     cvStartReadSeq( (CvSeq*)(subdiv->edges), &reader, 0 );  
    189.   
    190.     for( i = 0; i < total; i++ )  
    191.     {  
    192.         CvQuadEdge2D* edge = (CvQuadEdge2D*)(reader.ptr);//获取四方边缘  
    193.   
    194.         if( CV_IS_SET_ELEM( edge ))//判断边缘是否在边缘集中  
    195.         {  
    196.             CvSubdiv2DEdge e = (CvSubdiv2DEdge)edge;//edge是四方边缘的指针,而CvSubdiv2DEdge高位表示四方边缘的指针。  
    197.             //cout<<(e&3)<<endl;//通过测试e低2位即索引值应该设置为0了,即输入边缘  
    198.             // left  
    199.             draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 1 ));//e为Delaunay边,获得Delaunay边对应的voronoi边,即e的旋转边缘  
    200.   
    201.             // right  
    202.             draw_subdiv_facet( img, cvSubdiv2DRotateEdge( e, 3 ));//反向的旋转边缘  
    203.         }  
    204.   
    205.         CV_NEXT_SEQ_ELEM( elem_size, reader );//移动到下一个位置  
    206.     }  
    207. }  
    208. /*************************************************************************************/  
    209. void  draw_edge(CvSubdiv2DEdge e0,IplImage *img,const char *cp )  
    210. {  
    211. CvSubdiv2DPoint *point1_org=cvSubdiv2DEdgeOrg(e0);  
    212.         CvSubdiv2DPoint *point1_dst=cvSubdiv2DEdgeDst(e0);  
    213.         CvPoint pt_org=cvPointFrom32f(point1_org->pt);  
    214.         CvPoint pt_dst=cvPointFrom32f(point1_dst->pt);  
    215.         CvPoint pt;  
    216.         pt.x=(pt_org.x+pt_dst.x)/2;  
    217.         pt.y=(pt_org.y+pt_dst.y)/2;  
    218.         CvFont font;  
    219.         cvInitFont(&font,CV_FONT_ITALIC,1,1,0,2,8);  
    220.         cvLine(img,pt_org,pt_dst,cvScalar(255,0,0),2,8);  
    221.         cvCircle(img,pt,6,cvScalar(0,0,0),2,CV_AA);  
    222.         cout<<"点位于"<<pt.x<<" "<<pt.y<<endl;  
    223.         cvPutText(img,cp,pt,&font,cvScalar(0,255,0));  
    224.         if(pt_dst.y-pt_org.y>0)  
    225.         {  
    226.             cout<<"箭头朝下"<<endl;  
    227.         }else   
    228.         {  
    229.             cout<<"箭头朝上"<<endl;  
    230.         }  
    231.   
    232. }  
    233. static void run(void)  
    234. {  
    235.     char win[] = "source";  
    236.     int i;  
    237.     CvRect rect = { 0, 0, 600, 600 };  
    238.     CvMemStorage* storage;  
    239.     CvSubdiv2D* subdiv;  
    240.     IplImage* img;  
    241.     CvScalar active_facet_color, delaunay_color, voronoi_color, bkgnd_color;  
    242.   
    243.     active_facet_color = CV_RGB( 255, 0, 0 );//红色  
    244.     delaunay_color  = CV_RGB( 0,0,0);//黑色  
    245.     voronoi_color = CV_RGB(0, 180, 0);//绿色  
    246.     bkgnd_color = CV_RGB(255,255,255);//白色  
    247.   
    248.     img = cvCreateImage( cvSize(rect.width,rect.height), 8, 3 );  
    249.     cvSet( img, bkgnd_color, 0 );  
    250.   
    251.     cvNamedWindow( win, 1 );  
    252.   
    253.     storage = cvCreateMemStorage(0);  
    254.     subdiv = init_delaunay( storage, rect );  
    255.   
    256.     printf("Delaunay triangulation will be build now interactively. "  
    257.         "To stop the process, press any key ");  
    258.   
    259.     vector<CvPoint2D32f> points;  
    260.     for( i = 0; i < 5; i++ )  
    261.     {  
    262.         CvPoint2D32f fp = cvPoint2D32f( (float)(rand()%(rect.width-10)),//使点约束在距离边框10像素之内。  
    263.             (float)(rand()%(rect.height-10)));  
    264.         points.push_back(fp);  
    265.   
    266.         locate_point( subdiv, fp, img, active_facet_color );//定位点的位置,并画出点所在voronoi面的边。  
    267.         cvShowImage( win, img );//刷新显示  
    268.   
    269.         if( cvWaitKey( 100 ) >= 0 )  
    270.             break;  
    271.   
    272.         cvSubdivDelaunay2DInsert( subdiv, fp );//向三角剖分中插入该点,即对该点进行三角剖分  
    273.         cvCalcSubdivVoronoi2D( subdiv );//计算Voronoi细分,有时候我们不需要  
    274.         cvSet( img, bkgnd_color, 0 );//设置图像的背景颜色为白色  
    275.         draw_subdiv( img, subdiv, delaunay_color, voronoi_color);  
    276.         cvShowImage( win, img );  
    277.   
    278.         //cvWaitKey();  
    279.         if( cvWaitKey( 100 ) >= 0 )  
    280.             break;  
    281.     }  
    282.     for(int i=0;i<points.size();i++)  
    283.         draw_subdiv_point( img, points[i], active_facet_color );  
    284.     cvShowImage(win,img);  
    285.     cvWaitKey();  
    286.   
    287.     //  cvSet( img, bkgnd_color, 0 );//重新刷新画布,即设置背景颜色为白色  
    288.     paint_voronoi( subdiv, img );//画出细分  
    289.       
    290.   
    291.       
    292.     CvPoint2D32f point1=cvPoint2D32f(300,300);//图像中心选择一点。  
    293.     CvSubdiv2DEdge e;  
    294.     CvSubdiv2DEdge e0 = 0;  
    295.     CvSubdiv2DPoint* p = 0;  
    296.     CvSubdiv2DPointLocation loc=cvSubdiv2DLocate( subdiv, point1, &e0, &p );  
    297.     if(loc==CV_PTLOC_INSIDE)  
    298.     {  
    299.         cout<<"落入某些面,箭头的方向用来说明图的方向"<<endl;  
    300.         draw_edge(e0,img,"fisrt");  
    301.         CvSubdiv2DEdge e_lnext=cvSubdiv2DGetEdge(e0,CV_NEXT_AROUND_LEFT);  
    302.         draw_edge(e_lnext,img,"second");  
    303.         CvSubdiv2DEdge e_Onext=cvSubdiv2DGetEdge(e_lnext,CV_NEXT_AROUND_LEFT);  
    304.         draw_edge(e_Onext,img,"third");  
    305.           
    306.   
    307.   
    308.     }else if(loc==CV_PTLOC_ON_EDGE)  
    309.     {  
    310.         cout<<"点落在边缘上"<<endl;  
    311.     }else if(loc==CV_PTLOC_VERTEX)  
    312.     {  
    313.         cout<<"和顶点重合"<<endl;  
    314.     }else   
    315.     {  
    316.         cout<<"输入变量无效"<<endl;  
    317.     }  
    318.     cvShowImage( win, img );//  
    319.     cvWaitKey(0);  
    320.   
    321.   
    322.     cvReleaseMemStorage( &storage );  
    323.     cvReleaseImage(&img);  
    324.     cvDestroyWindow( win );  
    325. }  
    326.   
    327. int main( int argc, char** argv )  
    328. {  
    329.     (void)argc; (void)argv;  
    330.     help();  
    331.     run();  
    332.     return 0;  
    333. }  
    334.   
    335. #ifdef _EiC  
    336. main( 1, "delaunay.c" );  
    337. #endif  

    执行效果:

    上图中我们选择了图像的中心点,图像大小为600×600,故中心点为300×300,我们通过函数cvSubdiv2DLocate()得知该点落在了面内,然后我们该函数得到该面的一个边缘,我们有了边缘信息,如果我们帮它当做程序1上的参考图中的e,那么我就可以获得参考图中的所有边的信息,我们也可以根据这些边的信息获取的这些边的端点。

    并注意一下控制台的输出信息:即first边的方向向下,second为方向向上,third是方向向下。


    程序三:

    1. #include <opencv2/legacy/legacy.hpp>  
    2. #include <opencv2/opencv.hpp>    
    3. #include <opencv2/nonfree/nonfree.hpp>    
    4. #include <opencv2/nonfree/features2d.hpp>    
    5. #include <atlstr.h> // use STL string instead, although not as convenient...  
    6. #include <atltrace.h>  
    7. #include <iostream>  
    8. #include <fstream>  
    9. #include <string>  
    10. #include<time.h>  
    11.   
    12. using namespace std;  
    13. using namespace cv;  
    14. /* 
    15. pts,要剖分的散点集,in 
    16. img,剖分的画布,in 
    17. tri,存储三个表示顶点变换的正数,out 
    18. */  
    19.   
    20. // used for doing delaunay trianglation with opencv function  
    21. //该函数用来防止多次重画并消去虚拟三角形的 顶点  
    22. bool isGoodTri( Vec3i &v, vector<Vec3i> & tri )   
    23. {  
    24.     int a = v[0], b = v[1], c = v[2];  
    25.     v[0] = min(a,min(b,c));//v[0]找到点插入的先后顺序(0....N-1,N为点的个数)的最小值  
    26.     v[2] = max(a,max(b,c));//v[2]存储最大值.  
    27.     v[1] = a+b+c-v[0]-v[2];//v[1]为中间值  
    28.     if (v[0] == -1) return false;  
    29.   
    30.     vector<Vec3i>::iterator iter = tri.begin();//开始时为空  
    31.     for(;iter!=tri.end();iter++)  
    32.     {  
    33.         Vec3i &check = *iter;//如果当前待压入的和存储的重复了,则停止返回false。  
    34.         if (check[0]==v[0] &&  
    35.             check[1]==v[1] &&  
    36.             check[2]==v[2])  
    37.         {  
    38.             break;  
    39.         }  
    40.     }  
    41.     if (iter == tri.end())  
    42.     {  
    43.         tri.push_back(v);  
    44.         return true;  
    45.     }  
    46.     return false;  
    47. }  
    48. /* 
    49. pts,要剖分的散点集,in 
    50. img,剖分的画布,in 
    51. tri,存储三个表示顶点变换的正数,out 
    52. */  
    53. void TriSubDiv( vector<Point2f> &pts, Mat &img, vector<Vec3i> &tri )   
    54. {  
    55.     CvSubdiv2D* subdiv;  
    56.     CvMemStorage* storage = cvCreateMemStorage(0); //创建存储器  
    57.     Rect rc = Rect(0,0, img.cols, img.rows);//矩形是图像的大小  
    58.   
    59.     subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv),  
    60.         sizeof(CvSubdiv2DPoint),  
    61.         sizeof(CvQuadEdge2D),  
    62.         storage );//为剖分数据分配空间  
    63.     cvInitSubdivDelaunay2D( subdiv, rc );  
    64.     for (size_t i = 0; i < pts.size(); i++)  
    65.     {  
    66.         CvSubdiv2DPoint *pt = cvSubdivDelaunay2DInsert( subdiv, pts[i] );//利用插入法进行剖分  
    67.         pt->id = i;//为每一个顶点分配一个id  
    68.           
    69.     }  
    70.   
    71.     CvSeqReader reader;//利用CvSeqReader遍历  
    72.     int total = subdiv->edges->total;//边的总数  
    73.     int elem_size = subdiv->edges->elem_size;//边的大小  
    74.   
    75.     cvStartReadSeq( (CvSeq*)(subdiv->edges), &reader, 0 );  
    76.     Point buf[3];  
    77.     const Point *pBuf = buf;  
    78.     Vec3i verticesIdx;  
    79.     Mat imgShow = img.clone();  
    80.   
    81.     srand( (unsigned)time( NULL ) );     
    82.     forint i = 0; i < total; i++ )   
    83.     {     
    84.         CvQuadEdge2D* edge = (CvQuadEdge2D*)(reader.ptr);     
    85.   
    86.         if( CV_IS_SET_ELEM( edge ))   
    87.         {  
    88.             CvSubdiv2DEdge t = (CvSubdiv2DEdge)edge;   
    89.             int iPointNum = 3;  
    90.             Scalar color = CV_RGB(rand()&255,rand()&255,rand()&255);  
    91.             //Scalar color=CV_RGB(255,0,0);  
    92.             //bool isNeg = false;  
    93.             int j;  
    94.             for(j = 0; j < iPointNum; j++ )  
    95.             {  
    96.                 CvSubdiv2DPoint* pt = cvSubdiv2DEdgeOrg( t );//获取t边的源点  
    97.                 if( !pt ) break;  
    98.                 buf[j] = pt->pt;//将点存储起来  
    99.                 //if (pt->id == -1) isNeg = true;  
    100.                 verticesIdx[j] = pt->id;//获取顶点的Id号,将三个点的id存储到verticesIdx中  
    101.                 t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );//获取下一条边  
    102.             }  
    103.             if (j != iPointNum) continue;  
    104.             if (isGoodTri(verticesIdx, tri))  
    105.             {  
    106.                 //tri.push_back(verticesIdx);  
    107.                 polylines( imgShow, &pBuf, &iPointNum,   
    108.                     1, true, color,  
    109.                     1, CV_AA, 0);//画出三条边  
    110.                 //printf("(%d, %d)-(%d, %d)-(%d, %d) ", buf[0].x, buf[0].y, buf[1].x, buf[1].y, buf[2].x, buf[2].y);  
    111.                 //printf("%d %d %d ", verticesIdx[0], verticesIdx[1], verticesIdx[2]);  
    112.                 //imshow("Delaunay", imgShow);  
    113.                 //waitKey();  
    114.             }  
    115.               
    116.             t = (CvSubdiv2DEdge)edge+2;//相反边缘 reversed e  
    117.   
    118.             for(j = 0; j < iPointNum; j++ )  
    119.             {  
    120.                 CvSubdiv2DPoint* pt = cvSubdiv2DEdgeOrg( t );  
    121.                 if( !pt ) break;  
    122.                 buf[j] = pt->pt;  
    123.                 verticesIdx[j] = pt->id;  
    124.                 t = cvSubdiv2DGetEdge( t, CV_NEXT_AROUND_LEFT );  
    125.             }     
    126.             if (j != iPointNum) continue;  
    127.             if (isGoodTri(verticesIdx, tri))  
    128.             {  
    129.                 //tri.push_back(verticesIdx);  
    130.                 polylines( imgShow, &pBuf, &iPointNum,   
    131.                     1, true, color,  
    132.                     1, CV_AA, 0);  
    133.                 //printf("(%d, %d)-(%d, %d)-(%d, %d) ", buf[0].x, buf[0].y, buf[1].x, buf[1].y, buf[2].x, buf[2].y);  
    134.                 //printf("%d %d %d ", verticesIdx[0], verticesIdx[1], verticesIdx[2]);  
    135.                 //imshow("Delaunay", imgShow);  
    136.                 //waitKey();  
    137.         }  
    138.               
    139.         }  
    140.   
    141.         CV_NEXT_SEQ_ELEM( elem_size, reader );  
    142.   
    143.     }  
    144.   
    145.     //RemoveDuplicate(tri);  
    146.     char title[100];  
    147.     sprintf_s(title, 100, "Delaunay: %d Triangles", tri.size());//tri存储的为3个顶点为一个vec3i,故tri.size()表示三角形的个数。  
    148.     imshow(title, imgShow);  
    149.     waitKey();  
    150. }  
    151.   
    152. void main(int argc, char* argv[])  
    153.   
    154. {  
    155.     Mat imgL(600,600,CV_8UC3);  
    156.     /************************************************************************/  
    157.     /* Delaunay triangulation                                               */  
    158.     /************************************************************************/  
    159.     cout<<"doing triangulation..."<<endl;  
    160.     vector<Vec3i> tri;  
    161.   
    162.     vector<Point2f> vec_points;  
    163.     for(int  i = 0; i < 60; i++ )    
    164.     {    
    165.         Point2f fp = cvPoint2D32f( (float)(rand()%(imgL.cols-10)),//使点约束在距离边框10像素之内。    
    166.             (float)(rand()%(imgL.rows-10)));    
    167.         vec_points.push_back(fp);    
    168.     }  
    169.   
    170.     TriSubDiv(vec_points, imgL, tri);  
    171.   
    172.   
    173. }  

    执行结果:


    上程序中,通过isGoodTri()函数可以有效地防止重画并且消除虚拟三角形的顶点。

  • 相关阅读:
    父目录权限子目录权限关系
    微信自媒体账号涉违规大规模被封
    微信支付接口申请指南
    微信公众平台开发(83) 生成带参数二维码
    百度天气预报接口
    微信支付全面开放
    公众平台商户接入(微信支付)功能申请教程
    移动互联网流量变现模式调研问卷
    天气预报接口
    微信公众平台开发(82) 天气预报
  • 原文地址:https://www.cnblogs.com/zfluo/p/5131851.html
Copyright © 2011-2022 走看看