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


    问题描述:已知多边形点集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

  • 相关阅读:
    优雅得使用composer来安装各种PHP小工具
    Docker学习总结之Docker与Vagrant之间的特点比较
    深入理解php 匿名函数和 Closure
    laravel 拾遗 中间件
    centos 手动编译 fcitx 各种问题大全
    Install haroopad on centos7
    centos7 編譯 chmsee
    centos 7 禁用笔记本触摸板设置
    理解 Linux 配置文件
    输入法环境变量XMODIFIERS/GTK_IM_MODULE
  • 原文地址:https://www.cnblogs.com/xmphoenix/p/4508466.html
Copyright © 2020-2023  润新知