numpy meshgrid to Shapely polygons

北战南征 提交于 2020-07-29 03:45:49

问题


I'm trying to create a numpy meshgrid and convert it to Shapely polygons. I can likely solve this with a very brute force method but it feels like there has to be a good trick to accomplish this but I haven't come up with it, yet.

This gets me the grid of points (assumed running in Jupyter) -

import numpy as np
from matplotlib import pyplot

fig = pyplot.figure(figsize=(10, 10))
ax = fig.add_subplot(111, aspect='equal')

x,y = np.mgrid[-5:-1:8j, 1:5:8j]
ax.plot(x,y, 'o', color='#000000')
pyplot.show()

Now the need is to connect all of these points horizontally and vertically to form Shapely polygons. My first attempt at this was to generate a Shapely MultiLineString to draw vertical and horizontal lines and then perform a polygonize operation on it. This resulted in only the main outer polygon being created - this is due to the MultiLineString only containing vertices on the outer polygon.

I know this might be more reasonable using rasters and GDAL but my circumstances require the end result to be Shapely polygons.

Any help tracking down a solution is appreciated!


回答1:


You basically have to define every line before you construct the MultiLineString.

import numpy as np
from shapely.geometry import MultiLineString
from shapely.ops import polygonize

x = np.linspace(-5, -1, 8)
y = np.linspace(1, 5, 8)

hlines = [((x1, yi), (x2, yi)) for x1, x2 in zip(x[:-1], x[1:]) for yi in y]
vlines = [((xi, y1), (xi, y2)) for y1, y2 in zip(y[:-1], y[1:]) for xi in x]

grids = list(polygonize(MultiLineString(hlines + vlines)))


来源:https://stackoverflow.com/questions/37041377/numpy-meshgrid-to-shapely-polygons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!