2016-11-09 205 views
2

我使用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

你可以简单地做 -

insideRegion = insideOuter & ~insideInner 
+0

超好听,非常感谢!我认为,对于更一般的情况,第一个建议更安全:“False - True = -1”,但“False&〜True = 0”。 – mtgoncalves

+0

@mtgoncalves好点!删除了那个。 – Divakar