简体   繁体   English

numpy meshgrid到Shapely多边形

[英]numpy meshgrid to Shapely polygons

I'm trying to create a numpy meshgrid and convert it to Shapely polygons. 我正在尝试创建一个numpy meshgrid并将其转换为Shapely多边形。 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) - 这让我获得了积分(假设在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. 现在需要水平和垂直连接所有这些点以形成Shapely多边形。 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. 我对此的第一次尝试是生成一个Shapely MultiLineString来绘制垂直和水平线,然后对其执行多边形操作。 This resulted in only the main outer polygon being created - this is due to the MultiLineString only containing vertices on the outer polygon. 这导致仅创建主外部多边形 - 这是由于MultiLineString仅包含外部多边形上的顶点。

I know this might be more reasonable using rasters and GDAL but my circumstances require the end result to be Shapely polygons. 我知道使用栅格和GDAL可能更合理,但我的情况要求最终结果是Shapely多边形。

Any help tracking down a solution is appreciated! 任何帮助追踪解决方案的人都表示赞赏!

You basically have to define every line before you construct the MultiLineString. 在构造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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM