python - 沿某个轴为 2D 多边形添加每个像素的点
问题描述
假设我有一个由二维点列表表示的开放多边形。例如,某种没有基础的三角形多边形的表示将是:
import numpy as np
polygon_arr = np.array([[0,0], [15,10], [2,4]])
我正在寻找一种优雅的方式来丰富表示,即将点添加到polygon_arr使得多边形本身不会改变,但是对于每个 y 值(在多边形的范围内),polygon_arr中都会有一个匹配点.
例子:
simple_line_polygon = np.array([[0,0], [10,5]])
enriched_representation = foo(simple_line_polygon)
# foo() should return: np.array([[0,0], [2,1], [4,2], [6,3], [8,4], [10,5]])
我考虑考虑多边形中的每两个相邻点,构造一个线方程(y = mx + n)并为范围内的每个y采样;然后处理特殊情况,例如两个点是垂直的(因此未定义线方程)以及点已经彼此接近而不是 y 值变化一个像素的情况。然而,这不是那么优雅,并且会欣赏更好的想法。
解决方案
这里不需要线方程。您可以分别缩放点之间的 x 和 y 距离。如果点之间应该有最小距离,您可以通过计算角之间的欧几里得距离来检查。这是一个小功能,希望能满足您的需求:
import numpy as np
def enrich_polygon(polygon, maxpoints = 5, mindist=1):
result = []
##looping over all lines of the polygon:
for start, end in zip(polygon, np.vstack([polygon[1:],polygon[:1]])):
dist = np.sqrt(np.sum((start-end)**2)) ##distance between points
N = int(min(maxpoints+1,dist/mindist)) ##amount of sub-sections
if N < 2: ##mindist already reached
result += [start]
##generating the new points:
##put all points (including original start) on the line into results
else:
result += [
start+i*(end-start)/(N-1) for i in range(N-1)
]
return np.array(result)
polygon_arr = np.array([[0,0], [15,10], [2,4]])
res = enrich_polygon(polygon_arr)
print(res)
该函数采用原始多边形并迭代成对的相邻角点。如果两个角之间的距离大于mindist
,则新点将被添加到 maxpoints (每行要添加的最大点数)。对于给定的示例,结果如下所示:
[[ 0. 0. ]
[ 3. 2. ]
[ 6. 4. ]
[ 9. 6. ]
[12. 8. ]
[15. 10. ]
[12.4 8.8 ]
[ 9.8 7.6 ]
[ 7.2 6.4 ]
[ 4.6 5.2 ]
[ 2. 4. ]
[ 1.33333333 2.66666667]
[ 0.66666667 1.33333333]]
推荐阅读
- python - 如何使用 selenium,python 按索引单击通过 xpath 找到的所有元素
- java - Android:如何在句末使用句点将字符串分成单独的行
- c++ - 如何检查函数参数中的变量是否与 C++ 中函数外部的变量匹配?
- php - UTF-16 到 UTF-8 PHP 转换
- java - 获取 URL 中倒数第二个斜杠后的字母
- c++ - 如何返回 COM 接口?
- java - 有没有办法阻止客户端从实例调用静态方法?
- javascript - formSubmit - TypeError:无法读取未定义的属性“公司” - 应用脚本 - 编程新手
- python - 如何使用字典中每个键的第一个值有效地创建优先级队列
- amazon-web-services - terraform 错误:模块参数的值无效