[英]How to find the nearest point to the line?
I have a point cloud stored as a numpy array.我有一个存储为 numpy 数组的点云。 There is also a line coming through that point cloud specified with two points.还有一条线穿过用两个点指定的点云。
How can I get the closest point to that line in the most optimized version?如何在最优化的版本中获得最接近该线的点?
I have calculated distance to every point one by one, but it takes to much time to calculate that and it freezes my app....我已经一一计算了到每个点的距离,但是计算它需要很长时间,并且它冻结了我的应用程序....
Please help me to optimize that;(请帮我优化它;(
This is how I have been doing it for every point:这就是我对每一点的做法:
def isectSphere(self, p0, p1, cpt):
# normalized ray direction
r_dir = np.subtract(p0, p1)
r_dir = r_dir / np.linalg.norm(r_dir)
# nearest point on the ray to the sphere
p0_cpt = np.subtract(p0, cpt)
near_pt = np.subtract(p0, r_dir * np.dot(p0_cpt, r_dir))
# distance to center point
return np.linalg.norm(np.subtract(near_pt, cpt))
After iterating that code on every point a have been taking the min out of it.在每个点上迭代该代码之后,a 一直在减少它。
In the point cloud there is around 6 000 000 points.在点云中大约有 6 000 000 个点。
You can use vectorized calculations:您可以使用矢量化计算:
Assuming p0
and p1
are of shape (m,)
and pc
is your point cloud array of shape (N, m)
, you can use np.cross
to calculate vectorized distance:假设p0
和p1
的形状为(m,)
并且pc
是形状(N, m)
的点云数组,您可以使用np.cross
来计算矢量化距离:
closest_point = pc[np.argmin(np.linalg.norm(np.cross(p1-p0, p0-pc, axisb=1), axis=1)/np.linalg.norm(p1-p0))]
This on a personal system, takes less than a second for over 6,000,000 points.在个人系统上,超过 6,000,000 点只需不到一秒的时间。
import numpy as np
def isectSphere(p0, p1, cloud):
"""
>>> isectSphere([1, 0], [3, 0], [[0, -4], [2, 3]])
1
>>> isectSphere([1, 0, 0], [3, 0, 0], [[0, -4, 0], [2, 3, 0]])
1
"""
p0 = np.asarray(p0)
p1 = np.asarray(p1)
cloud = np.asarray(cloud)
product = np.cross(cloud - p0, p1 - p0)
if product.ndim == 2:
distances = np.linalg.norm(product, axis=1)
else:
distances = np.abs(product)
return distances.argmin()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.