简体   繁体   中英

Area of polygon with list of (x,y) coordinates

It might seem a bit odd that I am asking for python code to calculate the area of a polygon with a list of (x,y) coordinates given that there have been solutions offered in stackoverflow in the past. However, I have found that all the solutions provided are sensitive to the order of the list of (x,y) coordinates given. For example, with the code below to find an area of a polygon:

def area(p):
    return 0.5 * abs(sum(x0*y1 - x1*y0
                             for ((x0, y0), (x1, y1)) in segments(p)))

def segments(p):
    return zip(p, p[1:] + [p[0]])


coordinates1 = [(0.5,0.5), (1.5,0.5), (0.5,1.5), (1.5,1.5)]
coordinates2 = [(0.5,0.5), (1.5,0.5), (1.5,1.5), (0.5,1.5)]

print "coordinates1", area(coordinates1)
print "coordinates2", area(coordinates2)

This returns

coordinates1 0.0
coordinates2 1.0  #This is the correct area

For the same set of coordinates but with a different order. How would I correct this in order to get the area of the non-intersecting full polygon with a list of random (x,y) coordinates that I want to make into a non-intersecting polygon?

EDIT: I realise now that there can be multiple non-intersecting polygons from a set of coodinates. Basically I am using scipy.spatial.Voronoi to create Voronoi cells and I wish to calculate the area of the cells once I've fed the coordinates to the scipy Voronoi function - unfortunately the function doesn't always output the coordinates in the order that will allow me to calculate the correct area.

Several non-intersecting polygons can be created from a random list of coordinates (depending on its order), and each polygon will have a different area, so it is essential that you specify the order of the coordinates to build the polygon (see attached picture for an example). 这两个多边形的坐标相同但面积不同

The Voronoi cells are convex, so that the polygon is unambiguously defined.

You can compute the convex hull of the points, but as there are no reflex vertices to be removed, the procedure is simpler.

1) sort the points by increasing abscissa; in case of ties, sort on ordinates (this is a lexicographical ordering);

2) consider the straight line from the first point to the last and split the point sequence in a left and a right subsequence (with respect to the line);

3) the requested polygon is the concatenation of the left subsequence and the right one, reversed.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM