Search code examples
pythonnumpymatplotlibvectorizationpoint-in-polygon

Point inside polygonal region with polygonal hole


I am using matplotlib.path.Path to check whether a set of points are inside a region bounded by polygons (polygonal region with a polygonal hole). My approach involves two checks and a loop:

import numpy as np
from matplotlib import path

# Define coordinates of the boundaries
xyOuter = np.array([[-5, -5], [5, -5], [5, 5], [-5, 5]])
xyInner = np.array([[-2, -2], [2, -2], [2, 2], [-2, 2]])

# Convert boundary coordinates to Path objects
xyOuter = path.Path(xyOuter)
xyInner = path.Path(xyInner)

# Define coordinates of the test points
xyPoints = np.linspace(-7, 7, 57)
xyPoints = np.vstack([xyPoints, xyPoints]).T

# Test whether points are inside the outer region
insideOuter = xyOuter.contains_points(xyPoints)

# Test whether points are inside the inner region
insideInner = xyInner.contains_points(xyPoints)

# Initialise boolean array for region bounded by two polygons
insideRegion = np.zeros(insideOuter.shape, dtype=bool)

# Flip False to True if point is inside the outer region AND outside the inner region
for i in range(len(insideRegion)):
    if insideOuter[i] == True:
        if insideInner[i] == False:
            insideRegion[i] = True

# Print results
for o, i, r in zip(insideOuter, insideInner, insideRegion):
    print o, i, r

Is there a faster approach which does not involve a for-loop?


Solution

  • You could simply do -

    insideRegion = insideOuter & ~insideInner