Alphashape与PolygonPatch基础示例运行报错,请教原因
问题:Alphashape官方示例运行报错的原因及解决办法
报错信息
File "/anaconda3/lib/python3.8/site-packages/descartes/patch.py", line 87, in PolygonPatch return PathPatch(PolygonPath(polygon), **kwargs) File "/anaconda3/lib/python3.8/site-packages/descartes/patch.py", line 62, in PolygonPath vertices = concatenate([ File "/anaconda3/lib/python3.8/site-packages/descartes/patch.py", line 63, in <listcomp> concatenate([asarray(t.exterior)[:, :2]] + IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed
运行代码
import numpy as np from descartes import PolygonPatch import matplotlib.pyplot as plt import alphashape points_2d = [(0., 0.), (0., 1.), (1., 1.), (1., 0.), (0.5, 0.25), (0.5, 0.75), (0.25, 0.5), (0.75, 0.5)] fig, ax = plt.subplots() ax.scatter(*zip(*points_2d)) alpha_shape = alphashape.alphashape(points_2d, 0.) ax.add_patch(PolygonPatch(alpha_shape, alpha=0.2)) plt.savefig(f"./test.png")
原因分析
这个错误的核心是descartes库与新版shapely/alphashape的兼容性问题:
- descartes是已停止维护的库,它的
PolygonPatch方法无法正确处理新版shapely返回的几何对象结构,当尝试读取几何对象的exterior属性时,得到的是0维数组,触发索引报错。 - 即使alpha=0时理论上应返回凸包多边形,但库版本不匹配会导致返回的几何对象类型或结构不符合descartes的预期。
解决办法
方法1:替换descartes,使用shapely原生绘图接口
放弃descartes,改用shapely自带的plot方法,代码修改如下:
import numpy as np import matplotlib.pyplot as plt import alphashape from shapely.plotting import plot_polygon points_2d = [(0., 0.), (0., 1.), (1., 1.), (1., 0.), (0.5, 0.25), (0.5, 0.75), (0.25, 0.5), (0.75, 0.5)] fig, ax = plt.subplots() ax.scatter(*zip(*points_2d)) alpha_shape = alphashape.alphashape(points_2d, 0.) # 使用shapely的plot_polygon绘制 plot_polygon(alpha_shape, ax=ax, alpha=0.2, facecolor='lightblue') plt.savefig("./test.png")
方法2:使用matplotlib原生Polygon类
手动提取多边形的坐标,用matplotlib的Polygon创建补丁:
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Polygon import alphashape points_2d = [(0., 0.), (0., 1.), (1., 1.), (1., 0.), (0.5, 0.25), (0.5, 0.75), (0.25, 0.5), (0.75, 0.5)] fig, ax = plt.subplots() ax.scatter(*zip(*points_2d)) alpha_shape = alphashape.alphashape(points_2d, 0.) # 提取多边形 exterior 的坐标 coords = list(alpha_shape.exterior.coords) ax.add_patch(Polygon(coords, alpha=0.2, facecolor='lightblue')) plt.savefig("./test.png")
方法3:降级到兼容的库版本
如果必须使用descartes,可以安装旧版本的shapely(2.0以下版本),因为descartes仅支持旧版shapely:
pip install shapely==1.8.5 descartes==1.1.0
内容的提问来源于stack exchange,提问作者Mik Kim
相关产品推荐
相关产品推荐

