如何使用Shapely谓词区分两类LinearRing几何图形
问题描述
项目中有两类LinearRing场景:
- 场景1:红色与蓝色LinearRing无重叠(指围成的区域无重叠)
- 场景2:红色与蓝色LinearRing存在重叠(指围成的区域有重叠)
尝试了Shapely多种谓词测试,无法区分这两类场景,测试代码及结果如下:
from shapely import LinearRing # 场景1:区域无重叠 blue_sq = LinearRing([(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]) red_one = LinearRing([(0, 0), (0, 3), (3, 3), (3, 2), (1, 2), (1, 0), (0, 0)]) print(blue_sq.overlaps(red_one)) print(blue_sq.intersects(red_one)) print(blue_sq.crosses(red_one)) print(blue_sq.contains(red_one)) print(blue_sq.touches(red_one)) print(blue_sq.within(red_one)) # 场景2:区域有重叠 blue_ln = LinearRing([(2, 1), (2, 2), (7, 2), (7, 1), (2, 1)]) red_two = LinearRing([(1, 0), (1, 1), (2, 1), (2, 2), (3, 2), (3, 0), (1, 0)]) print(blue_ln.overlaps(red_two)) print(blue_ln.intersects(red_two)) print(blue_ln.crosses(red_two)) print(blue_ln.contains(red_two)) print(blue_ln.touches(red_two)) print(blue_ln.within(red_two))
测试结果汇总
| Shapely谓词 | 场景1 | 场景2 |
|---|---|---|
| overlaps | True | True |
| intersects | True | True |
| crosses | False | False |
| contains | False | False |
| touches | False | False |
| within | False | False |
两类场景均返回intersects和overlaps为True,其余谓词均为False,无法区分区域是否重叠。
解决方案
问题核心在于:LinearRing是线环(闭合线串),Shapely的谓词判断的是线要素的空间关系,而非线环围成的多边形区域。你需要将LinearRing转换为Polygon,再通过区域相关逻辑区分:
方法1:计算多边形交集面积
如果两个Polygon的交集面积大于0,说明区域存在重叠;否则无重叠:
from shapely import LinearRing, Polygon # 场景1处理 blue_poly1 = Polygon(blue_sq) red_poly1 = Polygon(red_one) print("场景1区域是否重叠:", blue_poly1.intersection(red_poly1).area > 0) # 输出False # 场景2处理 blue_poly2 = Polygon(blue_ln) red_poly2 = Polygon(red_two) print("场景2区域是否重叠:", blue_poly2.intersection(red_poly2).area > 0) # 输出True
方法2:使用Polygon的overlaps谓词
Polygon的overlaps谓词定义为:两个区域有交集但互不包含,刚好匹配你的场景:
- 场景1中蓝色多边形完全在红色多边形内部,
overlaps返回False - 场景2中两个多边形部分重叠,
overlaps返回True
print("场景1区域overlaps:", blue_poly1.overlaps(red_poly1)) # False print("场景2区域overlaps:", blue_poly2.overlaps(red_poly2)) # True
关键原因说明
场景1中,蓝色LinearRing的边与红色LinearRing的边存在重合段,所以线要素层面的overlaps返回True,但围成的多边形区域是蓝色完全在红色内部,无区域重叠;场景2中,线要素和区域都存在重叠,因此原线要素谓词无法区分两类场景。
内容的提问来源于stack exchange,提问作者snow6oy
相关产品推荐
相关产品推荐

