【发布时间】:2018-12-09 04:50:38
【问题描述】:
我有扩展多边形的代码,它的工作原理是将 xs 和 ys 乘以一个因子,然后将生成的多边形重新居中在原始的中心。
给定多边形需要到达的点,我还有代码可以找到扩展因子的值:
import numpy as np
import itertools as IT
import copy
from shapely.geometry import LineString, Point
def getPolyCenter(points):
"""
http://stackoverflow.com/a/14115494/190597 (mgamba)
"""
area = area_of_polygon(*zip(*points))
result_x = 0
result_y = 0
N = len(points)
points = IT.cycle(points)
x1, y1 = next(points)
for i in range(N):
x0, y0 = x1, y1
x1, y1 = next(points)
cross = (x0 * y1) - (x1 * y0)
result_x += (x0 + x1) * cross
result_y += (y0 + y1) * cross
result_x /= (area * 6.0)
result_y /= (area * 6.0)
return (result_x, result_y)
def expandPoly(points, factor):
points = np.array(points, dtype=np.float64)
expandedPoly = points*factor
expandedPoly -= getPolyCenter(expandedPoly)
expandedPoly += getPolyCenter(points)
return np.array(expandedPoly, dtype=np.int64)
def distanceLine2Point(points, point):
points = np.array(points, dtype=np.float64)
point = np.array(point, dtype=np.float64)
points = LineString(points)
point = Point(point)
return points.distance(point)
def distancePolygon2Point(points, point):
distances = []
for i in range(len(points)):
if i==len(points)-1:
j = 0
else:
j = i+1
line = [points[i], points[j]]
distances.append(distanceLine2Point(line, point))
minDistance = np.min(distances)
#index = np.where(distances==minDistance)[0][0]
return minDistance
"""
Returns the distance from a point to the nearest line of the polygon,
AND the distance from where the normal to the line (to reach the point)
intersets the line to the center of the polygon.
"""
def distancePolygon2PointAndCenter(points, point):
distances = []
for i in range(len(points)):
if i==len(points)-1:
j = 0
else:
j = i+1
line = [points[i], points[j]]
distances.append(distanceLine2Point(line, point))
minDistance = np.min(distances)
i = np.where(distances==minDistance)[0][0]
if i==len(points)-1:
j = 0
else:
j = i+1
line = copy.deepcopy([points[i], points[j]])
centerDistance = distanceLine2Point(line, getPolyCenter(points))
return minDistance, centerDistance
minDistance, centerDistance = distancePolygon2PointAndCenter(points, point)
expandedPoly = expandPoly(points, 1+minDistance/centerDistance)
此代码仅在点与多边形线之一直接相对时有效。
【问题讨论】:
-
如果我正确理解了您的描述(不是您的代码),那么您通过将多边形顶点从多边形中心移开来生长多边形。根据您的标题,您希望这样做直到一个(或多个)边框达到特定点,但是您的文本描述然后说您将所有点乘以一个因子。您能解释一下为什么您认为该实现会按照您的标题所暗示的那样去做吗?
-
我们假设多边形是凸的吗?如果是这样,那么这只是一个几何问题。
-
@Mike'Pomax'Kamermans 一开始我也很困惑,但现在我想我明白了。想象一下网格上的多边形。要增加大小,请将每个点乘以一个因子,但将其设想为增加网格的粒度,使所有内容保持原样。多边形已有效增长,但使用新坐标,它可能需要平移(无论出于何种原因)。
标签: python algorithm geometry polygon computational-geometry