Sorting according to clockwise point coordinates

前端 未结 7 2177
别跟我提以往
别跟我提以往 2020-12-16 18:18

Given a list in Python containing 8 x, y coordinate values (all positive) of 4 points as [x1, x2, x3, x4, y1, y2, y3, y4] ((xi, yi) are x and y coo

7条回答
  •  温柔的废话
    2020-12-16 18:48

    As suggested by IgnacioVazquez-Abrams, we can also do sorting according to atan2 angles:

    Code:

    import math
    import copy
    import matplotlib.pyplot as plt
    
    a = [2, 4, 5, 1, 0.5, 4, 0, 4]
    print(a)
    
    
    def clock(a):
        angles = []
        (x0, y0) = ((a[0]+a[1]+a[2]+a[3])/4, (a[4]+ a[5] + a[6] + a[7])/4)  # centroid
        for j in range(4):
            (dx, dy) = (a[j] - x0, a[j+4] - y0)
            angles.append(math.degrees(math.atan2(float(dy), float(dx))))
        for k in range(4):
            angles.append(angles[k] + 800)
        # print(angles)
    
        z = [copy.copy(x) for (y,x) in sorted(zip(angles,a), key=lambda pair: pair[0])]
        print("z is: ", z)
    
    plt.scatter(a[:4], a[4:8])
    plt.show()
    
    clock(a)
    

    Output is :

    [2, 4, 5, 1, 0.5, 4, 0, 4]
    [-121.60750224624891, 61.92751306414704, -46.73570458892839, 136.8476102659946, 678.3924977537511, 861.9275130641471, 753.2642954110717, 936.8476102659946]
    z is:  [2, 5, 4, 1, 0.5, 0, 4, 4]
    

提交回复
热议问题