使用 numpy、matplotlib 检查坐标是否重叠

问题描述

我需要检查一个正方形是否与定义的多边形重叠

是的,使用以下 shapely 可以轻松完成

from shapely.geometry.polygon import polygon
from shapely.geometry import Box
minx,miny,maxx,maxy=0,1,1
b = Box(minx,maxy)
polygon = polygon([(230,478),(500,(432,154),(308,154)])
print(polygon.contains(b))

是否有使用 NumPy、matplotlib 实现相同结果的替代方法
仅供参考:shapely 未被批准使用

解决方法

您(几乎)可以通过几个步骤来做到这一点。这个可运行的代码显示了所有步骤和结果图。

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

vts = np.array([(230,478),(500,(432,154),(308,154)])
pgon = patches.Polygon(vts,color="blue",alpha=0.5)

# 2 points defining a box
point1 = (300,357)  # upper-right point: (xmax,ymax)
point2 = (250,250)  # lower-left point:  (xmin,ymin)

# plot the polygon patch
fig,ax = plt.subplots()
ax.add_patch(pgon)

# check if the 2 points are inside the polygon patch?
pts_inside = pgon.contains_points(ax.transData.transform([point1,point2]))

print(pts_inside) # get [ True False] output

# plot points
ax.scatter(point1[0],point1[1],color="red",zorder=6)   # point1 inside
ax.scatter(point2[0],point2[1],color="green",zorder=6) # point2 outside

plt.show()

pointsinpgon

从上面的代码,你得到

pts_inside

包含 vaues: [True,False]。这意味着只有点 1 在多边形内。如果得到 [True,True],则两个点都在多边形内,但由点定义的矩形框可能不在。