我发现了很多关于如何计算两点之间或从一点到多边形的距离的帖子,但是我只是找不到如何计算每个边的距离。我有一个多边形,坐标是这样的:
[[[623 284]]
[[526 256]]
[[532 189]]
[[504 166]]
[[323 175]]
[[276 219]]
[[119 221]]
[[ 1 272]]
[[ 0 473]]
[[615 479]]]我只想计算每个边的长度。也许我应该用(math.dist(p, q))和for loop什么的?
发布于 2021-08-25 10:30:28
如果点坐标存储在两个python列表x和y中,那么您可以使用以下方法计算每个边的长度:
import numpy as np
x.append(x[0])
y.append(y[0])
d = [np.sqrt((x[i + 1] - x[i])**2 + (y[i + 1] - y[i])**2) for i in range(len(x) - 1)]需要append才能关闭多边形并计算所有边的长度。使用上面提供的点,边缘距离是:
[100.96038827183659, 67.26812023536856, 36.235341863986875, 181.22361876973983, 64.38167441127949, 157.01273833673497, 128.5496013218244, 201.0024875467963, 615.0292675962665, 195.1640335717624]发布于 2021-08-29 12:26:16
由于您有一个numpy数组,解决方案变得非常简单:
points
。
这使用了整个数组操作。
import numpy as np
points = np.array([
[[623, 284]],
[[526, 256]],
[[532, 189]],
[[504, 166]],
[[323, 175]],
[[276, 219]],
[[119, 221]],
[[ 1, 272]],
[[ 0, 473]],
[[615, 479]]])
# funny shape because OpenCV. it's a Nx1 vector of 2-channel elements
# fix that up, remove the silly dimension
points.shape = (-1, 2)
# look at the data, how it's moving the values around
following_points = np.roll(points, -1, axis=0)
# vector: difference between following point and this point
vectors = following_points - points
# length of a vector, using the L2/euclidean norm
lengths = np.linalg.norm(vectors, axis=1)
print("distance to following point:")
print(lengths)
# this is just for printing/displaying, not useful in code
print("point and distance to following point:")
print(np.hstack([points, lengths.reshape((-1, 1))]))distance to following point:
[100.96039 67.26812 36.23534 181.22362 64.38167 157.01274 128.5496 201.00249 615.02927 195.16403]-89.72609 -88.20969]
point and distance to following point:
[[623. 284. 100.96039]
[526. 256. 67.26812]
[532. 189. 36.23534]
[504. 166. 181.22362]
[323. 175. 64.38167]
[276. 219. 157.01274]
[119. 221. 128.5496 ]
[ 1. 272. 201.00249]
[ 0. 473. 615.02927]
[615. 479. 195.16403]]发布于 2021-08-25 10:25:11
有一种数学方法可以轻松地做到这一点。用2D毕达戈尔定理: A(x1,y1) B(x2,x2)
点间距离:d= sqrt( (x2-x1)^2 + (y2-y1)^2 )
作为python脚本,您可以创建如下函数:
import math
A = [1,2]
B = [3, 3]
distance = math.sqrt( (B[0] - A[0])**2 + (B[1] - A[1])**2 )https://stackoverflow.com/questions/68920958
复制相似问题