Title: Calculate the area of a polygon in Python
When you run this program, left-click to draw a polyline. Right-click to close the first and last points to form the polygon. The program will then calculate and display the polygon's signed area and its area. The signed area will be positive if the polygon's points are oriented counterclockwise; it will be negative if the points are oriented clockwise.
Calculating Areas
You can calculate the area of a polygon by adding the areas of the trapezoids defined by the polygon's edges dropped to the X-axis. If two adjacent points along the polygon's edges have coordinates (x1, y1) and (x2, y2) as shown in the picture on the right, then the area (shown in blue) of that side's trapezoid is given by:
area = (x2 - x1) * (y2 + y1) / 2
When the program adds up all of the trapezoid areas, the sides on the polygon's bottom give negative areas because x1 > x2. Those areas cancel out the parts of the other trapezoids that lie outside of the polygon as shown in the picture below.
This method gives strange results for self-intersecting polygons because some areas are counted multiple times. The method does work if the polygon intersects the X axis or if you use the Y axis instead of the X axis.
Building the Function
The following code shows a Python implementation of this calculation.
def signed_polygon_area(points):
'''Return the polygon's signed area in square units.'''
# The value will be negative if the polygon is oriented clockwise.
# Calculate and add the areas.
num_points = len(points)
area = 0
for i in range(num_points):
j = (i + 1) % num_points
area += \
(points[j][0] - points[i][0]) * \
(points[j][1] + points[i][1]) / 2;
return area
This function loops through the polygon's points. For each point, it finds the following point, uses the equation shown earlier to calculate the corresponding trapezoid's area, and adds the area to the running total area. After it adds all of the trapezoid areas, the code returns the result, which is the polygon's signed area.
Because the sign of the result depends on whether the points are arranged clockwise or counterclockwise, you can use this function to determine the polygon's orientation.
The following function returns what we normally think of as the polygon's area.
def polygon_area(points):
'''Return the polygon's area in square units.'''
# Return the absolute value of the signed area.
return abs(signed_polygon_area(points))
This function simply calls signed_polygon_area and returns the absolute value of the polygon's signed area.
Conclusion
The area function is fairly simple, as long as you know how to calculate the area of a polygon. Download the example to experiment with it and to see additional details.
|