开发者

How to detect inner polygons from a multipolygon shapely object?

I would like to detect inner polygons from a multipolygon shapely object. Great lakes, Black Sea and Caspian sea should be inner polygons and not be filled.

How to do this properly with shapefile ?

How to detect inner polygons from a multipolygon shapely object?

Please find the script bellow for investigating.

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from shapely import geometry
import random
import pickle

! wget -nc https://thredds-su.ipsl.fr/thredds/fileServer/ipsl_thredds/brocksce/tmp/polys.pickle

with open('./polys.pickle', "rb") as poly_file:
    polygons = pickle.load(poly_file)

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.Robinson(10))

transform = ccrs.Geodetic()

for polygon in polygons.geoms:
    random_color = "#"+''.join([random.choice('0123456789ABCDEF') for i in range(6)])
    x = polygon.exterior.coords.xy[0]
    y = polygon.exterior.coords.xy[1]
    ax.fill(开发者_StackOverflowx, y, transform=transform, color=random_color, lw=0.5, edgecolor="black")

ax.set_global()
ax.gridlines()
plt.show()


One way to detect inner polygons in a multipolygon shapefile is:

  1. Load the multipolygon shapefile using the GeoPandas library.
  2. Use the unary_union method to combine the polygons into a single multipolygon object.
  3. Use the difference method to find the inner polygons by subtracting the outer polygons from the multipolygon object.
  4. Use the type method to check if the resulting object is a multipolygon, and if so, iterate over the individual polygons and process them as needed.

Here's an example of how this could be implemented:

import geopandas as gpd
from shapely.geometry import MultiPolygon, Polygon

# Load the multipolygon shapefile using GeoPandas
gdf = gpd.read_file('multipolygon.shp')

# Use the unary_union method to combine the polygons into a single multipolygon object
multipoly = gdf.unary_union

# Use the difference method to find the inner polygons
inner_polygons = multipoly.difference(gdf.geometry[0])

# Check if the resulting object is a multipolygon, and if so, iterate over the individual polygons
if isinstance(inner_polygons, MultiPolygon):
    for polygon in inner_polygons:
        # Process the inner polygons as needed
        #...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