【计算几何】多边形点集排序

问题描述:已知多边形点集C={P1,P2,...,PN},其排列顺序是杂乱,依次连接这N个点,无法形成确定的多边形,需要对点集C进行排序后,再绘制多边形。

点集排序过程中,关键在于如何定义点的大小关系。

以按逆时针排序为例,算法步骤如下:

定义:点A在点B的逆时针方向,则点A大于点B

1.计算点集的重心O,以重心作为逆时针旋转的中心点。

2.计算点之间的大小关系。

大小关系的计算,可由两种方法进行计算。

方法1:

以重心O作一条平行于X轴的单位向量OX,然后依次计算OPi和OX的夹角,根据夹角的大小,确定点之间的大小关系。

OPi和OX夹角越大,说明点Pi越小,如图所示。

方法2:

根据向量叉积的定义,向量OPi和OPj的叉积大于0,则向量OPj在向量OPi的逆时针方向,即点Pj小于点Pi。

依据方法2,多边形点集排序的代码如下:

 1 typedef struct Point
 2 {
 3     int x;
 4     int y;
 5 }Point;
 6 //若点a大于点b,即点a在点b顺时针方向,返回true,否则返回false
 7 bool PointCmp(const Point &a,const Point &b,const Point &center)
 8 {
 9     if (a.x >= 0 && b.x < 0)
10         return true;
11     if (a.x == 0 && b.x == 0)
12         return a.y > b.y;
13     //向量OA和向量OB的叉积
14     int det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);
15     if (det < 0)
16         return true;
17     if (det > 0)
18         return false;
19     //向量OA和向量OB共线,以距离判断大小
20     int d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);
21     int d2 = (b.x - center.x) * (b.x - center.y) + (b.y - center.y) * (b.y - center.y);
22     return d1 > d2;
23 }
24 void ClockwiseSortPoints(std::vector<Point> &vPoints)
25 {
26     //计算重心
27     cv::Point center;
28     double x = 0,y = 0;
29     for (int i = 0;i < vPoints.size();i++)
30     {
31         x += vPoints[i].x;
32         y += vPoints[i].y;
33     }
34     center.x = (int)x/vPoints.size();
35     center.y = (int)y/vPoints.size();
36 
37     //冒泡排序
38     for(int i = 0;i < vPoints.size() - 1;i++)
39     {
40         for (int j = 0;j < vPoints.size() - i - 1;j++)
41         {
42             if (PointCmp(vPoints[j],vPoints[j+1],center))
43             {
44                 cv::Point tmp = vPoints[j];
45                 vPoints[j] = vPoints[j + 1];
46                 vPoints[j + 1] = tmp;
47             }
48         }
49     }
50 }

参考资料:

http://blog.csdn.net/beyond071/article/details/5855171

http://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order

 

posted @ 2013-08-01 15:30  一点心青  阅读(20881)  评论(15编辑  收藏  举报