我在单位正方形(红色)中和周围有许多随机矩形(黑色),需要提取单位正方形内未被任何矩形覆盖的所有多边形区域。
看起来这可以用 Shapely 完成,当我有矩形的联合(绿色)时,我已经到了这一点,但我不知道如何从单位正方形中减去它并检索多边形列表。
这是我生成测试数据的代码:
import pylab
import random
from matplotlib import pyplot
from shapely.geometry import Point, Polygon
from shapely.ops import cascaded_union
from descartes import PolygonPatch
def make_square(x, y, size1, size2):
dx = [size1, -size1, -size1, size1, size1]
dy = [size2, size2, -size2, -size2, size2]
return [(x+sx, y+sy) for sx, sy in zip(dx, dy)]
pylab.figure()
square = make_square(0.5, 0.5, 1.0, 1.0)
a, b = zip(*square)
pylab.plot(a, b, 'r-')
polygons = []
for i in xrange(10):
x = random.random()
y = random.random()
s1 = random.random()
s2 = random.random()
square = make_square(x, y, s1, s2)
polygons.append(Polygon(square))
a, b = zip(*square)
pylab.plot(a, b, 'k-')
u = cascaded_union(polygons)
patch2b = PolygonPatch(u, fc='#00ff00', ec='#00ff00', alpha=0.5, zorder=2)
pylab.gca().add_patch(patch2b)
pylab.show()