python - Find holes in a union of rectangles? -
i have number of random rectangles (black) in , around unit square (red) , need extract polygonal regions inside unit square not covered rectangle.

it looks can done shapely , i've gotten point when have union of rectangles (green) i'm not sure how subtract unit square , retrieve list of polygons.
here code generate test data:
import pylab import random matplotlib import pyplot shapely.geometry import point, polygon shapely.ops import cascaded_union 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) 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 = [] 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()
basically, want take difference of "unioned" polygons large square , polygonize result individual, separate polygons. example:
#-- region not covered individual squares. uncovered_region = polygon(bigsquare).difference(union) # in cases, result single polygon... if not isinstance(uncovered_region, multipolygon): uncovered_region = [uncovered_region] poly in polygonize(uncovered_region): patch = polygonpatch(poly, fc='purple', alpha=0.5, zorder=2) ax.add_patch(patch) as full example, based on yours:
import matplotlib.pyplot plt import random shapely.geometry import polygon, multipolygon shapely.ops import cascaded_union, polygonize 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) sx, sy in zip(dx, dy)] fig, ax = plt.subplots() bigsquare = make_square(0.5, 0.5, 1.0, 1.0) a, b = zip(*bigsquare) ax.plot(a, b, 'r-') polygons = [] 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) ax.plot(a, b, 'k-') union = cascaded_union(polygons) patch2b = polygonpatch(union, fc='#00ff00', ec='#00ff00', alpha=0.5, zorder=2) ax.add_patch(patch2b) #-- region not covered individual squares. uncovered_region = polygon(bigsquare).difference(union) # in cases, result single polygon... if not isinstance(uncovered_region, multipolygon): uncovered_region = [uncovered_region] poly in polygonize(uncovered_region): print poly patch = polygonpatch(poly, fc='purple', alpha=0.5, zorder=2) ax.add_patch(patch) plt.margins(0.05) plt.show() 
Comments
Post a Comment