我正在使用matplotlib.path.Path
来检查一组点是否在由多边形限定的区域内(具有多边形孔的多边形区域)。我的方法涉及两个检查和一个循环:
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
是否有更快的方法不涉及for循环?
答案 0 :(得分:0)
你可以这么做 -
insideRegion = insideOuter & ~insideInner