ordering shuffled points that can be joined to form a polygon (in python)

前端 未结 2 516
粉色の甜心
粉色の甜心 2020-12-08 03:28

I have a collection of points that join to form a polygon in 2D cartesian space. It is in the form of a python list of tuples

[(x1, y1), (x2, y2), ... , (xn,         


        
2条回答
  •  感动是毒
    2020-12-08 03:54

    This sorts your points according to polar coordinates:

    import math
    import matplotlib.patches as patches
    import pylab
    pp=[(-0.500000050000005, -0.5), (-0.499999950000005, 0.5), (-0.500000100000005, -1.0), (-0.49999990000000505, 1.0), (0.500000050000005, -0.5), (-1.0000000250000025, -0.5), (1.0000000250000025, -0.5), (0.499999950000005, 0.5), (-0.9999999750000024, 0.5), (0.9999999750000024, 0.5), (0.500000100000005, -1.0), (0.49999990000000505, 1.0), (-1.0, 0.0), (-0.0, -1.0), (0.0, 1.0), (1.0, 0.0), (-0.500000050000005, -0.5)]
    # compute centroid
    cent=(sum([p[0] for p in pp])/len(pp),sum([p[1] for p in pp])/len(pp))
    # sort by polar angle
    pp.sort(key=lambda p: math.atan2(p[1]-cent[1],p[0]-cent[0]))
    # plot points
    pylab.scatter([p[0] for p in pp],[p[1] for p in pp])
    # plot polyline
    pylab.gca().add_patch(patches.Polygon(pp,closed=False,fill=False))
    pylab.grid()
    pylab.show()
    

    resulting polygon

提交回复
热议问题