Testing if a Point is Inside a Polygon in Python

Finally got around to find this out by Googling.  It’s a useful function so I reproduce it here for copy & paste:

def inside_polygon(x, y, points):
    """
    Return True if a coordinate (x, y) is inside a polygon defined by
    a list of verticies [(x1, y1), (x2, x2), ... , (xN, yN)].

    Reference: http://www.ariel.com.au/a/python-point-int-poly.html
    """
    n = len(points)
    inside = False
    p1x, p1y = points[0]
    for i in range(1, n + 1):
        p2x, p2y = points[i % n]
        if y > min(p1y, p2y):
            if y <= max(p1y, p2y):
                if x <= max(p1x, p2x):
                    if p1y != p2y:
                        xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x, p1y = p2x, p2y
    return inside
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to Testing if a Point is Inside a Polygon in Python

  1. christian says:

    Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *