首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多边形中点间距离的计算

多边形中点间距离的计算
EN

Stack Overflow用户
提问于 2021-08-25 10:15:17
回答 3查看 864关注 0票数 1

我发现了很多关于如何计算两点之间或从一点到多边形的距离的帖子,但是我只是找不到如何计算每个边的距离。我有一个多边形,坐标是这样的:

代码语言:javascript
复制
 [[[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什么的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-08-25 10:30:28

如果点坐标存储在两个python列表xy中,那么您可以使用以下方法计算每个边的长度:

代码语言:javascript
复制
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才能关闭多边形并计算所有边的长度。使用上面提供的点,边缘距离是:

代码语言:javascript
复制
[100.96038827183659, 67.26812023536856, 36.235341863986875, 181.22361876973983, 64.38167441127949, 157.01273833673497, 128.5496013218244, 201.0024875467963, 615.0292675962665, 195.1640335717624]
票数 0
EN

Stack Overflow用户

发布于 2021-08-29 12:26:16

由于您有一个numpy数组,解决方案变得非常简单:

points

  • calculate
  • 使用“范数”计算这些向量的长度,这里是L2范数,即欧氏范数

这使用了整个数组操作。

代码语言:javascript
复制
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))]))
代码语言:javascript
复制
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]]
票数 1
EN

Stack Overflow用户

发布于 2021-08-25 10:25:11

有一种数学方法可以轻松地做到这一点。用2D毕达戈尔定理: A(x1,y1) B(x2,x2)

点间距离:d= sqrt( (x2-x1)^2 + (y2-y1)^2 )

作为python脚本,您可以创建如下函数:

代码语言:javascript
复制
import math

A = [1,2]
B = [3, 3]

distance = math.sqrt( (B[0] - A[0])**2 + (B[1] - A[1])**2 )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68920958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档