305

有一个点列表,我如何找到它们是否按顺时针顺序排列?

例如:

point[0] = (5,0)
point[1] = (6,4)
point[2] = (4,5)
point[3] = (1,5)
point[4] = (1,0)

会说它是逆时针(或逆时针,对某些人来说)。

4

23 回答 23

475

在非凸多边形(例如新月形)的情况下,一些建议的方法将失败。这是一个适用于非凸多边形的简单多边形(它甚至适用于像八字形这样的自相交多边形,告诉你它是否主要是顺时针的)。

对边求和,(x 2 - x 1 )(y 2 + y 1 )。如果结果为正,则曲线为顺时针,如果结果为负,则曲线为逆时针。(结果是封闭区域的两倍,采用 +/- 约定。)

point[0] = (5,0)   edge[0]: (6-5)(4+0) =   4
point[1] = (6,4)   edge[1]: (4-6)(5+4) = -18
point[2] = (4,5)   edge[2]: (1-4)(5+5) = -30
point[3] = (1,5)   edge[3]: (1-1)(0+5) =   0
point[4] = (1,0)   edge[4]: (5-1)(0+0) =   0
                                         ---
                                         -44  counter-clockwise
于 2009-07-22T15:02:22.263 回答
63

找到 y 最小的顶点(如果有联系,则 x 最大)。设顶点 beA和列表中的前一个顶点 beB和列表中的下一个顶点 be C。现在计算和的叉积的符号ABAC


参考:

于 2009-07-24T21:30:21.673 回答
55

我将提出另一种解决方案,因为它简单明了且数学上不密集——它只使用基本代数。计算多边形的有符号面积。如果为负,则点按顺时针顺序排列,如果为正,则按逆时针顺序排列。(这与 Beta 的解决方案非常相似。)

计算有符号面积: A = 1/2 * (x 1 *y 2 - x 2 *y 1 + x 2 *y 3 - x 3 *y 2 + ... + x n *y 1 - x 1 *y n )

或者在伪代码中:

signedArea = 0
for each point in points:
    x1 = point[0]
    y1 = point[1]
    if point is last point
        x2 = firstPoint[0]
        y2 = firstPoint[1]
    else
        x2 = nextPoint[0]
        y2 = nextPoint[1]
    end if

    signedArea += (x1 * y2 - x2 * y1)
end for
return signedArea / 2

请注意,如果您只检查排序,则无需费心除以 2。

资料来源: http: //mathworld.wolfram.com/PolygonArea.html

于 2012-04-24T13:19:30.660 回答
50

测量两个向量的垂直度。想象一下,多边形的每条边都是三维 (3-D) xyz 空间的 xy 平面中的向量。然后两个连续边的叉积是 z 方向上的向量,(如果第二段是顺时针方向,则为正 z 方向,如果是逆时针方向,则为负 z 方向)。该向量的大小与两个原始边缘之间的角度的正弦成正比,因此当它们垂直时它达到最大值,当边缘共线(平行)时逐渐变小以消失。

因此,对于多边形的每个顶点(点),计算两个相邻边的叉积大小:

Using your data:
point[0] = (5, 0)
point[1] = (6, 4)
point[2] = (4, 5)
point[3] = (1, 5)
point[4] = (1, 0)

因此,连续标记边缘,就像从to和between to ...之间的
edgeA线段一样。 point0point1
edgeBpoint1point2

edgeEpoint4point0

