Python - 返回给定x的多边形路径的y坐标

时间:2015-08-28 16:43:08

标签: python matplotlib polygon

我有一个不规则的多边形,其周长由笛卡尔坐标数组定义。

我正在寻找一种方法来找到x坐标的最小和最大y坐标,该坐标适用于从x-min到x-max的连续范围。

我认为这样做的一种方法是定义每个点之间的直线方程,然后应用其范围满足给定x坐标的其中两个。

有更快的方法来计算/实施吗?或者是否有一个允许我轻松完成此操作的模块?

我一直在使用matplotlib.path绘制多边形 - 也许这个类可以帮忙?

由于

2 个答案:

答案 0 :(得分:0)

这是插值的一个快速而肮脏的例子:

def y_on_line(x, pos1, pos2):
    if(x < min(pos1[0], pos2[0])) or (x > max(pos1[0], pos2[0])):
        return None
    else:
        if(pos1[0] == pos2[0]):
            return pos1[1]
        else:
            return pos1[1] + (pos2[1] - pos1[1]) * (x - pos1[0]) / (pos2[0] - pos1[0])

def min_max_y(x, array):
    miny = None
    maxy = None
    for i in range(len(array)):
        y = y_on_line(x, array[i], array[(i+1)%len(array)])
        if(y is None):
            continue
        if(y < miny) or (miny is None):
            miny = y
        if(y > maxy) or (maxy is None):
            maxy = y
    return [miny, maxy]

print min_max_y(0.5, [[0,0],[0,2],[1,1]])

output: [0.5,1.5]

请注意,如果你的多边形是凹的,那么就没有理由(x, miny) - (x,maxy)包含在其中,以防万一。

答案 1 :(得分:0)

Per @ tcaswell的建议,shapely使这相当容易。特别是,该方法是计算多边形边界与所选x位置的垂直线之间的.intersection(即重叠)。

这里要注意的一个关键点是,形状多边形是填充对象,这样计算这些多边形与线的重叠将返回多边形内部线的线段。因此,要获得垂直线与多边形边缘交叉的点,计算多边形的.boundary属性与垂直线之间的交点可能最简单。

实施

这是一个函数返回输入多边形与指定x值的垂直线的交点:

import shapely.geometry as sg

def polygon_intersect_x(poly, x_val):
    """
    Find the intersection points of a vertical line at
    x=`x_val` with the Polygon `poly`.
    """
    if x_val < poly.bounds[0] or x_val > poly.bounds[2]:
        raise ValueError('`x_val` is outside the limits of the Polygon.')
    if isinstance(poly, sg.Polygon):
        poly = poly.boundary
    vert_line = sg.LineString([[x_val, poly.bounds[1]],
                               [x_val, poly.bounds[3]]])
    pts = [pt.xy[1][0] for pt in poly.intersection(vert_line)]
    pts.sort()
    return pts

使用示例

首先创建一个示例shapely.geometry.Polygon

p = sg.Polygon([(0, 0),
                (10, 0),
                (30, 10),
                (70, -50),
                (80, 30),
                (40, 40),
                (60, 80),
                (50, 100),
                (15, 20),
                (0, 0)])

请注意,您还可以通过以下方式创建匀称的对象: a)wrapping NumPy arrays to shapely types, b)将MPL路径转换为形状多边形为p = sg.Polygon(my_path.vertices)

现在可以使用上述函数计算最小/最大交点:

x_val = 45
points = polygon_intersect_x(p, x_val)
minmax = [points[0], points[-1]]  # The values are already sorted
print minmax
# [-12.5, 88.5714286]

这是一个简单的情节,演示了这种方法:

import matplotlib.pyplot as plt

ax = plt.gca()

ax.fill(*p.boundary.xy, color='y')
ax.axvline(x_val, color='b')

ax.plot([x_val, ] * len(points), points, 'b.')
ax.plot([x_val, ] * 2, minmax, 'ro', ms=10)

Example Figure: Red dots are the 'minmax' values, blue dots are the other intersections.