如何简化shapely中的边界几何形状

10

我正在使用shapely进行地理信息系统的开发,但是当加载每个邮政编码的几何形状时,由于几何形状过于复杂和崎岖不平,导致内存错误。

我希望通过尽可能减少边界点的数量来缩小形状的内存占用,而又不会过度扭曲形状。使用凸包似乎是一个解决方案,还可以从边界中简单地丢弃很多点。我想知道是否已经有现成的方法解决这个问题。

2个回答

13

尝试使用几何图形的 简化方法, 指定公差距离。


2
我在浏览中发现了这篇旧帖子,因为我遇到了类似的问题。根据Mike T链接,我的解决方案如下:

从区域掩码生成多边形。

这里有两个区域。

import matplotlib.pyplot as plt
import shapely.geometry
import cv2
import numpy as np

# gen. mask
mask=np.zeros((600,600),dtype=bool)
mask[300:500,300:500]=True
mask[:150,30:120]=True
mask[70:120,30:220]=True
mask[100:200,200:260]=True

# get contours == polygon
contours, _ = cv2.findContours(mask.astype(np.uint8),  # cv2 requires special types
                               cv2.RETR_TREE,
                               cv2.CHAIN_APPROX_NONE)
contours = [i.reshape((-1, 2)) for i in contours]

简化多边形
def simplify(polygon, tolerance = .1):
    """ Simplify a polygon with shapely.
    Polygon: ndarray
        ndarray of the polygon positions of N points with the shape (N,2)
    tolerance: float
        the tolerance
    """
    poly = shapely.geometry.Polygon(i)
    poly_s = poly.simplify(tolerance=tolerance)
    # convert it back to numpy
    return np.array(poly_s.boundary.coords[:])

# Simplify all contours
contours_s = []
for i in contours:
    contours_s.append(simplify(i)

情节

plt.figure(figsize=(4,4))
plt.imshow(mask, label='2D mask')

for i, c_i in enumerate(contours_s):
    plt.plot(*c_i.T, '-', label=f'cv2 contours {i}')
    
for i, c_i in enumerate(contours_s):
    plt.plot(*c_i.T, 'o', label=f'shapely simplify {i}')
    
plt.legend()
plt.tight_layout()

Plot


嗨!我觉得你在“简化多边形”部分缺少了一个闭括号。这一行:contours_s.append(simplify(i)。应该是contours_s.append(simplify(i))吧? - undefined
1
嗨,Marci,谢谢你指出这个错别字并提供解决方案。我已经在帖子中修复了它。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接