那么顶点 A ( point0) 在
edgeE[From point4to point0]
edgeA[From point0to `point1'之间

这两条边本身就是向量,其 x 和 y 坐标可以通过减去它们的起点和终点的坐标来确定:

edgeE= point0- point4= (1, 0) - (5, 0)=(-4, 0)
edgeA= point1- point0= (6, 4) - (1, 0)=(5, 4)

并且这两个相邻边的叉积是使用以下矩阵的行列式计算的,该矩阵是通过将两个向量的坐标放在表示三个坐标轴(ij、 & k)的符号下方来构造的。第三个(零)值坐标在那里,因为叉积概念是一个 3-D 构造,因此我们将这些 2-D 向量扩展为 3-D 以应用叉积:

 i    j    k 
-4    0    0
 1    4    0    

假设所有叉积都产生一个垂直于两个向量相乘平面的向量,那么上面矩阵的行列式只有一个k, (或 z 轴)分量。或z轴分量
大小的计算公式为 = k
a1*b2 - a2*b1 = -4* 4 - 0* 1-16

该值 ( -16) 的大小是 2 个原始向量之间的角度的正弦值乘以 2 个向量的大小的乘积的量度。
实际上,它的值的另一个公式是
A X B (Cross Product) = |A| * |B| * sin(AB)

因此,要回到角度的度量,您需要将该值 ( -16) 除以两个向量的大小的乘积。

|A| * |B| = 4 * Sqrt(17) =16.4924...

所以 sin(AB) = -16 / 16.4924=-.97014...

这是对顶点之后的下一段是否向左或向右弯曲以及弯曲程度的度量。不需要取反正弦。我们只关心它的大小,当然还有它的符号(正或负)!

对封闭路径周围的其他 4 个点中的每一个执行此操作,并将此计算中的每个顶点的值相加。

如果最终总和为正,则顺时针,负,逆时针。

于 2009-07-22T18:23:26.457 回答
31

这是基于@Beta 的答案的算法的简单 C# 实现。

假设我们有一个Vector具有 typeXY属性的类型double

public bool IsClockwise(IList<Vector> vertices)
{
    double sum = 0.0;
    for (int i = 0; i < vertices.Count; i++) {
        Vector v1 = vertices[i];
        Vector v2 = vertices[(i + 1) % vertices.Count];
        sum += (v2.X - v1.X) * (v2.Y + v1.Y);
    }
    return sum > 0.0;
}

%是执行模运算的模或余数运算符(根据维基百科),它在一个数字除以另一个数字后找到余数。


根据@MichelRouzic 的评论优化版本:

double sum = 0.0;
Vector v1 = vertices[vertices.Count - 1]; // or vertices[^1] with
                                          // C# 8.0+ and .NET Core
for (int i = 0; i < vertices.Count; i++) {
    Vector v2 = vertices[i];
    sum += (v2.X - v1.X) * (v2.Y + v1.Y);
    v1 = v2;
}
return sum > 0.0;

这不仅节省了模运算%,还节省了数组索引。

于 2013-08-27T18:28:55.143 回答
6

从其中一个顶点开始,计算每条边所对的角度。

第一个和最后一个将是零(所以跳过那些);对于其余部分,角度的正弦将由 (point[n]-point[0]) 和 (point[n-1]-point[0]) 的单位长度的归一化的叉积给出。

如果值的总和为正,则您的多边形是以逆时针方向绘制的。

于 2009-07-22T14:31:08.773 回答
5

肖恩的答案在 JavaScript 中的实现:

function calcArea(poly) {
    if(!poly || poly.length < 3) return null;
    let end = poly.length - 1;
    let sum = poly[end][0]*poly[0][1] - poly[0][0]*poly[end][1];
    for(let i=0; i<end; ++i) {
        const n=i+1;
        sum += poly[i][0]*poly[n][1] - poly[n][0]*poly[i][1];
    }
    return sum;
}

function isClockwise(poly) {
    return calcArea(poly) > 0;
}

let poly = [[352,168],[305,208],[312,256],[366,287],[434,248],[416,186]];

console.log(isClockwise(poly));

let poly2 = [[618,186],[650,170],[701,179],[716,207],[708,247],[666,259],[637,246],[615,219]];

console.log(isClockwise(poly2));

很确定这是对的。它似乎正在工作:-)

如果您想知道,这些多边形看起来像这样:

于 2017-10-06T20:36:03.523 回答
4

对于它的价值,我使用这个 mixin 来计算 Google Maps API v3 应用程序的缠绕顺序。

该代码利用了多边形区域的副作用:顶点的顺时针缠绕顺序产生正面积,而相同顶点的逆时针缠绕顺序产生相同的面积作为负值。该代码还使用了 Google Maps 几何库中的一种私有 API。我觉得使用它很舒服 - 使用风险自负。

示例用法:

var myPolygon = new google.maps.Polygon({/*options*/});
var isCW = myPolygon.isPathClockwise();

单元测试的完整示例@ http://jsfiddle.net/stevejansen/bq2ec/

/** Mixin to extend the behavior of the Google Maps JS API Polygon type
 *  to determine if a polygon path has clockwise of counter-clockwise winding order.
 *  
 *  Tested against v3.14 of the GMaps API.
 *
 *  @author  stevejansen_github@icloud.com
 *
 *  @license http://opensource.org/licenses/MIT
 *
 *  @version 1.0
 *
 *  @mixin
 *  
 *  @param {(number|Array|google.maps.MVCArray)} [path] - an optional polygon path; defaults to the first path of the polygon
 *  @returns {boolean} true if the path is clockwise; false if the path is counter-clockwise
 */
(function() {
  var category = 'google.maps.Polygon.isPathClockwise';
     // check that the GMaps API was already loaded
  if (null == google || null == google.maps || null == google.maps.Polygon) {
    console.error(category, 'Google Maps API not found');
    return;
  }
  if (typeof(google.maps.geometry.spherical.computeArea) !== 'function') {
    console.error(category, 'Google Maps geometry library not found');
    return;
  }

  if (typeof(google.maps.geometry.spherical.computeSignedArea) !== 'function') {
    console.error(category, 'Google Maps geometry library private function computeSignedArea() is missing; this may break this mixin');
  }

  function isPathClockwise(path) {
    var self = this,
        isCounterClockwise;

    if (null === path)
      throw new Error('Path is optional, but cannot be null');

    // default to the first path
    if (arguments.length === 0)
        path = self.getPath();

    // support for passing an index number to a path
    if (typeof(path) === 'number')
        path = self.getPaths().getAt(path);

    if (!path instanceof Array && !path instanceof google.maps.MVCArray)
      throw new Error('Path must be an Array or MVCArray');

    // negative polygon areas have counter-clockwise paths
    isCounterClockwise = (google.maps.geometry.spherical.computeSignedArea(path) < 0);

    return (!isCounterClockwise);
  }

  if (typeof(google.maps.Polygon.prototype.isPathClockwise) !== 'function') {
    google.maps.Polygon.prototype.isPathClockwise = isPathClockwise;
  }
})();
于 2013-12-20T05:35:34.327 回答
3

这是OpenLayers 2实现的功能。具有顺时针多边形的条件是area < 0,它由this reference确认。

function IsClockwise(feature)
{
    if(feature.geometry == null)
        return -1;

    var vertices = feature.geometry.getVertices();
    var area = 0;

    for (var i = 0; i < (vertices.length); i++) {
        j = (i + 1) % vertices.length;

        area += vertices[i].x * vertices[j].y;
        area -= vertices[j].x * vertices[i].y;
        // console.log(area);
    }

    return (area < 0);
}
于 2014-11-18T10:56:17.757 回答
3

实现lhf 答案的C# 代码:

// https://en.wikipedia.org/wiki/Curve_orientation#Orientation_of_a_simple_polygon
public static WindingOrder DetermineWindingOrder(IList<Vector2> vertices)
{
    int nVerts = vertices.Count;
    // If vertices duplicates first as last to represent closed polygon,
    // skip last.
    Vector2 lastV = vertices[nVerts - 1];
    if (lastV.Equals(vertices[0]))
        nVerts -= 1;
    int iMinVertex = FindCornerVertex(vertices);
    // Orientation matrix:
    //     [ 1  xa  ya ]
    // O = | 1  xb  yb |
    //     [ 1  xc  yc ]
    Vector2 a = vertices[WrapAt(iMinVertex - 1, nVerts)];
    Vector2 b = vertices[iMinVertex];
    Vector2 c = vertices[WrapAt(iMinVertex + 1, nVerts)];
    // determinant(O) = (xb*yc + xa*yb + ya*xc) - (ya*xb + yb*xc + xa*yc)
    double detOrient = (b.X * c.Y + a.X * b.Y + a.Y * c.X) - (a.Y * b.X + b.Y * c.X + a.X * c.Y);

    // TBD: check for "==0", in which case is not defined?
    // Can that happen?  Do we need to check other vertices / eliminate duplicate vertices?
    WindingOrder result = detOrient > 0
            ? WindingOrder.Clockwise
            : WindingOrder.CounterClockwise;
    return result;
}

public enum WindingOrder
{
    Clockwise,
    CounterClockwise
}

// Find vertex along one edge of bounding box.
// In this case, we find smallest y; in case of tie also smallest x.
private static int FindCornerVertex(IList<Vector2> vertices)
{
    int iMinVertex = -1;
    float minY = float.MaxValue;
    float minXAtMinY = float.MaxValue;
    for (int i = 0; i < vertices.Count; i++)
    {
        Vector2 vert = vertices[i];
        float y = vert.Y;
        if (y > minY)
            continue;
        if (y == minY)
            if (vert.X >= minXAtMinY)
                continue;

        // Minimum so far.
        iMinVertex = i;
        minY = y;
        minXAtMinY = vert.X;
    }

    return iMinVertex;
}

// Return value in (0..n-1).
// Works for i in (-n..+infinity).
// If need to allow more negative values, need more complex formula.
private static int WrapAt(int i, int n)
{
    // "+n": Moves (-n..) up to (0..).
    return (i + n) % n;
}
于 2019-02-06T03:50:50.817 回答
2

如果您使用 Matlab,ispolycw如果多边形顶点按顺时针顺序,该函数将返回 true。

于 2013-10-17T14:10:42.810 回答
1

正如在这篇维基百科文章中解释的曲线方向,给定 3 个点pq并且r在平面上(即具有 x 和 y 坐标),您可以计算以下行列式的符号

在此处输入图像描述

如果行列式为负(即Orient(p, q, r) < 0),则多边形的方向为顺时针方向(CW)。如果行列式为正(即Orient(p, q, r) > 0),则多边形的方向为逆时针(CCW)。Orient(p, q, r) == 0如果点和共线p,则行列式为零(即) 。qr

在上面的公式中,我们在 的坐标前面加上那些 ,p因为我们使用的是齐次坐标qr

于 2014-05-01T17:33:38.707 回答
0

我认为为了顺时针给出某些点,所有边缘都必须是正的,而不仅仅是边缘的总和。如果一个边缘是负数,则逆时针方向至少给出 3 个点。

于 2015-02-24T12:41:31.087 回答
0

这是我使用其他答案中的解释的解决方案:

def segments(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return zip(poly, poly[1:] + [poly[0]])

def check_clockwise(poly):
    clockwise = False
    if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(poly))) < 0:
        clockwise = not clockwise
    return clockwise

poly = [(2,2),(6,2),(6,6),(2,6)]
check_clockwise(poly)
False

poly = [(2, 6), (6, 6), (6, 2), (2, 2)]
check_clockwise(poly)
True
于 2013-03-06T15:25:29.590 回答
0

另一个解决方案;

const isClockwise = (vertices=[]) => {
    const len = vertices.length;
    const sum = vertices.map(({x, y}, index) => {
        let nextIndex = index + 1;
        if (nextIndex === len) nextIndex = 0;

        return {
            x1: x,
            x2: vertices[nextIndex].x,
            y1: x,
            y2: vertices[nextIndex].x
        }
    }).map(({ x1, x2, y1, y2}) => ((x2 - x1) * (y1 + y2))).reduce((a, b) => a + b);

    if (sum > -1) return true;
    if (sum < 0) return false;
}

像这样把所有的顶点当作一个数组;

const vertices = [{x: 5, y: 0}, {x: 6, y: 4}, {x: 4, y: 5}, {x: 1, y: 5}, {x: 1, y: 0}];
isClockwise(vertices);
于 2018-05-03T11:58:46.660 回答
0

如果您已经知道多边形内的一个点,则计算上更简单的方法:

  1. 按顺序从原始多边形、点及其坐标中选择任何线段。

  2. 添加一个已知的“内部”点,并形成一个三角形。

  3. 使用这三点计算此处建议的 CW 或 CCW 。

于 2018-01-21T22:04:05.080 回答
0

在测试了几个不可靠的实现之后,提供开箱即用的 CW/CCW 方向的令人满意结果的算法是 OP 在线程 ( shoelace_formula_3) 中发布的算法。

与往常一样,正数表示顺时针方向,而负数表示逆时针方向。

于 2017-09-08T08:50:46.433 回答
0

我的 C# / LINQ 解决方案基于以下@charlesbretana 的交叉产品建议。您可以为绕组指定参考法线。只要曲线主要位于由向上矢量定义的平面内,它就应该起作用。

using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace SolidworksAddinFramework.Geometry
{
    public static class PlanePolygon
    {
        /// <summary>
        /// Assumes that polygon is closed, ie first and last points are the same
        /// </summary>
       public static bool Orientation
           (this IEnumerable<Vector3> polygon, Vector3 up)
        {
            var sum = polygon
                .Buffer(2, 1) // from Interactive Extensions Nuget Pkg
                .Where(b => b.Count == 2)
                .Aggregate
                  ( Vector3.Zero
                  , (p, b) => p + Vector3.Cross(b[0], b[1])
                                  /b[0].Length()/b[1].Length());

            return Vector3.Dot(up, sum) > 0;

        } 

    }
}

带有单元测试

namespace SolidworksAddinFramework.Spec.Geometry
{
    public class PlanePolygonSpec
    {
        [Fact]
        public void OrientationShouldWork()
        {

            var points = Sequences.LinSpace(0, Math.PI*2, 100)
                .Select(t => new Vector3((float) Math.Cos(t), (float) Math.Sin(t), 0))
                .ToList();

            points.Orientation(Vector3.UnitZ).Should().BeTrue();
            points.Reverse();
            points.Orientation(Vector3.UnitZ).Should().BeFalse();



        } 
    }
}
于 2016-06-24T07:21:13.717 回答
0

R确定方向的解决方案,如果顺时针反转(发现它对owin对象是必要的):

coords <- cbind(x = c(5,6,4,1,1),y = c(0,4,5,5,0))
a <- numeric()
for (i in 1:dim(coords)[1]){
  #print(i)
  q <- i + 1
  if (i == (dim(coords)[1])) q <- 1
  out <- ((coords[q,1]) - (coords[i,1])) * ((coords[q,2]) + (coords[i,2]))
  a[q] <- out
  rm(q,out)
} #end i loop

rm(i)

a <- sum(a) #-ve is anti-clockwise

b <- cbind(x = rev(coords[,1]), y = rev(coords[,2]))

if (a>0) coords <- b #reverses coords if polygon not traced in anti-clockwise direction
于 2018-06-29T04:25:19.140 回答
0

这是基于上述答案的 swift 3.0 解决方案:

    for (i, point) in allPoints.enumerated() {
        let nextPoint = i == allPoints.count - 1 ? allPoints[0] : allPoints[i+1]
        signedArea += (point.x * nextPoint.y - nextPoint.x * point.y)
    }

    let clockwise  = signedArea < 0
于 2018-02-28T17:26:08.963 回答
0

虽然这些答案是正确的,但它们在数学上的强度超过了必要的程度。假设地图坐标,最北点是地图上的最高点。找到最北的点,如果 2 个点并列,则它是最北的,然后是最东的(这是 lhf 在他的答案中使用的点)。在你的观点中,

点[0] = (5,0)

点[1] = (6,4)

点[2] = (4,5)

点[3] = (1,5)

点[4] = (1,0)

如果我们假设 P2 是最北的,那么前一个点或下一个点的东点将确定顺时针、顺时针或逆时针。由于最北点在北面上,如果 P1(前一个)到 P2 向东移动,则方向为 CW。在这种情况下,它向西移动,因此方向是 CCW,正如公认的答案所说。如果前一个点没有水平移动,那么同样的系统适用于下一个点 P3。如果 P3 在 P2 的西边,是的,那么运动是逆时针方向的。如果 P2 到 P3 的运动是东,在这种情况下是西,运动是 CW。假设您的数据中的 nte,P2 是最北的然后是东的点,prv 是前一个点,P1 在您的数据中,nxt 是下一个点,P3 在您的数据中,并且 [0] 是水平或东/西,其中西小于东,[1] 是垂直的。

if (nte[0] >= prv[0] && nxt[0] >= nte[0]) return(CW);
if (nte[0] <= prv[0] && nxt[0] <= nte[0]) return(CCW);
// Okay, it's not easy-peasy, so now, do the math
if (nte[0] * nxt[1] - nte[1] * nxt[0] - prv[0] * (nxt[1] - crt[1]) + prv[1] * (nxt[0] - nte[0]) >= 0) return(CCW); // For quadrant 3 return(CW)
return(CW) // For quadrant 3 return (CCW)
于 2019-02-03T11:18:31.533 回答
0

这是一个基于此答案的简单 Python 3 实现(反过来,它基于接受的答案中提出的解决方案

def is_clockwise(points):
    # points is your list (or array) of 2d points.
    assert len(points) > 0
    s = 0.0
    for p1, p2 in zip(points, points[1:] + [points[0]]):
        s += (p2[0] - p1[0]) * (p2[1] + p1[1])
    return s > 0.0
于 2020-05-24T19:41:36.583 回答
-4

找到这些点的质心。

假设从这一点到你的点有线。

找到 line0 line1 的两条线之间的角度

比为 line1 和 line2 做

...

...

如果这个角度比逆时针单调增加,

否则,如果单调递减,则顺时针

否则(它不是单调的)

你不能决定,所以这不明智

于 2009-07-22T14:38:14.033 回答