使用 Alpha Shape 包。这是一个示例代码:
import matplotlib.pyplot as plt
from descartes import PolygonPatch
import alphashape
import random
from shapely.geometry import Point
points = [(0., 0.), (0., 1.), (1., 1.), (1., 0.),
(0.5, 0.25), (0.5, 0.75), (0.25, 0.5), (0.75, 0.5)]
alpha_shape = alphashape.alphashape(points, 2.0) # Create the alpha shape
# Plotting the alpha shape over the input data
fig, ax = plt.subplots()
ax.scatter(*zip(*points), c='green')
ax.add_patch(PolygonPatch(alpha_shape, alpha=0.2))
N = 10 # number of random points
for i in range(N):
x = round(random.uniform(0, 1), 2)
y = round(random.uniform(0, 1), 2)
point = Point(x,y) # analysis point
if alpha_shape.contains(point) == True:
plt.scatter(x,y,c='blue')
else:
plt.scatter(x,y,c='red')
传说:
- 红色表示凹多边形外的点
- 在绿色中,顶点
- 蓝色表示凹多边形内的点