【问题标题】:Convert SVG path to polygon with specific number of points python将SVG路径转换为具有特定点数python的多边形
【发布时间】:2021-12-30 11:23:59
【问题描述】:

我想复制Link 中显示的效果,即从 svg 路径中​​迭代生成具有越来越多点的多边形。

我目前设法将 svg 路径转换为多边形,使用 svgpath2mpl 的 parse_path 和 to_polygons 函数,然后将它们转换为 Shapely 多边形。然而,使用这种方法,它会生成一个包含路径上所有点的多边形。有没有办法对多边形/路径进行采样以获得不同精度的多边形?这可以在转换为多边形之前或之后完成。

这是我目前拥有的:

from svgpath2mpl import parse_path
mpl_path = parse_path('M12.302 798.100 c0.300 ...')
coordinates = mpl_path.to_polygons()

from shapely.geometry import Polygon
poly = Polygon(coordinates[0])

我还在使用 shapely 转换之前和之后生成了 matplotlibs 图,它们给出了 identical results,而这是原始路径 itself。 svg 路径的绘图是使用this 在线工具生成的。

【问题讨论】:

  • 您好!您能否发布一个指向您用作输入的 SVG 的链接?

标签: python svg polygon shapes shapely


【解决方案1】:

下面的函数应该可以工作:

def sample_polygon(polygon, n_points):
    '''
    Generates a new shapely Polygon with a specific number of points sampled 
    from the original input.

    Parameters
    ----------
    polygon : shapely.geometry.Polygon
        The input polygon from which the points will be sampled
    n_points : integer
        The number of points to sample

    Returns
    -------
    sampled_poly : shapely.geometry.Polygon
        Newly-generated polygon. It will have as many points as the `n_points` 
        variable demands.

    '''
    # Sampling the coordinates
    sample_coords = [polygon
                     .exterior
                     .interpolate(i/n_points, 
                                  normalized=True) for i in range(n_points)]
    
    # Generating a new polygon
    sampled_poly = shapely.geometry.Polygon(sample_coords)
    
    return sampled_poly 
    

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 2012-11-07
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多