79

I have a set of points and would like to know if there is a function (for the sake of convenience and probably speed) that can calculate the area enclosed by a set of points.

for example:

x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)

points = zip(x,y)

given points the area should be approximately equal to (pi-2)/4. Maybe there is something from scipy, matplotlib, numpy, shapely, etc. to do this? I won't be encountering any negative values for either the x or y coordinates... and they will be polygons without any defined function.

EDIT:

points will most likely not be in any specified order (clockwise or counterclockwise) and may be quite complex as they are a set of utm coordinates from a shapefile under a set of boundaries

pbreach
  • 16,049
  • 27
  • 82
  • 120

13 Answers13

149

Implementation of Shoelace formula could be done in Numpy. Assuming these vertices:

import numpy as np
x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)

We can redefine the function in numpy to find the area:

def PolyArea(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

And getting results:

print PolyArea(x,y)
# 0.26353377782163534

Avoiding for loop makes this function ~50X faster than PolygonArea:

%timeit PolyArea(x,y)
# 10000 loops, best of 3: 42 µs per loop
%timeit PolygonArea(zip(x,y))
# 100 loops, best of 3: 2.09 ms per loop.

Timing is done in Jupyter notebook.

Mahdi
  • 3,188
  • 2
  • 20
  • 33
  • 2
    Great solution. I'm not sure why, but the "top" answer by @Nikos Athanasiou does not work when some of the coordinates are negative. Also another solution listed [here](http://stackoverflow.com/questions/451426/how-do-i-calculate-the-surface-area-of-a-2d-polygon) had that issue. Your solution is the only one that worked. Just check with `xxx = np.array([[-100,0],[100,0],[100,150],[-100,150],[-100,0]])` – user989762 Jun 19 '15 at 07:48
  • 3
    @user989762: But I am getting the same answer using both methods! – Mahdi Jun 20 '15 at 06:04
  • 10
    rookie mistake: not providing the points in an ordered (clockwise/counter clockwise) manner would yield faulty results. – emredog Jul 25 '18 at 12:55
  • Can you explain how you used the dot product instead of the cross product as the shoelace forumla states? – pstatix Dec 13 '19 at 19:08
  • 1
    @pstatix: Indeed the shoelace formula can be written in terms of the exterior product but you can expand the product, and you'll see there are two types of terms: positive terms and negative terms. If you separate them into two terms, you'd see they are the product of x and y then you can write those x's and y's as two vectors with a dot product between them. Look at the `proof for a triangle` section here: https://en.wikipedia.org/wiki/Shoelace_formula – Mahdi Dec 14 '19 at 20:57
57

The most optimized solution that covers all possible cases, would be to use a geometry package, like shapely, scikit-geometry or pygeos. All of them use C++ geometry packages under the hood. The first one is easy to install via pip:

pip install shapely

and simple to use:

from shapely.geometry import Polygon
pgon = Polygon(zip(x, y)) # Assuming the OP's x,y coordinates

print(pgon.area)

To build it from scratch or understand how the underlying algorithm works, check the shoelace formula:

# e.g. corners = [(2.0, 1.0), (4.0, 5.0), (7.0, 8.0)]
def Area(corners):
    n = len(corners) # of corners
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

Since this works for simple polygons:

  • If you have a polygon with holes : Calculate the area of the outer ring and subtrack the areas of the inner rings

  • If you have self-intersecting rings : You have to decompose them into simple sectors

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153
  • Mine might be very complex polygons. The points are utm coordinates selected from a shapefile under a set of boundaries – pbreach Jun 28 '14 at 15:01
  • 3
    @user2593236: So long as your polygon boundary doesn't cross itself (which is what "simple" means in this context), you should be fine. – Mark Dickinson Jun 28 '14 at 15:05
  • 3
    @user2593236 [Simple](http://en.wikipedia.org/wiki/Simple_polygon) means concave or convex without holes or self intersections. – Nikos Athanasiou Jun 28 '14 at 15:05
  • 1
    I tried with very simple coordinates `[(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]` and it gave 0.0 area. Are there any limitations that you know? Also tried to shift it out of the origin, getting the same result. – diegopso Apr 06 '17 at 20:53
  • 1
    @diegopso seems that it works only if the points are in a series of drawing. So it will work for `[(0, 0), (0, 1), (1, 1), (1, 0)]` – Pithikos Mar 13 '19 at 21:39
19

By analysis of Mahdi's answer, I concluded that the majority of time was spent doing np.roll(). By removing the need of the roll, and still using numpy, I got the execution time down to 4-5µs per loop compared to Mahdi's 41µs (for comparison Mahdi's function took an average of 37µs on my machine).

def polygon_area(x,y):
    correction = x[-1] * y[0] - y[-1]* x[0]
    main_area = np.dot(x[:-1], y[1:]) - np.dot(y[:-1], x[1:])
    return 0.5*np.abs(main_area + correction)

By calculating the correctional term, and then slicing the arrays, there is no need to roll or create a new array.

Benchmarks:

10000 iterations
PolyArea(x,y): 37.075µs per loop
polygon_area(x,y): 4.665µs per loop

Timing was done using the time module and time.clock()

maxb
  • 625
  • 6
  • 15
  • I get a difference between this approach and the one of Mahdi when I define `x` and `y` such as `x_{n+1} = x_1 and x_0 = x_n, as well as y_{n+1} = y_1 and y_0 = y_n` as required to apply the shoelace formula (see https://en.wikipedia.org/wiki/Shoelace_formula#Definition) The difference is slight because the points are the vertices are so close to each other but exists and may be magnified when working with polygons with longer sides. – Eskapp Sep 27 '18 at 16:23
  • Of course there are floating point errors, as with any implementation. Could you provide a full example of the difference? If you need more precision, you could use arbitrary precision arithmetics. – maxb Sep 27 '18 at 16:45
  • 1
    My bad, I was confused about the correction term and thought that some difference I could observe could come from there while tracking a bug in my code. Seems to work perfectly after many more tests comparing different implementations for computing the area of polygons. Your solution has the speed advantage as well as being easy to read! – Eskapp Sep 27 '18 at 17:54
  • @Eskapp glad to hear everything is working correctly! – maxb Sep 27 '18 at 19:52
  • Can you explain how the dot product is used instead of cross products? – pstatix Dec 13 '19 at 18:42
  • 1
    @pstatix if you look at the Wikipedia article for the [Shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula#Statement), it can be visualized as a shifted dot product. I didn't come up with the formula myself, but I did realize that the pattern of calculation used directly matched using the dot product (or rather two dot products), with one vector in each product shifted around. For more info I'd just read the article, the only thing I did for this answer was to improve the performance of the algorithm. – maxb Dec 14 '19 at 21:19
13

maxb's answer gives good performance but can easily lead to loss of precision when coordinate values or the number of points are large. This can be mitigated with a simple coordinate shift:

def polygon_area(x,y):
    # coordinate shift
    x_ = x - x.mean()
    y_ = y - y.mean()
    # everything else is the same as maxb's code
    correction = x_[-1] * y_[0] - y_[-1]* x_[0]
    main_area = np.dot(x_[:-1], y_[1:]) - np.dot(y_[:-1], x_[1:])
    return 0.5*np.abs(main_area + correction)

For example, a common geographic reference system is UTM, which might have (x,y) coordinates of (488685.984, 7133035.984). The product of those two values is 3485814708748.448. You can see that this single product is already at the edge of precision (it has the same number of decimal places as the inputs). Adding just a few of these products, let alone thousands, will result in loss of precision.

A simple way to mitigate this is to shift the polygon from large positive coordinates to something closer to (0,0), for example by subtracting the centroid as in the code above. This helps in two ways:

  1. It eliminates a factor of x.mean() * y.mean() from each product
  2. It produces a mix of positive and negative values within each dot product, which will largely cancel.

The coordinate shift does not alter the total area, it just makes the calculation more numerically stable.

Trenton
  • 331
  • 3
  • 4
  • The only solution that offered the correct result! Kudos! See my answer for an slightly modified version that takes a list of tuples. – HumbleBee Oct 20 '20 at 10:46
5

There's an error in the code above as it doesn't take absolute values on each iteration. The above code will always return zero. (Mathematically, it's the difference between taking signed area or wedge product and the actual area http://en.wikipedia.org/wiki/Exterior_algebra.) Here's some alternate code.

def area(vertices):
    n = len(vertices) # of corners
    a = 0.0
    for i in range(n):
        j = (i + 1) % n
        a += abs(vertices[i][0] * vertices[j][1]-vertices[j][0] * vertices[i][1])
    result = a / 2.0
    return result
Chris Judge
  • 151
  • 1
  • 2
5

It's faster to use shapely.geometry.Polygon rather than to calculate yourself.

from shapely.geometry import Polygon
import numpy as np
def PolyArea(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
coords = np.random.rand(6, 2)
x, y = coords[:, 0], coords[:, 1]

With those codes, and do %timeit

%timeit PolyArea(x,y)
46.4 µs ± 2.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit Polygon(coords).area
20.2 µs ± 414 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
C.K.
  • 1,409
  • 10
  • 20
4

a bit late here, but have you considered simply using sympy?

a simple code is :

from sympy import Polygon
a = Polygon((0, 0), (2, 0), (2, 2), (0, 2)).area
print(a)
Alex Jiang
  • 41
  • 2
4

cv2.contourArea() in OpenCV gives an alternative method.

example:

points = np.array([[0,0],[10,0],[10,10],[0,10]])
area = cv2.contourArea(points)
print(area) # 100.0

The argument (points, in the above example) is a numpy array with dtype int, representing the vertices of a polygon: [[x1,y1],[x2,y2], ...]

Toru Kikuchi
  • 332
  • 4
  • 4
3

I compared every solutions offered here to Shapely's area method result, they had the right integer part but the decimal numbers differed. Only @Trenton's solution provided the the correct result.

Now improving on @Trenton's answer to process coordinates as a list of tuples, I came up with the following:

import numpy as np

def polygon_area(coords):
    # get x and y in vectors
    x = [point[0] for point in coords]
    y = [point[1] for point in coords]
    # shift coordinates
    x_ = x - np.mean(x)
    y_ = y - np.mean(y)
    # calculate area
    correction = x_[-1] * y_[0] - y_[-1] * x_[0]
    main_area = np.dot(x_[:-1], y_[1:]) - np.dot(y_[:-1], x_[1:])
    return 0.5 * np.abs(main_area + correction)

#### Example output
coords = [(385495.19520441635, 6466826.196947694), (385496.1951836388, 6466826.196947694), (385496.1951836388, 6466825.196929455), (385495.19520441635, 6466825.196929455), (385495.19520441635, 6466826.196947694)]

Shapely's area method:  0.9999974610685296
@Trenton's area method: 0.9999974610685296
HumbleBee
  • 1,212
  • 13
  • 20
0

This is much simpler, for regular polygons:

import math

def area_polygon(n, s):
    return 0.25 * n * s**2 / math.tan(math.pi/n)

since the formula is ¼ n s2 / tan(π/n). Given the number of sides, n, and the length of each side, s

DrSocket
  • 135
  • 1
  • 11
  • Interesting. Seems like this would be fast and easy to jit compile with numba. Do you have a reference for this? – pbreach Jan 21 '16 at 17:56
  • # Given the number of sides, n, and the length of each side, s, the polygon's area is # 1/4 n s2 / tan( pi/n) Interactive Python (Rice University, Coursera) again here: Area of a Polygon (http://www.academia.edu/5179705/Exercise_1_How_to_design_programs) I did the function from that... – DrSocket Jan 22 '16 at 09:12
  • 4
    This is for a *regular* polygon which is a special but very limited case of this problem. All sides must be the same length (which would need to be calculated as well). If you explained what `n` and `s` are then maybe it would be more apparent... – pbreach Jan 22 '16 at 16:56
0

Based on

https://www.mathsisfun.com/geometry/area-irregular-polygons.html

def _area_(coords):
    t=0
    for count in range(len(coords)-1):
        y = coords[count+1][1] + coords[count][1]
        x = coords[count+1][0] - coords[count][0]
        z = y * x
        t += z
    return abs(t/2.0)

a=[(5.09,5.8), (1.68,4.9), (1.48,1.38), (4.76,0.1), (7.0,2.83), (5.09,5.8)]
print _area_(a)

The trick is that the first coordinate should also be last.

  • It gave wrong result when I tried more complex area with 15 vertices. – Edip Ahmet Jun 17 '19 at 08:06
  • can you please provide the coordinates? – Takis Tsiberis Jun 18 '19 at 11:21
  • Sorry it is my fault. I tested your code a few times and compared the results with CAD software, I tested coords=[(1141.784,893.124), (1521.933,893.124), (1521.933,999.127), (1989.809,999.127), (1989.809,622.633), (2125.054,622.633), (2125.054,326.556), (1372.067,326.556), (1372.067,-60.903), (1872.84,-60.903), (1872.84,52.41), (2015.396,52.41), (2015.396,-455.673), (1090.611,-455.673), (1086.955,436.214), (1141.784,893.124)] Yesterday I got wrong result maybe I missed something, today it works great like PolygonArea function. – Edip Ahmet Jun 18 '19 at 12:14
  • I think I comment it by mistake, maybe I tried another function here yesterday. – Edip Ahmet Jun 18 '19 at 12:17
  • 1
    Glad I could help – Takis Tsiberis Jun 19 '19 at 15:25
0
def find_int_coordinates(n: int, coords: list[list[int]]) -> float:
    rez = 0
    x, y = coords[n - 1]
    for coord in coords:
        rez += (x + coord[0]) * (y - coord[1])
        x, y = coord
    return abs(rez / 2)
Ali
  • 11
  • 5
0

Shoelace formula comes from computing internal triangles based on consecutive points around the polygon. It could be more informative to base the code on this explanation. The area of polygon is simply length of cross product (determinant) of its two neighboring vectors divided by two, all added up,

https://youtu.be/0KjG8Pg6LGk?t=213

import numpy as np, numpy.linalg as lin

def area(pts):
    ps = np.array([0.5 * lin.det(np.vstack((pts[i], pts[i+1]))) for i in range(len(pts)-1)])
    s = np.sum(ps)
    p1,p2 = pts[-1],pts[0] # cycle back, last pt with the first 
    s += 0.5 * lin.det(np.vstack((p1,p2)))
    return np.abs(s)

points = np.array([[0,0],[10,0],[10,10],[0,10]])
area(points) # 100
BBSysDyn
  • 4,389
  • 8
  • 48
  • 63